hls.light.mjs 712 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549
  1. function getDefaultExportFromCjs (x) {
  2. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  3. }
  4. var urlToolkit = {exports: {}};
  5. (function (module, exports) {
  6. // see https://tools.ietf.org/html/rfc1808
  7. (function (root) {
  8. var URL_REGEX =
  9. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  10. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  11. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  12. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  13. var URLToolkit = {
  14. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  15. // E.g
  16. // With opts.alwaysNormalize = false (default, spec compliant)
  17. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  18. // With opts.alwaysNormalize = true (not spec compliant)
  19. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  20. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  21. opts = opts || {};
  22. // remove any remaining space and CRLF
  23. baseURL = baseURL.trim();
  24. relativeURL = relativeURL.trim();
  25. if (!relativeURL) {
  26. // 2a) If the embedded URL is entirely empty, it inherits the
  27. // entire base URL (i.e., is set equal to the base URL)
  28. // and we are done.
  29. if (!opts.alwaysNormalize) {
  30. return baseURL;
  31. }
  32. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  33. if (!basePartsForNormalise) {
  34. throw new Error('Error trying to parse base URL.');
  35. }
  36. basePartsForNormalise.path = URLToolkit.normalizePath(
  37. basePartsForNormalise.path
  38. );
  39. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  40. }
  41. var relativeParts = URLToolkit.parseURL(relativeURL);
  42. if (!relativeParts) {
  43. throw new Error('Error trying to parse relative URL.');
  44. }
  45. if (relativeParts.scheme) {
  46. // 2b) If the embedded URL starts with a scheme name, it is
  47. // interpreted as an absolute URL and we are done.
  48. if (!opts.alwaysNormalize) {
  49. return relativeURL;
  50. }
  51. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  52. return URLToolkit.buildURLFromParts(relativeParts);
  53. }
  54. var baseParts = URLToolkit.parseURL(baseURL);
  55. if (!baseParts) {
  56. throw new Error('Error trying to parse base URL.');
  57. }
  58. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  59. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  60. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  61. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  62. baseParts.netLoc = pathParts[1];
  63. baseParts.path = pathParts[2];
  64. }
  65. if (baseParts.netLoc && !baseParts.path) {
  66. baseParts.path = '/';
  67. }
  68. var builtParts = {
  69. // 2c) Otherwise, the embedded URL inherits the scheme of
  70. // the base URL.
  71. scheme: baseParts.scheme,
  72. netLoc: relativeParts.netLoc,
  73. path: null,
  74. params: relativeParts.params,
  75. query: relativeParts.query,
  76. fragment: relativeParts.fragment,
  77. };
  78. if (!relativeParts.netLoc) {
  79. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  80. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  81. // (if any) of the base URL.
  82. builtParts.netLoc = baseParts.netLoc;
  83. // 4) If the embedded URL path is preceded by a slash "/", the
  84. // path is not relative and we skip to Step 7.
  85. if (relativeParts.path[0] !== '/') {
  86. if (!relativeParts.path) {
  87. // 5) If the embedded URL path is empty (and not preceded by a
  88. // slash), then the embedded URL inherits the base URL path
  89. builtParts.path = baseParts.path;
  90. // 5a) if the embedded URL's <params> is non-empty, we skip to
  91. // step 7; otherwise, it inherits the <params> of the base
  92. // URL (if any) and
  93. if (!relativeParts.params) {
  94. builtParts.params = baseParts.params;
  95. // 5b) if the embedded URL's <query> is non-empty, we skip to
  96. // step 7; otherwise, it inherits the <query> of the base
  97. // URL (if any) and we skip to step 7.
  98. if (!relativeParts.query) {
  99. builtParts.query = baseParts.query;
  100. }
  101. }
  102. } else {
  103. // 6) The last segment of the base URL's path (anything
  104. // following the rightmost slash "/", or the entire path if no
  105. // slash is present) is removed and the embedded URL's path is
  106. // appended in its place.
  107. var baseURLPath = baseParts.path;
  108. var newPath =
  109. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  110. relativeParts.path;
  111. builtParts.path = URLToolkit.normalizePath(newPath);
  112. }
  113. }
  114. }
  115. if (builtParts.path === null) {
  116. builtParts.path = opts.alwaysNormalize
  117. ? URLToolkit.normalizePath(relativeParts.path)
  118. : relativeParts.path;
  119. }
  120. return URLToolkit.buildURLFromParts(builtParts);
  121. },
  122. parseURL: function (url) {
  123. var parts = URL_REGEX.exec(url);
  124. if (!parts) {
  125. return null;
  126. }
  127. return {
  128. scheme: parts[1] || '',
  129. netLoc: parts[2] || '',
  130. path: parts[3] || '',
  131. params: parts[4] || '',
  132. query: parts[5] || '',
  133. fragment: parts[6] || '',
  134. };
  135. },
  136. normalizePath: function (path) {
  137. // The following operations are
  138. // then applied, in order, to the new path:
  139. // 6a) All occurrences of "./", where "." is a complete path
  140. // segment, are removed.
  141. // 6b) If the path ends with "." as a complete path segment,
  142. // that "." is removed.
  143. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  144. // 6c) All occurrences of "<segment>/../", where <segment> is a
  145. // complete path segment not equal to "..", are removed.
  146. // Removal of these path segments is performed iteratively,
  147. // removing the leftmost matching pattern on each iteration,
  148. // until no matching pattern remains.
  149. // 6d) If the path ends with "<segment>/..", where <segment> is a
  150. // complete path segment not equal to "..", that
  151. // "<segment>/.." is removed.
  152. while (
  153. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  154. ) {}
  155. return path.split('').reverse().join('');
  156. },
  157. buildURLFromParts: function (parts) {
  158. return (
  159. parts.scheme +
  160. parts.netLoc +
  161. parts.path +
  162. parts.params +
  163. parts.query +
  164. parts.fragment
  165. );
  166. },
  167. };
  168. module.exports = URLToolkit;
  169. })();
  170. } (urlToolkit));
  171. var urlToolkitExports = urlToolkit.exports;
  172. function ownKeys(e, r) {
  173. var t = Object.keys(e);
  174. if (Object.getOwnPropertySymbols) {
  175. var o = Object.getOwnPropertySymbols(e);
  176. r && (o = o.filter(function (r) {
  177. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  178. })), t.push.apply(t, o);
  179. }
  180. return t;
  181. }
  182. function _objectSpread2(e) {
  183. for (var r = 1; r < arguments.length; r++) {
  184. var t = null != arguments[r] ? arguments[r] : {};
  185. r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
  186. _defineProperty(e, r, t[r]);
  187. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  188. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  189. });
  190. }
  191. return e;
  192. }
  193. function _toPrimitive(t, r) {
  194. if ("object" != typeof t || !t) return t;
  195. var e = t[Symbol.toPrimitive];
  196. if (void 0 !== e) {
  197. var i = e.call(t, r || "default");
  198. if ("object" != typeof i) return i;
  199. throw new TypeError("@@toPrimitive must return a primitive value.");
  200. }
  201. return ("string" === r ? String : Number)(t);
  202. }
  203. function _toPropertyKey(t) {
  204. var i = _toPrimitive(t, "string");
  205. return "symbol" == typeof i ? i : String(i);
  206. }
  207. function _defineProperty(obj, key, value) {
  208. key = _toPropertyKey(key);
  209. if (key in obj) {
  210. Object.defineProperty(obj, key, {
  211. value: value,
  212. enumerable: true,
  213. configurable: true,
  214. writable: true
  215. });
  216. } else {
  217. obj[key] = value;
  218. }
  219. return obj;
  220. }
  221. function _extends() {
  222. _extends = Object.assign ? Object.assign.bind() : function (target) {
  223. for (var i = 1; i < arguments.length; i++) {
  224. var source = arguments[i];
  225. for (var key in source) {
  226. if (Object.prototype.hasOwnProperty.call(source, key)) {
  227. target[key] = source[key];
  228. }
  229. }
  230. }
  231. return target;
  232. };
  233. return _extends.apply(this, arguments);
  234. }
  235. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  236. const isFiniteNumber = Number.isFinite || function (value) {
  237. return typeof value === 'number' && isFinite(value);
  238. };
  239. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  240. const isSafeInteger = Number.isSafeInteger || function (value) {
  241. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  242. };
  243. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  244. let Events = /*#__PURE__*/function (Events) {
  245. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  246. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  247. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  248. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  249. Events["BUFFER_RESET"] = "hlsBufferReset";
  250. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  251. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  252. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  253. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  254. Events["BUFFER_EOS"] = "hlsBufferEos";
  255. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  256. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  257. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  258. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  259. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  260. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  261. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  262. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  263. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  264. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  265. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  266. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  267. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  268. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  269. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  270. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  271. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  272. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  273. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  274. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  275. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  276. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  277. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  278. Events["CUES_PARSED"] = "hlsCuesParsed";
  279. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  280. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  281. Events["FRAG_LOADING"] = "hlsFragLoading";
  282. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  283. Events["FRAG_LOADED"] = "hlsFragLoaded";
  284. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  285. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  286. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  287. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  288. Events["FRAG_PARSED"] = "hlsFragParsed";
  289. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  290. Events["FRAG_CHANGED"] = "hlsFragChanged";
  291. Events["FPS_DROP"] = "hlsFpsDrop";
  292. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  293. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  294. Events["ERROR"] = "hlsError";
  295. Events["DESTROYING"] = "hlsDestroying";
  296. Events["KEY_LOADING"] = "hlsKeyLoading";
  297. Events["KEY_LOADED"] = "hlsKeyLoaded";
  298. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  299. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  300. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  301. return Events;
  302. }({});
  303. /**
  304. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  305. */
  306. let ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  307. ErrorTypes["NETWORK_ERROR"] = "networkError";
  308. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  309. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  310. ErrorTypes["MUX_ERROR"] = "muxError";
  311. ErrorTypes["OTHER_ERROR"] = "otherError";
  312. return ErrorTypes;
  313. }({});
  314. let ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  315. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  316. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  317. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  318. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  319. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  320. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  321. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  322. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  323. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  324. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  325. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  326. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  327. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  328. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  329. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  330. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  331. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  332. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  333. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  334. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  335. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  336. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  337. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  338. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  339. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  340. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  341. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  342. ErrorDetails["FRAG_GAP"] = "fragGap";
  343. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  344. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  345. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  346. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  347. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  348. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  349. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  350. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  351. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  352. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  353. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  354. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  355. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  356. ErrorDetails["UNKNOWN"] = "unknown";
  357. return ErrorDetails;
  358. }({});
  359. const noop = function noop() {};
  360. const fakeLogger = {
  361. trace: noop,
  362. debug: noop,
  363. log: noop,
  364. warn: noop,
  365. info: noop,
  366. error: noop
  367. };
  368. let exportedLogger = fakeLogger;
  369. // let lastCallTime;
  370. // function formatMsgWithTimeInfo(type, msg) {
  371. // const now = Date.now();
  372. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  373. // lastCallTime = now;
  374. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  375. // return msg;
  376. // }
  377. function consolePrintFn(type) {
  378. const func = self.console[type];
  379. if (func) {
  380. return func.bind(self.console, `[${type}] >`);
  381. }
  382. return noop;
  383. }
  384. function exportLoggerFunctions(debugConfig, ...functions) {
  385. functions.forEach(function (type) {
  386. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  387. });
  388. }
  389. function enableLogs(debugConfig, id) {
  390. // check that console is available
  391. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  392. exportLoggerFunctions(debugConfig,
  393. // Remove out from list here to hard-disable a log-level
  394. // 'trace',
  395. 'debug', 'log', 'info', 'warn', 'error');
  396. // Some browsers don't allow to use bind on console object anyway
  397. // fallback to default if needed
  398. try {
  399. exportedLogger.log(`Debug logs enabled for "${id}" in hls.js version ${"1.5.15"}`);
  400. } catch (e) {
  401. exportedLogger = fakeLogger;
  402. }
  403. } else {
  404. exportedLogger = fakeLogger;
  405. }
  406. }
  407. const logger = exportedLogger;
  408. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  409. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  410. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  411. class AttrList {
  412. constructor(attrs) {
  413. if (typeof attrs === 'string') {
  414. attrs = AttrList.parseAttrList(attrs);
  415. }
  416. _extends(this, attrs);
  417. }
  418. get clientAttrs() {
  419. return Object.keys(this).filter(attr => attr.substring(0, 2) === 'X-');
  420. }
  421. decimalInteger(attrName) {
  422. const intValue = parseInt(this[attrName], 10);
  423. if (intValue > Number.MAX_SAFE_INTEGER) {
  424. return Infinity;
  425. }
  426. return intValue;
  427. }
  428. hexadecimalInteger(attrName) {
  429. if (this[attrName]) {
  430. let stringValue = (this[attrName] || '0x').slice(2);
  431. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  432. const value = new Uint8Array(stringValue.length / 2);
  433. for (let i = 0; i < stringValue.length / 2; i++) {
  434. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  435. }
  436. return value;
  437. } else {
  438. return null;
  439. }
  440. }
  441. hexadecimalIntegerAsNumber(attrName) {
  442. const intValue = parseInt(this[attrName], 16);
  443. if (intValue > Number.MAX_SAFE_INTEGER) {
  444. return Infinity;
  445. }
  446. return intValue;
  447. }
  448. decimalFloatingPoint(attrName) {
  449. return parseFloat(this[attrName]);
  450. }
  451. optionalFloat(attrName, defaultValue) {
  452. const value = this[attrName];
  453. return value ? parseFloat(value) : defaultValue;
  454. }
  455. enumeratedString(attrName) {
  456. return this[attrName];
  457. }
  458. bool(attrName) {
  459. return this[attrName] === 'YES';
  460. }
  461. decimalResolution(attrName) {
  462. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  463. if (res === null) {
  464. return undefined;
  465. }
  466. return {
  467. width: parseInt(res[1], 10),
  468. height: parseInt(res[2], 10)
  469. };
  470. }
  471. static parseAttrList(input) {
  472. let match;
  473. const attrs = {};
  474. const quote = '"';
  475. ATTR_LIST_REGEX.lastIndex = 0;
  476. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  477. let value = match[2];
  478. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  479. value = value.slice(1, -1);
  480. }
  481. const name = match[1].trim();
  482. attrs[name] = value;
  483. }
  484. return attrs;
  485. }
  486. }
  487. // Avoid exporting const enum so that these values can be inlined
  488. function isDateRangeCueAttribute(attrName) {
  489. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  490. }
  491. function isSCTE35Attribute(attrName) {
  492. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN";
  493. }
  494. class DateRange {
  495. constructor(dateRangeAttr, dateRangeWithSameId) {
  496. this.attr = void 0;
  497. this._startDate = void 0;
  498. this._endDate = void 0;
  499. this._badValueForSameId = void 0;
  500. if (dateRangeWithSameId) {
  501. const previousAttr = dateRangeWithSameId.attr;
  502. for (const key in previousAttr) {
  503. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  504. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  505. this._badValueForSameId = key;
  506. break;
  507. }
  508. }
  509. // Merge DateRange tags with the same ID
  510. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  511. }
  512. this.attr = dateRangeAttr;
  513. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  514. if ("END-DATE" in this.attr) {
  515. const endDate = new Date(this.attr["END-DATE"]);
  516. if (isFiniteNumber(endDate.getTime())) {
  517. this._endDate = endDate;
  518. }
  519. }
  520. }
  521. get id() {
  522. return this.attr.ID;
  523. }
  524. get class() {
  525. return this.attr.CLASS;
  526. }
  527. get startDate() {
  528. return this._startDate;
  529. }
  530. get endDate() {
  531. if (this._endDate) {
  532. return this._endDate;
  533. }
  534. const duration = this.duration;
  535. if (duration !== null) {
  536. return new Date(this._startDate.getTime() + duration * 1000);
  537. }
  538. return null;
  539. }
  540. get duration() {
  541. if ("DURATION" in this.attr) {
  542. const duration = this.attr.decimalFloatingPoint("DURATION");
  543. if (isFiniteNumber(duration)) {
  544. return duration;
  545. }
  546. } else if (this._endDate) {
  547. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  548. }
  549. return null;
  550. }
  551. get plannedDuration() {
  552. if ("PLANNED-DURATION" in this.attr) {
  553. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  554. }
  555. return null;
  556. }
  557. get endOnNext() {
  558. return this.attr.bool("END-ON-NEXT");
  559. }
  560. get isValid() {
  561. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class);
  562. }
  563. }
  564. class LoadStats {
  565. constructor() {
  566. this.aborted = false;
  567. this.loaded = 0;
  568. this.retry = 0;
  569. this.total = 0;
  570. this.chunkCount = 0;
  571. this.bwEstimate = 0;
  572. this.loading = {
  573. start: 0,
  574. first: 0,
  575. end: 0
  576. };
  577. this.parsing = {
  578. start: 0,
  579. end: 0
  580. };
  581. this.buffering = {
  582. start: 0,
  583. first: 0,
  584. end: 0
  585. };
  586. }
  587. }
  588. var ElementaryStreamTypes = {
  589. AUDIO: "audio",
  590. VIDEO: "video",
  591. AUDIOVIDEO: "audiovideo"
  592. };
  593. class BaseSegment {
  594. constructor(baseurl) {
  595. this._byteRange = null;
  596. this._url = null;
  597. // baseurl is the URL to the playlist
  598. this.baseurl = void 0;
  599. // relurl is the portion of the URL that comes from inside the playlist.
  600. this.relurl = void 0;
  601. // Holds the types of data this fragment supports
  602. this.elementaryStreams = {
  603. [ElementaryStreamTypes.AUDIO]: null,
  604. [ElementaryStreamTypes.VIDEO]: null,
  605. [ElementaryStreamTypes.AUDIOVIDEO]: null
  606. };
  607. this.baseurl = baseurl;
  608. }
  609. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  610. setByteRange(value, previous) {
  611. const params = value.split('@', 2);
  612. let start;
  613. if (params.length === 1) {
  614. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  615. } else {
  616. start = parseInt(params[1]);
  617. }
  618. this._byteRange = [start, parseInt(params[0]) + start];
  619. }
  620. get byteRange() {
  621. if (!this._byteRange) {
  622. return [];
  623. }
  624. return this._byteRange;
  625. }
  626. get byteRangeStartOffset() {
  627. return this.byteRange[0];
  628. }
  629. get byteRangeEndOffset() {
  630. return this.byteRange[1];
  631. }
  632. get url() {
  633. if (!this._url && this.baseurl && this.relurl) {
  634. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  635. alwaysNormalize: true
  636. });
  637. }
  638. return this._url || '';
  639. }
  640. set url(value) {
  641. this._url = value;
  642. }
  643. }
  644. /**
  645. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  646. */
  647. class Fragment extends BaseSegment {
  648. constructor(type, baseurl) {
  649. super(baseurl);
  650. this._decryptdata = null;
  651. this.rawProgramDateTime = null;
  652. this.programDateTime = null;
  653. this.tagList = [];
  654. // EXTINF has to be present for a m3u8 to be considered valid
  655. this.duration = 0;
  656. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  657. this.sn = 0;
  658. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  659. // core difference from the private field _decryptdata is the lack of the initialized IV
  660. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  661. this.levelkeys = void 0;
  662. // A string representing the fragment type
  663. this.type = void 0;
  664. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  665. this.loader = null;
  666. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  667. this.keyLoader = null;
  668. // The level/track index to which the fragment belongs
  669. this.level = -1;
  670. // The continuity counter of the fragment
  671. this.cc = 0;
  672. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  673. this.startPTS = void 0;
  674. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  675. this.endPTS = void 0;
  676. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  677. this.startDTS = void 0;
  678. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  679. this.endDTS = void 0;
  680. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  681. this.start = 0;
  682. // Set by `updateFragPTSDTS` in level-helper
  683. this.deltaPTS = void 0;
  684. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  685. this.maxStartPTS = void 0;
  686. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  687. this.minEndPTS = void 0;
  688. // Load/parse timing information
  689. this.stats = new LoadStats();
  690. // Init Segment bytes (unset for media segments)
  691. this.data = void 0;
  692. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  693. this.bitrateTest = false;
  694. // #EXTINF segment title
  695. this.title = null;
  696. // The Media Initialization Section for this segment
  697. this.initSegment = null;
  698. // Fragment is the last fragment in the media playlist
  699. this.endList = void 0;
  700. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  701. this.gap = void 0;
  702. // Deprecated
  703. this.urlId = 0;
  704. this.type = type;
  705. }
  706. get decryptdata() {
  707. const {
  708. levelkeys
  709. } = this;
  710. if (!levelkeys && !this._decryptdata) {
  711. return null;
  712. }
  713. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  714. const key = this.levelkeys.identity;
  715. if (key) {
  716. this._decryptdata = key.getDecryptData(this.sn);
  717. } else {
  718. const keyFormats = Object.keys(this.levelkeys);
  719. if (keyFormats.length === 1) {
  720. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  721. }
  722. }
  723. }
  724. return this._decryptdata;
  725. }
  726. get end() {
  727. return this.start + this.duration;
  728. }
  729. get endProgramDateTime() {
  730. if (this.programDateTime === null) {
  731. return null;
  732. }
  733. if (!isFiniteNumber(this.programDateTime)) {
  734. return null;
  735. }
  736. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  737. return this.programDateTime + duration * 1000;
  738. }
  739. get encrypted() {
  740. var _this$_decryptdata;
  741. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  742. // when we want the fragment to start reporting that it is encrypted.
  743. // Currently, keyFormat will only be set for identity keys
  744. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  745. return true;
  746. } else if (this.levelkeys) {
  747. const keyFormats = Object.keys(this.levelkeys);
  748. const len = keyFormats.length;
  749. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  750. return true;
  751. }
  752. }
  753. return false;
  754. }
  755. setKeyFormat(keyFormat) {
  756. if (this.levelkeys) {
  757. const key = this.levelkeys[keyFormat];
  758. if (key && !this._decryptdata) {
  759. this._decryptdata = key.getDecryptData(this.sn);
  760. }
  761. }
  762. }
  763. abortRequests() {
  764. var _this$loader, _this$keyLoader;
  765. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  766. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  767. }
  768. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  769. const {
  770. elementaryStreams
  771. } = this;
  772. const info = elementaryStreams[type];
  773. if (!info) {
  774. elementaryStreams[type] = {
  775. startPTS,
  776. endPTS,
  777. startDTS,
  778. endDTS,
  779. partial
  780. };
  781. return;
  782. }
  783. info.startPTS = Math.min(info.startPTS, startPTS);
  784. info.endPTS = Math.max(info.endPTS, endPTS);
  785. info.startDTS = Math.min(info.startDTS, startDTS);
  786. info.endDTS = Math.max(info.endDTS, endDTS);
  787. }
  788. clearElementaryStreamInfo() {
  789. const {
  790. elementaryStreams
  791. } = this;
  792. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  793. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  794. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  795. }
  796. }
  797. /**
  798. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  799. */
  800. class Part extends BaseSegment {
  801. constructor(partAttrs, frag, baseurl, index, previous) {
  802. super(baseurl);
  803. this.fragOffset = 0;
  804. this.duration = 0;
  805. this.gap = false;
  806. this.independent = false;
  807. this.relurl = void 0;
  808. this.fragment = void 0;
  809. this.index = void 0;
  810. this.stats = new LoadStats();
  811. this.duration = partAttrs.decimalFloatingPoint('DURATION');
  812. this.gap = partAttrs.bool('GAP');
  813. this.independent = partAttrs.bool('INDEPENDENT');
  814. this.relurl = partAttrs.enumeratedString('URI');
  815. this.fragment = frag;
  816. this.index = index;
  817. const byteRange = partAttrs.enumeratedString('BYTERANGE');
  818. if (byteRange) {
  819. this.setByteRange(byteRange, previous);
  820. }
  821. if (previous) {
  822. this.fragOffset = previous.fragOffset + previous.duration;
  823. }
  824. }
  825. get start() {
  826. return this.fragment.start + this.fragOffset;
  827. }
  828. get end() {
  829. return this.start + this.duration;
  830. }
  831. get loaded() {
  832. const {
  833. elementaryStreams
  834. } = this;
  835. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  836. }
  837. }
  838. const DEFAULT_TARGET_DURATION = 10;
  839. /**
  840. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  841. */
  842. class LevelDetails {
  843. constructor(baseUrl) {
  844. this.PTSKnown = false;
  845. this.alignedSliding = false;
  846. this.averagetargetduration = void 0;
  847. this.endCC = 0;
  848. this.endSN = 0;
  849. this.fragments = void 0;
  850. this.fragmentHint = void 0;
  851. this.partList = null;
  852. this.dateRanges = void 0;
  853. this.live = true;
  854. this.ageHeader = 0;
  855. this.advancedDateTime = void 0;
  856. this.updated = true;
  857. this.advanced = true;
  858. this.availabilityDelay = void 0;
  859. // Manifest reload synchronization
  860. this.misses = 0;
  861. this.startCC = 0;
  862. this.startSN = 0;
  863. this.startTimeOffset = null;
  864. this.targetduration = 0;
  865. this.totalduration = 0;
  866. this.type = null;
  867. this.url = void 0;
  868. this.m3u8 = '';
  869. this.version = null;
  870. this.canBlockReload = false;
  871. this.canSkipUntil = 0;
  872. this.canSkipDateRanges = false;
  873. this.skippedSegments = 0;
  874. this.recentlyRemovedDateranges = void 0;
  875. this.partHoldBack = 0;
  876. this.holdBack = 0;
  877. this.partTarget = 0;
  878. this.preloadHint = void 0;
  879. this.renditionReports = void 0;
  880. this.tuneInGoal = 0;
  881. this.deltaUpdateFailed = void 0;
  882. this.driftStartTime = 0;
  883. this.driftEndTime = 0;
  884. this.driftStart = 0;
  885. this.driftEnd = 0;
  886. this.encryptedFragments = void 0;
  887. this.playlistParsingError = null;
  888. this.variableList = null;
  889. this.hasVariableRefs = false;
  890. this.fragments = [];
  891. this.encryptedFragments = [];
  892. this.dateRanges = {};
  893. this.url = baseUrl;
  894. }
  895. reloaded(previous) {
  896. if (!previous) {
  897. this.advanced = true;
  898. this.updated = true;
  899. return;
  900. }
  901. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  902. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  903. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  904. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  905. if (this.updated || this.advanced) {
  906. this.misses = Math.floor(previous.misses * 0.6);
  907. } else {
  908. this.misses = previous.misses + 1;
  909. }
  910. this.availabilityDelay = previous.availabilityDelay;
  911. }
  912. get hasProgramDateTime() {
  913. if (this.fragments.length) {
  914. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  915. }
  916. return false;
  917. }
  918. get levelTargetDuration() {
  919. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  920. }
  921. get drift() {
  922. const runTime = this.driftEndTime - this.driftStartTime;
  923. if (runTime > 0) {
  924. const runDuration = this.driftEnd - this.driftStart;
  925. return runDuration * 1000 / runTime;
  926. }
  927. return 1;
  928. }
  929. get edge() {
  930. return this.partEnd || this.fragmentEnd;
  931. }
  932. get partEnd() {
  933. var _this$partList;
  934. if ((_this$partList = this.partList) != null && _this$partList.length) {
  935. return this.partList[this.partList.length - 1].end;
  936. }
  937. return this.fragmentEnd;
  938. }
  939. get fragmentEnd() {
  940. var _this$fragments;
  941. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  942. return this.fragments[this.fragments.length - 1].end;
  943. }
  944. return 0;
  945. }
  946. get age() {
  947. if (this.advancedDateTime) {
  948. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  949. }
  950. return 0;
  951. }
  952. get lastPartIndex() {
  953. var _this$partList2;
  954. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  955. return this.partList[this.partList.length - 1].index;
  956. }
  957. return -1;
  958. }
  959. get lastPartSn() {
  960. var _this$partList3;
  961. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  962. return this.partList[this.partList.length - 1].fragment.sn;
  963. }
  964. return this.endSN;
  965. }
  966. }
  967. // This file is inserted as a shim for modules which we do not want to include into the distro.
  968. // This replacement is done in the "alias" plugin of the rollup config.
  969. // Use a ES dedicated file as Rollup assigns an object in the output
  970. // For example: "var KeySystemFormats = emptyEs.KeySystemFormats;"
  971. var emptyEs = {};
  972. var Cues = /*@__PURE__*/getDefaultExportFromCjs(emptyEs);
  973. function sliceUint8(array, start, end) {
  974. // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
  975. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
  976. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
  977. }
  978. // breaking up those two types in order to clarify what is happening in the decoding path.
  979. /**
  980. * Returns true if an ID3 header can be found at offset in data
  981. * @param data - The data to search
  982. * @param offset - The offset at which to start searching
  983. */
  984. const isHeader$2 = (data, offset) => {
  985. /*
  986. * http://id3.org/id3v2.3.0
  987. * [0] = 'I'
  988. * [1] = 'D'
  989. * [2] = '3'
  990. * [3,4] = {Version}
  991. * [5] = {Flags}
  992. * [6-9] = {ID3 Size}
  993. *
  994. * An ID3v2 tag can be detected with the following pattern:
  995. * $49 44 33 yy yy xx zz zz zz zz
  996. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  997. */
  998. if (offset + 10 <= data.length) {
  999. // look for 'ID3' identifier
  1000. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  1001. // check version is within range
  1002. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1003. // check size is within range
  1004. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1005. return true;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return false;
  1011. };
  1012. /**
  1013. * Returns true if an ID3 footer can be found at offset in data
  1014. * @param data - The data to search
  1015. * @param offset - The offset at which to start searching
  1016. */
  1017. const isFooter = (data, offset) => {
  1018. /*
  1019. * The footer is a copy of the header, but with a different identifier
  1020. */
  1021. if (offset + 10 <= data.length) {
  1022. // look for '3DI' identifier
  1023. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  1024. // check version is within range
  1025. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1026. // check size is within range
  1027. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1028. return true;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. return false;
  1034. };
  1035. /**
  1036. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  1037. * @param data - The data to search in
  1038. * @param offset - The offset at which to start searching
  1039. * @returns the block of data containing any ID3 tags found
  1040. * or *undefined* if no header is found at the starting offset
  1041. */
  1042. const getID3Data = (data, offset) => {
  1043. const front = offset;
  1044. let length = 0;
  1045. while (isHeader$2(data, offset)) {
  1046. // ID3 header is 10 bytes
  1047. length += 10;
  1048. const size = readSize(data, offset + 6);
  1049. length += size;
  1050. if (isFooter(data, offset + 10)) {
  1051. // ID3 footer is 10 bytes
  1052. length += 10;
  1053. }
  1054. offset += length;
  1055. }
  1056. if (length > 0) {
  1057. return data.subarray(front, front + length);
  1058. }
  1059. return undefined;
  1060. };
  1061. const readSize = (data, offset) => {
  1062. let size = 0;
  1063. size = (data[offset] & 0x7f) << 21;
  1064. size |= (data[offset + 1] & 0x7f) << 14;
  1065. size |= (data[offset + 2] & 0x7f) << 7;
  1066. size |= data[offset + 3] & 0x7f;
  1067. return size;
  1068. };
  1069. const canParse$2 = (data, offset) => {
  1070. return isHeader$2(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
  1071. };
  1072. /**
  1073. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  1074. * @param data - Block of data containing one or more ID3 tags
  1075. */
  1076. const getTimeStamp = data => {
  1077. const frames = getID3Frames(data);
  1078. for (let i = 0; i < frames.length; i++) {
  1079. const frame = frames[i];
  1080. if (isTimeStampFrame(frame)) {
  1081. return readTimeStamp(frame);
  1082. }
  1083. }
  1084. return undefined;
  1085. };
  1086. /**
  1087. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  1088. */
  1089. const isTimeStampFrame = frame => {
  1090. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  1091. };
  1092. const getFrameData = data => {
  1093. /*
  1094. Frame ID $xx xx xx xx (four characters)
  1095. Size $xx xx xx xx
  1096. Flags $xx xx
  1097. */
  1098. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  1099. const size = readSize(data, 4);
  1100. // skip frame id, size, and flags
  1101. const offset = 10;
  1102. return {
  1103. type,
  1104. size,
  1105. data: data.subarray(offset, offset + size)
  1106. };
  1107. };
  1108. /**
  1109. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  1110. * @param id3Data - The ID3 data containing one or more ID3 tags
  1111. */
  1112. const getID3Frames = id3Data => {
  1113. let offset = 0;
  1114. const frames = [];
  1115. while (isHeader$2(id3Data, offset)) {
  1116. const size = readSize(id3Data, offset + 6);
  1117. // skip past ID3 header
  1118. offset += 10;
  1119. const end = offset + size;
  1120. // loop through frames in the ID3 tag
  1121. while (offset + 8 < end) {
  1122. const frameData = getFrameData(id3Data.subarray(offset));
  1123. const frame = decodeFrame(frameData);
  1124. if (frame) {
  1125. frames.push(frame);
  1126. }
  1127. // skip frame header and frame data
  1128. offset += frameData.size + 10;
  1129. }
  1130. if (isFooter(id3Data, offset)) {
  1131. offset += 10;
  1132. }
  1133. }
  1134. return frames;
  1135. };
  1136. const decodeFrame = frame => {
  1137. if (frame.type === 'PRIV') {
  1138. return decodePrivFrame(frame);
  1139. } else if (frame.type[0] === 'W') {
  1140. return decodeURLFrame(frame);
  1141. }
  1142. return decodeTextFrame(frame);
  1143. };
  1144. const decodePrivFrame = frame => {
  1145. /*
  1146. Format: <text string>\0<binary data>
  1147. */
  1148. if (frame.size < 2) {
  1149. return undefined;
  1150. }
  1151. const owner = utf8ArrayToStr(frame.data, true);
  1152. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  1153. return {
  1154. key: frame.type,
  1155. info: owner,
  1156. data: privateData.buffer
  1157. };
  1158. };
  1159. const decodeTextFrame = frame => {
  1160. if (frame.size < 2) {
  1161. return undefined;
  1162. }
  1163. if (frame.type === 'TXXX') {
  1164. /*
  1165. Format:
  1166. [0] = {Text Encoding}
  1167. [1-?] = {Description}\0{Value}
  1168. */
  1169. let index = 1;
  1170. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1171. index += description.length + 1;
  1172. const value = utf8ArrayToStr(frame.data.subarray(index));
  1173. return {
  1174. key: frame.type,
  1175. info: description,
  1176. data: value
  1177. };
  1178. }
  1179. /*
  1180. Format:
  1181. [0] = {Text Encoding}
  1182. [1-?] = {Value}
  1183. */
  1184. const text = utf8ArrayToStr(frame.data.subarray(1));
  1185. return {
  1186. key: frame.type,
  1187. data: text
  1188. };
  1189. };
  1190. const decodeURLFrame = frame => {
  1191. if (frame.type === 'WXXX') {
  1192. /*
  1193. Format:
  1194. [0] = {Text Encoding}
  1195. [1-?] = {Description}\0{URL}
  1196. */
  1197. if (frame.size < 2) {
  1198. return undefined;
  1199. }
  1200. let index = 1;
  1201. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1202. index += description.length + 1;
  1203. const value = utf8ArrayToStr(frame.data.subarray(index));
  1204. return {
  1205. key: frame.type,
  1206. info: description,
  1207. data: value
  1208. };
  1209. }
  1210. /*
  1211. Format:
  1212. [0-?] = {URL}
  1213. */
  1214. const url = utf8ArrayToStr(frame.data);
  1215. return {
  1216. key: frame.type,
  1217. data: url
  1218. };
  1219. };
  1220. const readTimeStamp = timeStampFrame => {
  1221. if (timeStampFrame.data.byteLength === 8) {
  1222. const data = new Uint8Array(timeStampFrame.data);
  1223. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  1224. // with the upper 31 bits set to zero.
  1225. const pts33Bit = data[3] & 0x1;
  1226. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  1227. timestamp /= 45;
  1228. if (pts33Bit) {
  1229. timestamp += 47721858.84;
  1230. } // 2^32 / 90
  1231. return Math.round(timestamp);
  1232. }
  1233. return undefined;
  1234. };
  1235. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1236. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1237. /* utf.js - UTF-8 <=> UTF-16 convertion
  1238. *
  1239. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1240. * Version: 1.0
  1241. * LastModified: Dec 25 1999
  1242. * This library is free. You can redistribute it and/or modify it.
  1243. */
  1244. const utf8ArrayToStr = (array, exitOnNull = false) => {
  1245. const decoder = getTextDecoder();
  1246. if (decoder) {
  1247. const decoded = decoder.decode(array);
  1248. if (exitOnNull) {
  1249. // grab up to the first null
  1250. const idx = decoded.indexOf('\0');
  1251. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1252. }
  1253. // remove any null characters
  1254. return decoded.replace(/\0/g, '');
  1255. }
  1256. const len = array.length;
  1257. let c;
  1258. let char2;
  1259. let char3;
  1260. let out = '';
  1261. let i = 0;
  1262. while (i < len) {
  1263. c = array[i++];
  1264. if (c === 0x00 && exitOnNull) {
  1265. return out;
  1266. } else if (c === 0x00 || c === 0x03) {
  1267. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1268. continue;
  1269. }
  1270. switch (c >> 4) {
  1271. case 0:
  1272. case 1:
  1273. case 2:
  1274. case 3:
  1275. case 4:
  1276. case 5:
  1277. case 6:
  1278. case 7:
  1279. // 0xxxxxxx
  1280. out += String.fromCharCode(c);
  1281. break;
  1282. case 12:
  1283. case 13:
  1284. // 110x xxxx 10xx xxxx
  1285. char2 = array[i++];
  1286. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1287. break;
  1288. case 14:
  1289. // 1110 xxxx 10xx xxxx 10xx xxxx
  1290. char2 = array[i++];
  1291. char3 = array[i++];
  1292. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1293. break;
  1294. }
  1295. }
  1296. return out;
  1297. };
  1298. let decoder;
  1299. function getTextDecoder() {
  1300. // On Play Station 4, TextDecoder is defined but partially implemented.
  1301. // Manual decoding option is preferable
  1302. if (navigator.userAgent.includes('PlayStation 4')) {
  1303. return;
  1304. }
  1305. if (!decoder && typeof self.TextDecoder !== 'undefined') {
  1306. decoder = new self.TextDecoder('utf-8');
  1307. }
  1308. return decoder;
  1309. }
  1310. /**
  1311. * hex dump helper class
  1312. */
  1313. const Hex = {
  1314. hexDump: function (array) {
  1315. let str = '';
  1316. for (let i = 0; i < array.length; i++) {
  1317. let h = array[i].toString(16);
  1318. if (h.length < 2) {
  1319. h = '0' + h;
  1320. }
  1321. str += h;
  1322. }
  1323. return str;
  1324. }
  1325. };
  1326. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1327. const push = [].push;
  1328. // We are using fixed track IDs for driving the MP4 remuxer
  1329. // instead of following the TS PIDs.
  1330. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1331. // may not like if there are TrackID "switches"
  1332. // See https://github.com/video-dev/hls.js/issues/1331
  1333. // Here we are mapping our internal track types to constant MP4 track IDs
  1334. // With MSE currently one can only have one track of each, and we are muxing
  1335. // whatever video/audio rendition in them.
  1336. const RemuxerTrackIdConfig = {
  1337. video: 1,
  1338. audio: 2,
  1339. id3: 3,
  1340. text: 4
  1341. };
  1342. function bin2str(data) {
  1343. return String.fromCharCode.apply(null, data);
  1344. }
  1345. function readUint16(buffer, offset) {
  1346. const val = buffer[offset] << 8 | buffer[offset + 1];
  1347. return val < 0 ? 65536 + val : val;
  1348. }
  1349. function readUint32(buffer, offset) {
  1350. const val = readSint32(buffer, offset);
  1351. return val < 0 ? 4294967296 + val : val;
  1352. }
  1353. function readUint64(buffer, offset) {
  1354. let result = readUint32(buffer, offset);
  1355. result *= Math.pow(2, 32);
  1356. result += readUint32(buffer, offset + 4);
  1357. return result;
  1358. }
  1359. function readSint32(buffer, offset) {
  1360. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1361. }
  1362. function writeUint32(buffer, offset, value) {
  1363. buffer[offset] = value >> 24;
  1364. buffer[offset + 1] = value >> 16 & 0xff;
  1365. buffer[offset + 2] = value >> 8 & 0xff;
  1366. buffer[offset + 3] = value & 0xff;
  1367. }
  1368. // Find "moof" box
  1369. function hasMoofData(data) {
  1370. const end = data.byteLength;
  1371. for (let i = 0; i < end;) {
  1372. const size = readUint32(data, i);
  1373. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1374. return true;
  1375. }
  1376. i = size > 1 ? i + size : end;
  1377. }
  1378. return false;
  1379. }
  1380. // Find the data for a box specified by its path
  1381. function findBox(data, path) {
  1382. const results = [];
  1383. if (!path.length) {
  1384. // short-circuit the search for empty paths
  1385. return results;
  1386. }
  1387. const end = data.byteLength;
  1388. for (let i = 0; i < end;) {
  1389. const size = readUint32(data, i);
  1390. const type = bin2str(data.subarray(i + 4, i + 8));
  1391. const endbox = size > 1 ? i + size : end;
  1392. if (type === path[0]) {
  1393. if (path.length === 1) {
  1394. // this is the end of the path and we've found the box we were
  1395. // looking for
  1396. results.push(data.subarray(i + 8, endbox));
  1397. } else {
  1398. // recursively search for the next box along the path
  1399. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1400. if (subresults.length) {
  1401. push.apply(results, subresults);
  1402. }
  1403. }
  1404. }
  1405. i = endbox;
  1406. }
  1407. // we've finished searching all of data
  1408. return results;
  1409. }
  1410. function parseSegmentIndex(sidx) {
  1411. const references = [];
  1412. const version = sidx[0];
  1413. // set initial offset, we skip the reference ID (not needed)
  1414. let index = 8;
  1415. const timescale = readUint32(sidx, index);
  1416. index += 4;
  1417. let earliestPresentationTime = 0;
  1418. let firstOffset = 0;
  1419. if (version === 0) {
  1420. earliestPresentationTime = readUint32(sidx, index);
  1421. firstOffset = readUint32(sidx, index + 4);
  1422. index += 8;
  1423. } else {
  1424. earliestPresentationTime = readUint64(sidx, index);
  1425. firstOffset = readUint64(sidx, index + 8);
  1426. index += 16;
  1427. }
  1428. // skip reserved
  1429. index += 2;
  1430. let startByte = sidx.length + firstOffset;
  1431. const referencesCount = readUint16(sidx, index);
  1432. index += 2;
  1433. for (let i = 0; i < referencesCount; i++) {
  1434. let referenceIndex = index;
  1435. const referenceInfo = readUint32(sidx, referenceIndex);
  1436. referenceIndex += 4;
  1437. const referenceSize = referenceInfo & 0x7fffffff;
  1438. const referenceType = (referenceInfo & 0x80000000) >>> 31;
  1439. if (referenceType === 1) {
  1440. logger.warn('SIDX has hierarchical references (not supported)');
  1441. return null;
  1442. }
  1443. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1444. referenceIndex += 4;
  1445. references.push({
  1446. referenceSize,
  1447. subsegmentDuration,
  1448. // unscaled
  1449. info: {
  1450. duration: subsegmentDuration / timescale,
  1451. start: startByte,
  1452. end: startByte + referenceSize - 1
  1453. }
  1454. });
  1455. startByte += referenceSize;
  1456. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1457. // for |sapDelta|.
  1458. referenceIndex += 4;
  1459. // skip to next ref
  1460. index = referenceIndex;
  1461. }
  1462. return {
  1463. earliestPresentationTime,
  1464. timescale,
  1465. version,
  1466. referencesCount,
  1467. references
  1468. };
  1469. }
  1470. /**
  1471. * Parses an MP4 initialization segment and extracts stream type and
  1472. * timescale values for any declared tracks. Timescale values indicate the
  1473. * number of clock ticks per second to assume for time-based values
  1474. * elsewhere in the MP4.
  1475. *
  1476. * To determine the start time of an MP4, you need two pieces of
  1477. * information: the timescale unit and the earliest base media decode
  1478. * time. Multiple timescales can be specified within an MP4 but the
  1479. * base media decode time is always expressed in the timescale from
  1480. * the media header box for the track:
  1481. * ```
  1482. * moov > trak > mdia > mdhd.timescale
  1483. * moov > trak > mdia > hdlr
  1484. * ```
  1485. * @param initSegment the bytes of the init segment
  1486. * @returns a hash of track type to timescale values or null if
  1487. * the init segment is malformed.
  1488. */
  1489. function parseInitSegment(initSegment) {
  1490. const result = [];
  1491. const traks = findBox(initSegment, ['moov', 'trak']);
  1492. for (let i = 0; i < traks.length; i++) {
  1493. const trak = traks[i];
  1494. const tkhd = findBox(trak, ['tkhd'])[0];
  1495. if (tkhd) {
  1496. let version = tkhd[0];
  1497. const trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1498. const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1499. if (mdhd) {
  1500. version = mdhd[0];
  1501. const timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1502. const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1503. if (hdlr) {
  1504. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1505. const type = {
  1506. soun: ElementaryStreamTypes.AUDIO,
  1507. vide: ElementaryStreamTypes.VIDEO
  1508. }[hdlrType];
  1509. if (type) {
  1510. // Parse codec details
  1511. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1512. const stsdData = parseStsd(stsd);
  1513. result[trackId] = {
  1514. timescale,
  1515. type
  1516. };
  1517. result[type] = _objectSpread2({
  1518. timescale,
  1519. id: trackId
  1520. }, stsdData);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. }
  1526. const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1527. trex.forEach(trex => {
  1528. const trackId = readUint32(trex, 4);
  1529. const track = result[trackId];
  1530. if (track) {
  1531. track.default = {
  1532. duration: readUint32(trex, 12),
  1533. flags: readUint32(trex, 20)
  1534. };
  1535. }
  1536. });
  1537. return result;
  1538. }
  1539. function parseStsd(stsd) {
  1540. const sampleEntries = stsd.subarray(8);
  1541. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1542. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1543. let codec = fourCC;
  1544. const encrypted = fourCC === 'enca' || fourCC === 'encv';
  1545. if (encrypted) {
  1546. const encBox = findBox(sampleEntries, [fourCC])[0];
  1547. const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1548. const sinfs = findBox(encBoxChildren, ['sinf']);
  1549. sinfs.forEach(sinf => {
  1550. const schm = findBox(sinf, ['schm'])[0];
  1551. if (schm) {
  1552. const scheme = bin2str(schm.subarray(4, 8));
  1553. if (scheme === 'cbcs' || scheme === 'cenc') {
  1554. const frma = findBox(sinf, ['frma'])[0];
  1555. if (frma) {
  1556. // for encrypted content codec fourCC will be in frma
  1557. codec = bin2str(frma);
  1558. }
  1559. }
  1560. }
  1561. });
  1562. }
  1563. switch (codec) {
  1564. case 'avc1':
  1565. case 'avc2':
  1566. case 'avc3':
  1567. case 'avc4':
  1568. {
  1569. // extract profile + compatibility + level out of avcC box
  1570. const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1571. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1572. break;
  1573. }
  1574. case 'mp4a':
  1575. {
  1576. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1577. const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1578. if (esdsBox && esdsBox.length > 12) {
  1579. let i = 4;
  1580. // ES Descriptor tag
  1581. if (esdsBox[i++] !== 0x03) {
  1582. break;
  1583. }
  1584. i = skipBERInteger(esdsBox, i);
  1585. i += 2; // skip es_id;
  1586. const flags = esdsBox[i++];
  1587. if (flags & 0x80) {
  1588. i += 2; // skip dependency es_id
  1589. }
  1590. if (flags & 0x40) {
  1591. i += esdsBox[i++]; // skip URL
  1592. }
  1593. // Decoder config descriptor
  1594. if (esdsBox[i++] !== 0x04) {
  1595. break;
  1596. }
  1597. i = skipBERInteger(esdsBox, i);
  1598. const objectType = esdsBox[i++];
  1599. if (objectType === 0x40) {
  1600. codec += '.' + toHex(objectType);
  1601. } else {
  1602. break;
  1603. }
  1604. i += 12;
  1605. // Decoder specific info
  1606. if (esdsBox[i++] !== 0x05) {
  1607. break;
  1608. }
  1609. i = skipBERInteger(esdsBox, i);
  1610. const firstByte = esdsBox[i++];
  1611. let audioObjectType = (firstByte & 0xf8) >> 3;
  1612. if (audioObjectType === 31) {
  1613. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1614. }
  1615. codec += '.' + audioObjectType;
  1616. }
  1617. break;
  1618. }
  1619. case 'hvc1':
  1620. case 'hev1':
  1621. {
  1622. const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1623. const profileByte = hvcCBox[1];
  1624. const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1625. const generalProfileIdc = profileByte & 0x1f;
  1626. const profileCompat = readUint32(hvcCBox, 2);
  1627. const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1628. const levelIDC = hvcCBox[12];
  1629. const constraintIndicator = hvcCBox.subarray(6, 12);
  1630. codec += '.' + profileSpace + generalProfileIdc;
  1631. codec += '.' + profileCompat.toString(16).toUpperCase();
  1632. codec += '.' + tierFlag + levelIDC;
  1633. let constraintString = '';
  1634. for (let i = constraintIndicator.length; i--;) {
  1635. const byte = constraintIndicator[i];
  1636. if (byte || constraintString) {
  1637. const encodedByte = byte.toString(16).toUpperCase();
  1638. constraintString = '.' + encodedByte + constraintString;
  1639. }
  1640. }
  1641. codec += constraintString;
  1642. break;
  1643. }
  1644. case 'dvh1':
  1645. case 'dvhe':
  1646. {
  1647. const dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];
  1648. const profile = dvcCBox[2] >> 1 & 0x7f;
  1649. const level = dvcCBox[2] << 5 & 0x20 | dvcCBox[3] >> 3 & 0x1f;
  1650. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);
  1651. break;
  1652. }
  1653. case 'vp09':
  1654. {
  1655. const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1656. const profile = vpcCBox[4];
  1657. const level = vpcCBox[5];
  1658. const bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1659. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  1660. break;
  1661. }
  1662. case 'av01':
  1663. {
  1664. const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1665. const profile = av1CBox[1] >>> 5;
  1666. const level = av1CBox[1] & 0x1f;
  1667. const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1668. const highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1669. const twelveBit = (av1CBox[2] & 0x20) >> 5;
  1670. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1671. const monochrome = (av1CBox[2] & 0x10) >> 4;
  1672. const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1673. const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1674. const chromaSamplePosition = av1CBox[2] & 0x03;
  1675. // TODO: parse color_description_present_flag
  1676. // default it to BT.709/limited range for now
  1677. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1678. const colorPrimaries = 1;
  1679. const transferCharacteristics = 1;
  1680. const matrixCoefficients = 1;
  1681. const videoFullRangeFlag = 0;
  1682. codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1683. break;
  1684. }
  1685. }
  1686. return {
  1687. codec,
  1688. encrypted
  1689. };
  1690. }
  1691. function skipBERInteger(bytes, i) {
  1692. const limit = i + 5;
  1693. while (bytes[i++] & 0x80 && i < limit) {}
  1694. return i;
  1695. }
  1696. function toHex(x) {
  1697. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1698. }
  1699. function addLeadingZero(num) {
  1700. return (num < 10 ? '0' : '') + num;
  1701. }
  1702. function patchEncyptionData(initSegment, decryptdata) {
  1703. if (!initSegment || !decryptdata) {
  1704. return initSegment;
  1705. }
  1706. const keyId = decryptdata.keyId;
  1707. if (keyId && decryptdata.isCommonEncryption) {
  1708. const traks = findBox(initSegment, ['moov', 'trak']);
  1709. traks.forEach(trak => {
  1710. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1711. // skip the sample entry count
  1712. const sampleEntries = stsd.subarray(8);
  1713. let encBoxes = findBox(sampleEntries, ['enca']);
  1714. const isAudio = encBoxes.length > 0;
  1715. if (!isAudio) {
  1716. encBoxes = findBox(sampleEntries, ['encv']);
  1717. }
  1718. encBoxes.forEach(enc => {
  1719. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1720. const sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1721. sinfBoxes.forEach(sinf => {
  1722. const tenc = parseSinf(sinf);
  1723. if (tenc) {
  1724. // Look for default key id (keyID offset is always 8 within the tenc box):
  1725. const tencKeyId = tenc.subarray(8, 24);
  1726. if (!tencKeyId.some(b => b !== 0)) {
  1727. logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1728. tenc.set(keyId, 8);
  1729. }
  1730. }
  1731. });
  1732. });
  1733. });
  1734. }
  1735. return initSegment;
  1736. }
  1737. function parseSinf(sinf) {
  1738. const schm = findBox(sinf, ['schm'])[0];
  1739. if (schm) {
  1740. const scheme = bin2str(schm.subarray(4, 8));
  1741. if (scheme === 'cbcs' || scheme === 'cenc') {
  1742. return findBox(sinf, ['schi', 'tenc'])[0];
  1743. }
  1744. }
  1745. return null;
  1746. }
  1747. /**
  1748. * Determine the base media decode start time, in seconds, for an MP4
  1749. * fragment. If multiple fragments are specified, the earliest time is
  1750. * returned.
  1751. *
  1752. * The base media decode time can be parsed from track fragment
  1753. * metadata:
  1754. * ```
  1755. * moof > traf > tfdt.baseMediaDecodeTime
  1756. * ```
  1757. * It requires the timescale value from the mdhd to interpret.
  1758. *
  1759. * @param initData - a hash of track type to timescale values
  1760. * @param fmp4 - the bytes of the mp4 fragment
  1761. * @returns the earliest base media decode start time for the
  1762. * fragment, in seconds
  1763. */
  1764. function getStartDTS(initData, fmp4) {
  1765. // we need info from two children of each track fragment box
  1766. return findBox(fmp4, ['moof', 'traf']).reduce((result, traf) => {
  1767. const tfdt = findBox(traf, ['tfdt'])[0];
  1768. const version = tfdt[0];
  1769. const start = findBox(traf, ['tfhd']).reduce((result, tfhd) => {
  1770. // get the track id from the tfhd
  1771. const id = readUint32(tfhd, 4);
  1772. const track = initData[id];
  1773. if (track) {
  1774. let baseTime = readUint32(tfdt, 4);
  1775. if (version === 1) {
  1776. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1777. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1778. // https://github.com/video-dev/hls.js/issues/5303
  1779. if (baseTime === UINT32_MAX$1) {
  1780. logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1781. return result;
  1782. }
  1783. baseTime *= UINT32_MAX$1 + 1;
  1784. baseTime += readUint32(tfdt, 8);
  1785. }
  1786. // assume a 90kHz clock if no timescale was specified
  1787. const scale = track.timescale || 90e3;
  1788. // convert base time to seconds
  1789. const startTime = baseTime / scale;
  1790. if (isFiniteNumber(startTime) && (result === null || startTime < result)) {
  1791. return startTime;
  1792. }
  1793. }
  1794. return result;
  1795. }, null);
  1796. if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {
  1797. return start;
  1798. }
  1799. return result;
  1800. }, null);
  1801. }
  1802. /*
  1803. For Reference:
  1804. aligned(8) class TrackFragmentHeaderBox
  1805. extends FullBox(‘tfhd’, 0, tf_flags){
  1806. unsigned int(32) track_ID;
  1807. // all the following are optional fields
  1808. unsigned int(64) base_data_offset;
  1809. unsigned int(32) sample_description_index;
  1810. unsigned int(32) default_sample_duration;
  1811. unsigned int(32) default_sample_size;
  1812. unsigned int(32) default_sample_flags
  1813. }
  1814. */
  1815. function getDuration(data, initData) {
  1816. let rawDuration = 0;
  1817. let videoDuration = 0;
  1818. let audioDuration = 0;
  1819. const trafs = findBox(data, ['moof', 'traf']);
  1820. for (let i = 0; i < trafs.length; i++) {
  1821. const traf = trafs[i];
  1822. // There is only one tfhd & trun per traf
  1823. // This is true for CMAF style content, and we should perhaps check the ftyp
  1824. // and only look for a single trun then, but for ISOBMFF we should check
  1825. // for multiple track runs.
  1826. const tfhd = findBox(traf, ['tfhd'])[0];
  1827. // get the track id from the tfhd
  1828. const id = readUint32(tfhd, 4);
  1829. const track = initData[id];
  1830. if (!track) {
  1831. continue;
  1832. }
  1833. const trackDefault = track.default;
  1834. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1835. let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
  1836. if (tfhdFlags & 0x000008) {
  1837. // 0x000008 indicates the presence of the default_sample_duration field
  1838. if (tfhdFlags & 0x000002) {
  1839. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  1840. // If present, the default_sample_duration exists at byte offset 12
  1841. sampleDuration = readUint32(tfhd, 12);
  1842. } else {
  1843. // Otherwise, the duration is at byte offset 8
  1844. sampleDuration = readUint32(tfhd, 8);
  1845. }
  1846. }
  1847. // assume a 90kHz clock if no timescale was specified
  1848. const timescale = track.timescale || 90e3;
  1849. const truns = findBox(traf, ['trun']);
  1850. for (let j = 0; j < truns.length; j++) {
  1851. rawDuration = computeRawDurationFromSamples(truns[j]);
  1852. if (!rawDuration && sampleDuration) {
  1853. const sampleCount = readUint32(truns[j], 4);
  1854. rawDuration = sampleDuration * sampleCount;
  1855. }
  1856. if (track.type === ElementaryStreamTypes.VIDEO) {
  1857. videoDuration += rawDuration / timescale;
  1858. } else if (track.type === ElementaryStreamTypes.AUDIO) {
  1859. audioDuration += rawDuration / timescale;
  1860. }
  1861. }
  1862. }
  1863. if (videoDuration === 0 && audioDuration === 0) {
  1864. // If duration samples are not available in the traf use sidx subsegment_duration
  1865. let sidxMinStart = Infinity;
  1866. let sidxMaxEnd = 0;
  1867. let sidxDuration = 0;
  1868. const sidxs = findBox(data, ['sidx']);
  1869. for (let i = 0; i < sidxs.length; i++) {
  1870. const sidx = parseSegmentIndex(sidxs[i]);
  1871. if (sidx != null && sidx.references) {
  1872. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1873. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1874. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1875. sidxDuration = sidxMaxEnd - sidxMinStart;
  1876. }
  1877. }
  1878. if (sidxDuration && isFiniteNumber(sidxDuration)) {
  1879. return sidxDuration;
  1880. }
  1881. }
  1882. if (videoDuration) {
  1883. return videoDuration;
  1884. }
  1885. return audioDuration;
  1886. }
  1887. /*
  1888. For Reference:
  1889. aligned(8) class TrackRunBox
  1890. extends FullBox(‘trun’, version, tr_flags) {
  1891. unsigned int(32) sample_count;
  1892. // the following are optional fields
  1893. signed int(32) data_offset;
  1894. unsigned int(32) first_sample_flags;
  1895. // all fields in the following array are optional
  1896. {
  1897. unsigned int(32) sample_duration;
  1898. unsigned int(32) sample_size;
  1899. unsigned int(32) sample_flags
  1900. if (version == 0)
  1901. { unsigned int(32)
  1902. else
  1903. { signed int(32)
  1904. }[ sample_count ]
  1905. }
  1906. */
  1907. function computeRawDurationFromSamples(trun) {
  1908. const flags = readUint32(trun, 0);
  1909. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  1910. // Each field is an int32, which is 4 bytes
  1911. let offset = 8;
  1912. // data-offset-present flag
  1913. if (flags & 0x000001) {
  1914. offset += 4;
  1915. }
  1916. // first-sample-flags-present flag
  1917. if (flags & 0x000004) {
  1918. offset += 4;
  1919. }
  1920. let duration = 0;
  1921. const sampleCount = readUint32(trun, 4);
  1922. for (let i = 0; i < sampleCount; i++) {
  1923. // sample-duration-present flag
  1924. if (flags & 0x000100) {
  1925. const sampleDuration = readUint32(trun, offset);
  1926. duration += sampleDuration;
  1927. offset += 4;
  1928. }
  1929. // sample-size-present flag
  1930. if (flags & 0x000200) {
  1931. offset += 4;
  1932. }
  1933. // sample-flags-present flag
  1934. if (flags & 0x000400) {
  1935. offset += 4;
  1936. }
  1937. // sample-composition-time-offsets-present flag
  1938. if (flags & 0x000800) {
  1939. offset += 4;
  1940. }
  1941. }
  1942. return duration;
  1943. }
  1944. function offsetStartDTS(initData, fmp4, timeOffset) {
  1945. findBox(fmp4, ['moof', 'traf']).forEach(traf => {
  1946. findBox(traf, ['tfhd']).forEach(tfhd => {
  1947. // get the track id from the tfhd
  1948. const id = readUint32(tfhd, 4);
  1949. const track = initData[id];
  1950. if (!track) {
  1951. return;
  1952. }
  1953. // assume a 90kHz clock if no timescale was specified
  1954. const timescale = track.timescale || 90e3;
  1955. // get the base media decode time from the tfdt
  1956. findBox(traf, ['tfdt']).forEach(tfdt => {
  1957. const version = tfdt[0];
  1958. const offset = timeOffset * timescale;
  1959. if (offset) {
  1960. let baseMediaDecodeTime = readUint32(tfdt, 4);
  1961. if (version === 0) {
  1962. baseMediaDecodeTime -= offset;
  1963. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  1964. writeUint32(tfdt, 4, baseMediaDecodeTime);
  1965. } else {
  1966. baseMediaDecodeTime *= Math.pow(2, 32);
  1967. baseMediaDecodeTime += readUint32(tfdt, 8);
  1968. baseMediaDecodeTime -= offset;
  1969. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  1970. const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
  1971. const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
  1972. writeUint32(tfdt, 4, upper);
  1973. writeUint32(tfdt, 8, lower);
  1974. }
  1975. }
  1976. });
  1977. });
  1978. });
  1979. }
  1980. // TODO: Check if the last moof+mdat pair is part of the valid range
  1981. function segmentValidRange(data) {
  1982. const segmentedRange = {
  1983. valid: null,
  1984. remainder: null
  1985. };
  1986. const moofs = findBox(data, ['moof']);
  1987. if (moofs.length < 2) {
  1988. segmentedRange.remainder = data;
  1989. return segmentedRange;
  1990. }
  1991. const last = moofs[moofs.length - 1];
  1992. // Offset by 8 bytes; findBox offsets the start by as much
  1993. segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);
  1994. segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);
  1995. return segmentedRange;
  1996. }
  1997. function appendUint8Array(data1, data2) {
  1998. const temp = new Uint8Array(data1.length + data2.length);
  1999. temp.set(data1);
  2000. temp.set(data2, data1.length);
  2001. return temp;
  2002. }
  2003. function parseSamples(timeOffset, track) {
  2004. const seiSamples = [];
  2005. const videoData = track.samples;
  2006. const timescale = track.timescale;
  2007. const trackId = track.id;
  2008. let isHEVCFlavor = false;
  2009. const moofs = findBox(videoData, ['moof']);
  2010. moofs.map(moof => {
  2011. const moofOffset = moof.byteOffset - 8;
  2012. const trafs = findBox(moof, ['traf']);
  2013. trafs.map(traf => {
  2014. // get the base media decode time from the tfdt
  2015. const baseTime = findBox(traf, ['tfdt']).map(tfdt => {
  2016. const version = tfdt[0];
  2017. let result = readUint32(tfdt, 4);
  2018. if (version === 1) {
  2019. result *= Math.pow(2, 32);
  2020. result += readUint32(tfdt, 8);
  2021. }
  2022. return result / timescale;
  2023. })[0];
  2024. if (baseTime !== undefined) {
  2025. timeOffset = baseTime;
  2026. }
  2027. return findBox(traf, ['tfhd']).map(tfhd => {
  2028. const id = readUint32(tfhd, 4);
  2029. const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2030. const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2031. const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2032. const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2033. let defaultSampleDuration = 0;
  2034. const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2035. let defaultSampleSize = 0;
  2036. const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2037. let tfhdOffset = 8;
  2038. if (id === trackId) {
  2039. if (baseDataOffsetPresent) {
  2040. tfhdOffset += 8;
  2041. }
  2042. if (sampleDescriptionIndexPresent) {
  2043. tfhdOffset += 4;
  2044. }
  2045. if (defaultSampleDurationPresent) {
  2046. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2047. tfhdOffset += 4;
  2048. }
  2049. if (defaultSampleSizePresent) {
  2050. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2051. tfhdOffset += 4;
  2052. }
  2053. if (defaultSampleFlagsPresent) {
  2054. tfhdOffset += 4;
  2055. }
  2056. if (track.type === 'video') {
  2057. isHEVCFlavor = isHEVC(track.codec);
  2058. }
  2059. findBox(traf, ['trun']).map(trun => {
  2060. const version = trun[0];
  2061. const flags = readUint32(trun, 0) & 0xffffff;
  2062. const dataOffsetPresent = (flags & 0x000001) !== 0;
  2063. let dataOffset = 0;
  2064. const firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2065. const sampleDurationPresent = (flags & 0x000100) !== 0;
  2066. let sampleDuration = 0;
  2067. const sampleSizePresent = (flags & 0x000200) !== 0;
  2068. let sampleSize = 0;
  2069. const sampleFlagsPresent = (flags & 0x000400) !== 0;
  2070. const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2071. let compositionOffset = 0;
  2072. const sampleCount = readUint32(trun, 4);
  2073. let trunOffset = 8; // past version, flags, and sample count
  2074. if (dataOffsetPresent) {
  2075. dataOffset = readUint32(trun, trunOffset);
  2076. trunOffset += 4;
  2077. }
  2078. if (firstSampleFlagsPresent) {
  2079. trunOffset += 4;
  2080. }
  2081. let sampleOffset = dataOffset + moofOffset;
  2082. for (let ix = 0; ix < sampleCount; ix++) {
  2083. if (sampleDurationPresent) {
  2084. sampleDuration = readUint32(trun, trunOffset);
  2085. trunOffset += 4;
  2086. } else {
  2087. sampleDuration = defaultSampleDuration;
  2088. }
  2089. if (sampleSizePresent) {
  2090. sampleSize = readUint32(trun, trunOffset);
  2091. trunOffset += 4;
  2092. } else {
  2093. sampleSize = defaultSampleSize;
  2094. }
  2095. if (sampleFlagsPresent) {
  2096. trunOffset += 4;
  2097. }
  2098. if (sampleCompositionOffsetsPresent) {
  2099. if (version === 0) {
  2100. compositionOffset = readUint32(trun, trunOffset);
  2101. } else {
  2102. compositionOffset = readSint32(trun, trunOffset);
  2103. }
  2104. trunOffset += 4;
  2105. }
  2106. if (track.type === ElementaryStreamTypes.VIDEO) {
  2107. let naluTotalSize = 0;
  2108. while (naluTotalSize < sampleSize) {
  2109. const naluSize = readUint32(videoData, sampleOffset);
  2110. sampleOffset += 4;
  2111. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2112. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2113. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2114. }
  2115. sampleOffset += naluSize;
  2116. naluTotalSize += naluSize + 4;
  2117. }
  2118. }
  2119. timeOffset += sampleDuration / timescale;
  2120. }
  2121. });
  2122. }
  2123. });
  2124. });
  2125. });
  2126. return seiSamples;
  2127. }
  2128. function isHEVC(codec) {
  2129. if (!codec) {
  2130. return false;
  2131. }
  2132. const delimit = codec.indexOf('.');
  2133. const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  2134. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2135. // Dolby Vision
  2136. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2137. }
  2138. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2139. if (isHEVCFlavor) {
  2140. const naluType = naluHeader >> 1 & 0x3f;
  2141. return naluType === 39 || naluType === 40;
  2142. } else {
  2143. const naluType = naluHeader & 0x1f;
  2144. return naluType === 6;
  2145. }
  2146. }
  2147. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2148. const data = discardEPB(unescapedData);
  2149. let seiPtr = 0;
  2150. // skip nal header
  2151. seiPtr += headerSize;
  2152. let payloadType = 0;
  2153. let payloadSize = 0;
  2154. let b = 0;
  2155. while (seiPtr < data.length) {
  2156. payloadType = 0;
  2157. do {
  2158. if (seiPtr >= data.length) {
  2159. break;
  2160. }
  2161. b = data[seiPtr++];
  2162. payloadType += b;
  2163. } while (b === 0xff);
  2164. // Parse payload size.
  2165. payloadSize = 0;
  2166. do {
  2167. if (seiPtr >= data.length) {
  2168. break;
  2169. }
  2170. b = data[seiPtr++];
  2171. payloadSize += b;
  2172. } while (b === 0xff);
  2173. const leftOver = data.length - seiPtr;
  2174. // Create a variable to process the payload
  2175. let payPtr = seiPtr;
  2176. // Increment the seiPtr to the end of the payload
  2177. if (payloadSize < leftOver) {
  2178. seiPtr += payloadSize;
  2179. } else if (payloadSize > leftOver) {
  2180. // Some type of corruption has happened?
  2181. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  2182. // We might be able to parse some data, but let's be safe and ignore it.
  2183. break;
  2184. }
  2185. if (payloadType === 4) {
  2186. const countryCode = data[payPtr++];
  2187. if (countryCode === 181) {
  2188. const providerCode = readUint16(data, payPtr);
  2189. payPtr += 2;
  2190. if (providerCode === 49) {
  2191. const userStructure = readUint32(data, payPtr);
  2192. payPtr += 4;
  2193. if (userStructure === 0x47413934) {
  2194. const userDataType = data[payPtr++];
  2195. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2196. if (userDataType === 3) {
  2197. const firstByte = data[payPtr++];
  2198. const totalCCs = 0x1f & firstByte;
  2199. const enabled = 0x40 & firstByte;
  2200. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2201. const byteArray = new Uint8Array(totalBytes);
  2202. if (enabled) {
  2203. byteArray[0] = firstByte;
  2204. for (let i = 1; i < totalBytes; i++) {
  2205. byteArray[i] = data[payPtr++];
  2206. }
  2207. }
  2208. samples.push({
  2209. type: userDataType,
  2210. payloadType,
  2211. pts,
  2212. bytes: byteArray
  2213. });
  2214. }
  2215. }
  2216. }
  2217. }
  2218. } else if (payloadType === 5) {
  2219. if (payloadSize > 16) {
  2220. const uuidStrArray = [];
  2221. for (let i = 0; i < 16; i++) {
  2222. const _b = data[payPtr++].toString(16);
  2223. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2224. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2225. uuidStrArray.push('-');
  2226. }
  2227. }
  2228. const length = payloadSize - 16;
  2229. const userDataBytes = new Uint8Array(length);
  2230. for (let i = 0; i < length; i++) {
  2231. userDataBytes[i] = data[payPtr++];
  2232. }
  2233. samples.push({
  2234. payloadType,
  2235. pts,
  2236. uuid: uuidStrArray.join(''),
  2237. userData: utf8ArrayToStr(userDataBytes),
  2238. userDataBytes
  2239. });
  2240. }
  2241. }
  2242. }
  2243. }
  2244. /**
  2245. * remove Emulation Prevention bytes from a RBSP
  2246. */
  2247. function discardEPB(data) {
  2248. const length = data.byteLength;
  2249. const EPBPositions = [];
  2250. let i = 1;
  2251. // Find all `Emulation Prevention Bytes`
  2252. while (i < length - 2) {
  2253. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2254. EPBPositions.push(i + 2);
  2255. i += 2;
  2256. } else {
  2257. i++;
  2258. }
  2259. }
  2260. // If no Emulation Prevention Bytes were found just return the original
  2261. // array
  2262. if (EPBPositions.length === 0) {
  2263. return data;
  2264. }
  2265. // Create a new array to hold the NAL unit data
  2266. const newLength = length - EPBPositions.length;
  2267. const newData = new Uint8Array(newLength);
  2268. let sourceIndex = 0;
  2269. for (i = 0; i < newLength; sourceIndex++, i++) {
  2270. if (sourceIndex === EPBPositions[0]) {
  2271. // Skip this byte
  2272. sourceIndex++;
  2273. // Remove this position index
  2274. EPBPositions.shift();
  2275. }
  2276. newData[i] = data[sourceIndex];
  2277. }
  2278. return newData;
  2279. }
  2280. function parseEmsg(data) {
  2281. const version = data[0];
  2282. let schemeIdUri = '';
  2283. let value = '';
  2284. let timeScale = 0;
  2285. let presentationTimeDelta = 0;
  2286. let presentationTime = 0;
  2287. let eventDuration = 0;
  2288. let id = 0;
  2289. let offset = 0;
  2290. if (version === 0) {
  2291. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2292. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2293. offset += 1;
  2294. }
  2295. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2296. offset += 1;
  2297. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2298. value += bin2str(data.subarray(offset, offset + 1));
  2299. offset += 1;
  2300. }
  2301. value += bin2str(data.subarray(offset, offset + 1));
  2302. offset += 1;
  2303. timeScale = readUint32(data, 12);
  2304. presentationTimeDelta = readUint32(data, 16);
  2305. eventDuration = readUint32(data, 20);
  2306. id = readUint32(data, 24);
  2307. offset = 28;
  2308. } else if (version === 1) {
  2309. offset += 4;
  2310. timeScale = readUint32(data, offset);
  2311. offset += 4;
  2312. const leftPresentationTime = readUint32(data, offset);
  2313. offset += 4;
  2314. const rightPresentationTime = readUint32(data, offset);
  2315. offset += 4;
  2316. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  2317. if (!isSafeInteger(presentationTime)) {
  2318. presentationTime = Number.MAX_SAFE_INTEGER;
  2319. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2320. }
  2321. eventDuration = readUint32(data, offset);
  2322. offset += 4;
  2323. id = readUint32(data, offset);
  2324. offset += 4;
  2325. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2326. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2327. offset += 1;
  2328. }
  2329. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2330. offset += 1;
  2331. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2332. value += bin2str(data.subarray(offset, offset + 1));
  2333. offset += 1;
  2334. }
  2335. value += bin2str(data.subarray(offset, offset + 1));
  2336. offset += 1;
  2337. }
  2338. const payload = data.subarray(offset, data.byteLength);
  2339. return {
  2340. schemeIdUri,
  2341. value,
  2342. timeScale,
  2343. presentationTime,
  2344. presentationTimeDelta,
  2345. eventDuration,
  2346. id,
  2347. payload
  2348. };
  2349. }
  2350. class LevelKey {
  2351. static clearKeyUriToKeyIdMap() {
  2352. }
  2353. constructor(method, uri, format, formatversions = [1], iv = null) {
  2354. this.uri = void 0;
  2355. this.method = void 0;
  2356. this.keyFormat = void 0;
  2357. this.keyFormatVersions = void 0;
  2358. this.encrypted = void 0;
  2359. this.isCommonEncryption = void 0;
  2360. this.iv = null;
  2361. this.key = null;
  2362. this.keyId = null;
  2363. this.pssh = null;
  2364. this.method = method;
  2365. this.uri = uri;
  2366. this.keyFormat = format;
  2367. this.keyFormatVersions = formatversions;
  2368. this.iv = iv;
  2369. this.encrypted = method ? method !== 'NONE' : false;
  2370. this.isCommonEncryption = this.encrypted && method !== 'AES-128';
  2371. }
  2372. isSupported() {
  2373. // If it's Segment encryption or No encryption, just select that key system
  2374. if (this.method) {
  2375. if (this.method === 'AES-128' || this.method === 'NONE') {
  2376. return true;
  2377. }
  2378. if (this.keyFormat === 'identity') {
  2379. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  2380. return this.method === 'SAMPLE-AES';
  2381. }
  2382. }
  2383. return false;
  2384. }
  2385. getDecryptData(sn) {
  2386. if (!this.encrypted || !this.uri) {
  2387. return null;
  2388. }
  2389. if (this.method === 'AES-128' && this.uri && !this.iv) {
  2390. if (typeof sn !== 'number') {
  2391. // We are fetching decryption data for a initialization segment
  2392. // If the segment was encrypted with AES-128
  2393. // It must have an IV defined. We cannot substitute the Segment Number in.
  2394. if (this.method === 'AES-128' && !this.iv) {
  2395. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  2396. }
  2397. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  2398. sn = 0;
  2399. }
  2400. const iv = createInitializationVector(sn);
  2401. const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  2402. return decryptdata;
  2403. }
  2404. {
  2405. return this;
  2406. }
  2407. }
  2408. }
  2409. function createInitializationVector(segmentNumber) {
  2410. const uint8View = new Uint8Array(16);
  2411. for (let i = 12; i < 16; i++) {
  2412. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2413. }
  2414. return uint8View;
  2415. }
  2416. /**
  2417. * MediaSource helper
  2418. */
  2419. function getMediaSource(preferManagedMediaSource = true) {
  2420. if (typeof self === 'undefined') return undefined;
  2421. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  2422. return mms || self.MediaSource || self.WebKitMediaSource;
  2423. }
  2424. function isManagedMediaSource(source) {
  2425. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  2426. }
  2427. // from http://mp4ra.org/codecs.html
  2428. // values indicate codec selection preference (lower is higher priority)
  2429. const sampleEntryCodesISO = {
  2430. audio: {
  2431. a3ds: 1,
  2432. 'ac-3': 0.95,
  2433. 'ac-4': 1,
  2434. alac: 0.9,
  2435. alaw: 1,
  2436. dra1: 1,
  2437. 'dts+': 1,
  2438. 'dts-': 1,
  2439. dtsc: 1,
  2440. dtse: 1,
  2441. dtsh: 1,
  2442. 'ec-3': 0.9,
  2443. enca: 1,
  2444. fLaC: 0.9,
  2445. // MP4-RA listed codec entry for FLAC
  2446. flac: 0.9,
  2447. // legacy browser codec name for FLAC
  2448. FLAC: 0.9,
  2449. // some manifests may list "FLAC" with Apple's tools
  2450. g719: 1,
  2451. g726: 1,
  2452. m4ae: 1,
  2453. mha1: 1,
  2454. mha2: 1,
  2455. mhm1: 1,
  2456. mhm2: 1,
  2457. mlpa: 1,
  2458. mp4a: 1,
  2459. 'raw ': 1,
  2460. Opus: 1,
  2461. opus: 1,
  2462. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2463. samr: 1,
  2464. sawb: 1,
  2465. sawp: 1,
  2466. sevc: 1,
  2467. sqcp: 1,
  2468. ssmv: 1,
  2469. twos: 1,
  2470. ulaw: 1
  2471. },
  2472. video: {
  2473. avc1: 1,
  2474. avc2: 1,
  2475. avc3: 1,
  2476. avc4: 1,
  2477. avcp: 1,
  2478. av01: 0.8,
  2479. drac: 1,
  2480. dva1: 1,
  2481. dvav: 1,
  2482. dvh1: 0.7,
  2483. dvhe: 0.7,
  2484. encv: 1,
  2485. hev1: 0.75,
  2486. hvc1: 0.75,
  2487. mjp2: 1,
  2488. mp4v: 1,
  2489. mvc1: 1,
  2490. mvc2: 1,
  2491. mvc3: 1,
  2492. mvc4: 1,
  2493. resv: 1,
  2494. rv60: 1,
  2495. s263: 1,
  2496. svc1: 1,
  2497. svc2: 1,
  2498. 'vc-1': 1,
  2499. vp08: 1,
  2500. vp09: 0.9
  2501. },
  2502. text: {
  2503. stpp: 1,
  2504. wvtt: 1
  2505. }
  2506. };
  2507. function isCodecType(codec, type) {
  2508. const typeCodes = sampleEntryCodesISO[type];
  2509. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2510. }
  2511. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2512. return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2513. }
  2514. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2515. var _MediaSource$isTypeSu;
  2516. const MediaSource = getMediaSource(preferManagedMediaSource);
  2517. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2518. }
  2519. function mimeTypeForCodec(codec, type) {
  2520. return `${type}/mp4;codecs="${codec}"`;
  2521. }
  2522. function videoCodecPreferenceValue(videoCodec) {
  2523. if (videoCodec) {
  2524. const fourCC = videoCodec.substring(0, 4);
  2525. return sampleEntryCodesISO.video[fourCC];
  2526. }
  2527. return 2;
  2528. }
  2529. function codecsSetSelectionPreferenceValue(codecSet) {
  2530. return codecSet.split(',').reduce((num, fourCC) => {
  2531. const preferenceValue = sampleEntryCodesISO.video[fourCC];
  2532. if (preferenceValue) {
  2533. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2534. }
  2535. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2536. }, 0);
  2537. }
  2538. const CODEC_COMPATIBLE_NAMES = {};
  2539. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2540. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2541. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2542. }
  2543. // Idealy fLaC and Opus would be first (spec-compliant) but
  2544. // some browsers will report that fLaC is supported then fail.
  2545. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2546. const codecsToCheck = {
  2547. flac: ['flac', 'fLaC', 'FLAC'],
  2548. opus: ['opus', 'Opus']
  2549. }[lowerCaseCodec];
  2550. for (let i = 0; i < codecsToCheck.length; i++) {
  2551. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2552. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2553. return codecsToCheck[i];
  2554. }
  2555. }
  2556. return lowerCaseCodec;
  2557. }
  2558. const AUDIO_CODEC_REGEXP = /flac|opus/i;
  2559. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2560. return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2561. }
  2562. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2563. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2564. // so use level codec is parsed codec is unavailable or incomplete
  2565. if (parsedCodec && parsedCodec !== 'mp4a') {
  2566. return parsedCodec;
  2567. }
  2568. return levelCodec ? levelCodec.split(',')[0] : levelCodec;
  2569. }
  2570. function convertAVC1ToAVCOTI(codec) {
  2571. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2572. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2573. const codecs = codec.split(',');
  2574. for (let i = 0; i < codecs.length; i++) {
  2575. const avcdata = codecs[i].split('.');
  2576. if (avcdata.length > 2) {
  2577. let result = avcdata.shift() + '.';
  2578. result += parseInt(avcdata.shift()).toString(16);
  2579. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  2580. codecs[i] = result;
  2581. }
  2582. }
  2583. return codecs.join(',');
  2584. }
  2585. 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;
  2586. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  2587. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  2588. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  2589. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  2590. /(?!#) *(\S[^\r\n]*)/.source,
  2591. // segment URI, group 3 => the URI (note newline is not eaten)
  2592. /#EXT-X-BYTERANGE:*(.+)/.source,
  2593. // next segment's byterange, group 4 => range spec (x@y)
  2594. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  2595. // next segment's program date/time group 5 => the datetime spec
  2596. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  2597. ].join('|'), 'g');
  2598. const LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(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('|'));
  2599. class M3U8Parser {
  2600. static findGroup(groups, mediaGroupId) {
  2601. for (let i = 0; i < groups.length; i++) {
  2602. const group = groups[i];
  2603. if (group.id === mediaGroupId) {
  2604. return group;
  2605. }
  2606. }
  2607. }
  2608. static resolve(url, baseUrl) {
  2609. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  2610. alwaysNormalize: true
  2611. });
  2612. }
  2613. static isMediaPlaylist(str) {
  2614. return IS_MEDIA_PLAYLIST.test(str);
  2615. }
  2616. static parseMasterPlaylist(string, baseurl) {
  2617. const hasVariableRefs = false;
  2618. const parsed = {
  2619. contentSteering: null,
  2620. levels: [],
  2621. playlistParsingError: null,
  2622. sessionData: null,
  2623. sessionKeys: null,
  2624. startTimeOffset: null,
  2625. variableList: null,
  2626. hasVariableRefs
  2627. };
  2628. const levelsWithKnownCodecs = [];
  2629. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  2630. let result;
  2631. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  2632. if (result[1]) {
  2633. var _level$unknownCodecs;
  2634. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  2635. const attrs = new AttrList(result[1]);
  2636. const uri = result[2];
  2637. const level = {
  2638. attrs,
  2639. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  2640. name: attrs.NAME,
  2641. url: M3U8Parser.resolve(uri, baseurl)
  2642. };
  2643. const resolution = attrs.decimalResolution('RESOLUTION');
  2644. if (resolution) {
  2645. level.width = resolution.width;
  2646. level.height = resolution.height;
  2647. }
  2648. setCodecs(attrs.CODECS, level);
  2649. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  2650. levelsWithKnownCodecs.push(level);
  2651. }
  2652. parsed.levels.push(level);
  2653. } else if (result[3]) {
  2654. const tag = result[3];
  2655. const attributes = result[4];
  2656. switch (tag) {
  2657. case 'SESSION-DATA':
  2658. {
  2659. // #EXT-X-SESSION-DATA
  2660. const sessionAttrs = new AttrList(attributes);
  2661. const dataId = sessionAttrs['DATA-ID'];
  2662. if (dataId) {
  2663. if (parsed.sessionData === null) {
  2664. parsed.sessionData = {};
  2665. }
  2666. parsed.sessionData[dataId] = sessionAttrs;
  2667. }
  2668. break;
  2669. }
  2670. case 'SESSION-KEY':
  2671. {
  2672. // #EXT-X-SESSION-KEY
  2673. const sessionKey = parseKey(attributes, baseurl);
  2674. if (sessionKey.encrypted && sessionKey.isSupported()) {
  2675. if (parsed.sessionKeys === null) {
  2676. parsed.sessionKeys = [];
  2677. }
  2678. parsed.sessionKeys.push(sessionKey);
  2679. } else {
  2680. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  2681. }
  2682. break;
  2683. }
  2684. case 'DEFINE':
  2685. {
  2686. break;
  2687. }
  2688. case 'CONTENT-STEERING':
  2689. {
  2690. // #EXT-X-CONTENT-STEERING
  2691. const contentSteeringAttributes = new AttrList(attributes);
  2692. parsed.contentSteering = {
  2693. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  2694. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  2695. };
  2696. break;
  2697. }
  2698. case 'START':
  2699. {
  2700. // #EXT-X-START
  2701. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  2702. break;
  2703. }
  2704. }
  2705. }
  2706. }
  2707. // Filter out levels with unknown codecs if it does not remove all levels
  2708. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  2709. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  2710. if (parsed.levels.length === 0) {
  2711. parsed.playlistParsingError = new Error('no levels found in manifest');
  2712. }
  2713. return parsed;
  2714. }
  2715. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  2716. let result;
  2717. const results = {};
  2718. const levels = parsed.levels;
  2719. const groupsByType = {
  2720. AUDIO: levels.map(level => ({
  2721. id: level.attrs.AUDIO,
  2722. audioCodec: level.audioCodec
  2723. })),
  2724. SUBTITLES: levels.map(level => ({
  2725. id: level.attrs.SUBTITLES,
  2726. textCodec: level.textCodec
  2727. })),
  2728. 'CLOSED-CAPTIONS': []
  2729. };
  2730. let id = 0;
  2731. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  2732. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  2733. const attrs = new AttrList(result[1]);
  2734. const type = attrs.TYPE;
  2735. if (type) {
  2736. const groups = groupsByType[type];
  2737. const medias = results[type] || [];
  2738. results[type] = medias;
  2739. const lang = attrs.LANGUAGE;
  2740. const assocLang = attrs['ASSOC-LANGUAGE'];
  2741. const channels = attrs.CHANNELS;
  2742. const characteristics = attrs.CHARACTERISTICS;
  2743. const instreamId = attrs['INSTREAM-ID'];
  2744. const media = {
  2745. attrs,
  2746. bitrate: 0,
  2747. id: id++,
  2748. groupId: attrs['GROUP-ID'] || '',
  2749. name: attrs.NAME || lang || '',
  2750. type,
  2751. default: attrs.bool('DEFAULT'),
  2752. autoselect: attrs.bool('AUTOSELECT'),
  2753. forced: attrs.bool('FORCED'),
  2754. lang,
  2755. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  2756. };
  2757. if (assocLang) {
  2758. media.assocLang = assocLang;
  2759. }
  2760. if (channels) {
  2761. media.channels = channels;
  2762. }
  2763. if (characteristics) {
  2764. media.characteristics = characteristics;
  2765. }
  2766. if (instreamId) {
  2767. media.instreamId = instreamId;
  2768. }
  2769. if (groups != null && groups.length) {
  2770. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  2771. // If we don't find the track signalled, lets use the first audio groups codec we have
  2772. // Acting as a best guess
  2773. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  2774. assignCodec(media, groupCodec, 'audioCodec');
  2775. assignCodec(media, groupCodec, 'textCodec');
  2776. }
  2777. medias.push(media);
  2778. }
  2779. }
  2780. return results;
  2781. }
  2782. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  2783. const level = new LevelDetails(baseurl);
  2784. const fragments = level.fragments;
  2785. // The most recent init segment seen (applies to all subsequent segments)
  2786. let currentInitSegment = null;
  2787. let currentSN = 0;
  2788. let currentPart = 0;
  2789. let totalduration = 0;
  2790. let discontinuityCounter = 0;
  2791. let prevFrag = null;
  2792. let frag = new Fragment(type, baseurl);
  2793. let result;
  2794. let i;
  2795. let levelkeys;
  2796. let firstPdtIndex = -1;
  2797. let createNextFrag = false;
  2798. let nextByteRange = null;
  2799. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  2800. level.m3u8 = string;
  2801. level.hasVariableRefs = false;
  2802. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  2803. if (createNextFrag) {
  2804. createNextFrag = false;
  2805. frag = new Fragment(type, baseurl);
  2806. // setup the next fragment for part loading
  2807. frag.start = totalduration;
  2808. frag.sn = currentSN;
  2809. frag.cc = discontinuityCounter;
  2810. frag.level = id;
  2811. if (currentInitSegment) {
  2812. frag.initSegment = currentInitSegment;
  2813. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  2814. currentInitSegment.rawProgramDateTime = null;
  2815. if (nextByteRange) {
  2816. frag.setByteRange(nextByteRange);
  2817. nextByteRange = null;
  2818. }
  2819. }
  2820. }
  2821. const duration = result[1];
  2822. if (duration) {
  2823. // INF
  2824. frag.duration = parseFloat(duration);
  2825. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  2826. const title = (' ' + result[2]).slice(1);
  2827. frag.title = title || null;
  2828. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  2829. } else if (result[3]) {
  2830. // url
  2831. if (isFiniteNumber(frag.duration)) {
  2832. frag.start = totalduration;
  2833. if (levelkeys) {
  2834. setFragLevelKeys(frag, levelkeys, level);
  2835. }
  2836. frag.sn = currentSN;
  2837. frag.level = id;
  2838. frag.cc = discontinuityCounter;
  2839. fragments.push(frag);
  2840. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  2841. const uri = (' ' + result[3]).slice(1);
  2842. frag.relurl = uri;
  2843. assignProgramDateTime(frag, prevFrag);
  2844. prevFrag = frag;
  2845. totalduration += frag.duration;
  2846. currentSN++;
  2847. currentPart = 0;
  2848. createNextFrag = true;
  2849. }
  2850. } else if (result[4]) {
  2851. // X-BYTERANGE
  2852. const data = (' ' + result[4]).slice(1);
  2853. if (prevFrag) {
  2854. frag.setByteRange(data, prevFrag);
  2855. } else {
  2856. frag.setByteRange(data);
  2857. }
  2858. } else if (result[5]) {
  2859. // PROGRAM-DATE-TIME
  2860. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  2861. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  2862. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  2863. if (firstPdtIndex === -1) {
  2864. firstPdtIndex = fragments.length;
  2865. }
  2866. } else {
  2867. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  2868. if (!result) {
  2869. logger.warn('No matches on slow regex match for level playlist!');
  2870. continue;
  2871. }
  2872. for (i = 1; i < result.length; i++) {
  2873. if (typeof result[i] !== 'undefined') {
  2874. break;
  2875. }
  2876. }
  2877. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  2878. const tag = (' ' + result[i]).slice(1);
  2879. const value1 = (' ' + result[i + 1]).slice(1);
  2880. const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  2881. switch (tag) {
  2882. case 'PLAYLIST-TYPE':
  2883. level.type = value1.toUpperCase();
  2884. break;
  2885. case 'MEDIA-SEQUENCE':
  2886. currentSN = level.startSN = parseInt(value1);
  2887. break;
  2888. case 'SKIP':
  2889. {
  2890. const skipAttrs = new AttrList(value1);
  2891. const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  2892. if (isFiniteNumber(skippedSegments)) {
  2893. level.skippedSegments = skippedSegments;
  2894. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  2895. for (let _i = skippedSegments; _i--;) {
  2896. fragments.unshift(null);
  2897. }
  2898. currentSN += skippedSegments;
  2899. }
  2900. const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  2901. if (recentlyRemovedDateranges) {
  2902. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  2903. }
  2904. break;
  2905. }
  2906. case 'TARGETDURATION':
  2907. level.targetduration = Math.max(parseInt(value1), 1);
  2908. break;
  2909. case 'VERSION':
  2910. level.version = parseInt(value1);
  2911. break;
  2912. case 'INDEPENDENT-SEGMENTS':
  2913. case 'EXTM3U':
  2914. break;
  2915. case 'ENDLIST':
  2916. level.live = false;
  2917. break;
  2918. case '#':
  2919. if (value1 || value2) {
  2920. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  2921. }
  2922. break;
  2923. case 'DISCONTINUITY':
  2924. discontinuityCounter++;
  2925. frag.tagList.push(['DIS']);
  2926. break;
  2927. case 'GAP':
  2928. frag.gap = true;
  2929. frag.tagList.push([tag]);
  2930. break;
  2931. case 'BITRATE':
  2932. frag.tagList.push([tag, value1]);
  2933. break;
  2934. case 'DATERANGE':
  2935. {
  2936. const dateRangeAttr = new AttrList(value1);
  2937. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  2938. if (dateRange.isValid || level.skippedSegments) {
  2939. level.dateRanges[dateRange.id] = dateRange;
  2940. } else {
  2941. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  2942. }
  2943. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  2944. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  2945. break;
  2946. }
  2947. case 'DEFINE':
  2948. {
  2949. break;
  2950. }
  2951. case 'DISCONTINUITY-SEQUENCE':
  2952. discontinuityCounter = parseInt(value1);
  2953. break;
  2954. case 'KEY':
  2955. {
  2956. const levelKey = parseKey(value1, baseurl);
  2957. if (levelKey.isSupported()) {
  2958. if (levelKey.method === 'NONE') {
  2959. levelkeys = undefined;
  2960. break;
  2961. }
  2962. if (!levelkeys) {
  2963. levelkeys = {};
  2964. }
  2965. if (levelkeys[levelKey.keyFormat]) {
  2966. levelkeys = _extends({}, levelkeys);
  2967. }
  2968. levelkeys[levelKey.keyFormat] = levelKey;
  2969. } else {
  2970. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  2971. }
  2972. break;
  2973. }
  2974. case 'START':
  2975. level.startTimeOffset = parseStartTimeOffset(value1);
  2976. break;
  2977. case 'MAP':
  2978. {
  2979. const mapAttrs = new AttrList(value1);
  2980. if (frag.duration) {
  2981. // Initial segment tag is after segment duration tag.
  2982. // #EXTINF: 6.0
  2983. // #EXT-X-MAP:URI="init.mp4
  2984. const init = new Fragment(type, baseurl);
  2985. setInitSegment(init, mapAttrs, id, levelkeys);
  2986. currentInitSegment = init;
  2987. frag.initSegment = currentInitSegment;
  2988. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  2989. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  2990. }
  2991. } else {
  2992. // Initial segment tag is before segment duration tag
  2993. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  2994. const end = frag.byteRangeEndOffset;
  2995. if (end) {
  2996. const start = frag.byteRangeStartOffset;
  2997. nextByteRange = `${end - start}@${start}`;
  2998. } else {
  2999. nextByteRange = null;
  3000. }
  3001. setInitSegment(frag, mapAttrs, id, levelkeys);
  3002. currentInitSegment = frag;
  3003. createNextFrag = true;
  3004. }
  3005. break;
  3006. }
  3007. case 'SERVER-CONTROL':
  3008. {
  3009. const serverControlAttrs = new AttrList(value1);
  3010. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  3011. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  3012. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  3013. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  3014. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  3015. break;
  3016. }
  3017. case 'PART-INF':
  3018. {
  3019. const partInfAttrs = new AttrList(value1);
  3020. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  3021. break;
  3022. }
  3023. case 'PART':
  3024. {
  3025. let partList = level.partList;
  3026. if (!partList) {
  3027. partList = level.partList = [];
  3028. }
  3029. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  3030. const index = currentPart++;
  3031. const partAttrs = new AttrList(value1);
  3032. const part = new Part(partAttrs, frag, baseurl, index, previousFragmentPart);
  3033. partList.push(part);
  3034. frag.duration += part.duration;
  3035. break;
  3036. }
  3037. case 'PRELOAD-HINT':
  3038. {
  3039. const preloadHintAttrs = new AttrList(value1);
  3040. level.preloadHint = preloadHintAttrs;
  3041. break;
  3042. }
  3043. case 'RENDITION-REPORT':
  3044. {
  3045. const renditionReportAttrs = new AttrList(value1);
  3046. level.renditionReports = level.renditionReports || [];
  3047. level.renditionReports.push(renditionReportAttrs);
  3048. break;
  3049. }
  3050. default:
  3051. logger.warn(`line parsed but not handled: ${result}`);
  3052. break;
  3053. }
  3054. }
  3055. }
  3056. if (prevFrag && !prevFrag.relurl) {
  3057. fragments.pop();
  3058. totalduration -= prevFrag.duration;
  3059. if (level.partList) {
  3060. level.fragmentHint = prevFrag;
  3061. }
  3062. } else if (level.partList) {
  3063. assignProgramDateTime(frag, prevFrag);
  3064. frag.cc = discontinuityCounter;
  3065. level.fragmentHint = frag;
  3066. if (levelkeys) {
  3067. setFragLevelKeys(frag, levelkeys, level);
  3068. }
  3069. }
  3070. const fragmentLength = fragments.length;
  3071. const firstFragment = fragments[0];
  3072. const lastFragment = fragments[fragmentLength - 1];
  3073. totalduration += level.skippedSegments * level.targetduration;
  3074. if (totalduration > 0 && fragmentLength && lastFragment) {
  3075. level.averagetargetduration = totalduration / fragmentLength;
  3076. const lastSn = lastFragment.sn;
  3077. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  3078. if (!level.live) {
  3079. lastFragment.endList = true;
  3080. }
  3081. if (firstFragment) {
  3082. level.startCC = firstFragment.cc;
  3083. }
  3084. } else {
  3085. level.endSN = 0;
  3086. level.startCC = 0;
  3087. }
  3088. if (level.fragmentHint) {
  3089. totalduration += level.fragmentHint.duration;
  3090. }
  3091. level.totalduration = totalduration;
  3092. level.endCC = discontinuityCounter;
  3093. /**
  3094. * Backfill any missing PDT values
  3095. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  3096. * one or more Media Segment URIs, the client SHOULD extrapolate
  3097. * backward from that tag (using EXTINF durations and/or media
  3098. * timestamps) to associate dates with those segments."
  3099. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  3100. * computed.
  3101. */
  3102. if (firstPdtIndex > 0) {
  3103. backfillProgramDateTimes(fragments, firstPdtIndex);
  3104. }
  3105. return level;
  3106. }
  3107. }
  3108. function parseKey(keyTagAttributes, baseurl, parsed) {
  3109. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  3110. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  3111. const keyAttrs = new AttrList(keyTagAttributes);
  3112. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  3113. const decrypturi = keyAttrs.URI;
  3114. const decryptiv = keyAttrs.hexadecimalInteger('IV');
  3115. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  3116. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  3117. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  3118. if (decrypturi && keyAttrs.IV && !decryptiv) {
  3119. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  3120. }
  3121. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  3122. // No uri is allowed when METHOD is NONE
  3123. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  3124. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  3125. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
  3126. }
  3127. function parseStartTimeOffset(startAttributes) {
  3128. const startAttrs = new AttrList(startAttributes);
  3129. const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  3130. if (isFiniteNumber(startTimeOffset)) {
  3131. return startTimeOffset;
  3132. }
  3133. return null;
  3134. }
  3135. function setCodecs(codecsAttributeValue, level) {
  3136. let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);
  3137. ['video', 'audio', 'text'].forEach(type => {
  3138. const filtered = codecs.filter(codec => isCodecType(codec, type));
  3139. if (filtered.length) {
  3140. // Comma separated list of all codecs for type
  3141. level[`${type}Codec`] = filtered.join(',');
  3142. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  3143. codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);
  3144. }
  3145. });
  3146. level.unknownCodecs = codecs;
  3147. }
  3148. function assignCodec(media, groupItem, codecProperty) {
  3149. const codecValue = groupItem[codecProperty];
  3150. if (codecValue) {
  3151. media[codecProperty] = codecValue;
  3152. }
  3153. }
  3154. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  3155. let fragPrev = fragments[firstPdtIndex];
  3156. for (let i = firstPdtIndex; i--;) {
  3157. const frag = fragments[i];
  3158. // Exit on delta-playlist skipped segments
  3159. if (!frag) {
  3160. return;
  3161. }
  3162. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  3163. fragPrev = frag;
  3164. }
  3165. }
  3166. function assignProgramDateTime(frag, prevFrag) {
  3167. if (frag.rawProgramDateTime) {
  3168. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  3169. } else if (prevFrag != null && prevFrag.programDateTime) {
  3170. frag.programDateTime = prevFrag.endProgramDateTime;
  3171. }
  3172. if (!isFiniteNumber(frag.programDateTime)) {
  3173. frag.programDateTime = null;
  3174. frag.rawProgramDateTime = null;
  3175. }
  3176. }
  3177. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  3178. frag.relurl = mapAttrs.URI;
  3179. if (mapAttrs.BYTERANGE) {
  3180. frag.setByteRange(mapAttrs.BYTERANGE);
  3181. }
  3182. frag.level = id;
  3183. frag.sn = 'initSegment';
  3184. if (levelkeys) {
  3185. frag.levelkeys = levelkeys;
  3186. }
  3187. frag.initSegment = null;
  3188. }
  3189. function setFragLevelKeys(frag, levelkeys, level) {
  3190. frag.levelkeys = levelkeys;
  3191. const {
  3192. encryptedFragments
  3193. } = level;
  3194. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {
  3195. encryptedFragments.push(frag);
  3196. }
  3197. }
  3198. var PlaylistContextType = {
  3199. MANIFEST: "manifest",
  3200. LEVEL: "level",
  3201. AUDIO_TRACK: "audioTrack",
  3202. SUBTITLE_TRACK: "subtitleTrack"
  3203. };
  3204. var PlaylistLevelType = {
  3205. MAIN: "main",
  3206. AUDIO: "audio",
  3207. SUBTITLE: "subtitle"
  3208. };
  3209. function mapContextToLevelType(context) {
  3210. const {
  3211. type
  3212. } = context;
  3213. switch (type) {
  3214. case PlaylistContextType.AUDIO_TRACK:
  3215. return PlaylistLevelType.AUDIO;
  3216. case PlaylistContextType.SUBTITLE_TRACK:
  3217. return PlaylistLevelType.SUBTITLE;
  3218. default:
  3219. return PlaylistLevelType.MAIN;
  3220. }
  3221. }
  3222. function getResponseUrl(response, context) {
  3223. let url = response.url;
  3224. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3225. // data-uri mode also not supported (but no need to detect redirection)
  3226. if (url === undefined || url.indexOf('data:') === 0) {
  3227. // fallback to initial URL
  3228. url = context.url;
  3229. }
  3230. return url;
  3231. }
  3232. class PlaylistLoader {
  3233. constructor(hls) {
  3234. this.hls = void 0;
  3235. this.loaders = Object.create(null);
  3236. this.variableList = null;
  3237. this.hls = hls;
  3238. this.registerListeners();
  3239. }
  3240. startLoad(startPosition) {}
  3241. stopLoad() {
  3242. this.destroyInternalLoaders();
  3243. }
  3244. registerListeners() {
  3245. const {
  3246. hls
  3247. } = this;
  3248. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3249. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3250. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3251. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3252. }
  3253. unregisterListeners() {
  3254. const {
  3255. hls
  3256. } = this;
  3257. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3258. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3259. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3260. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3261. }
  3262. /**
  3263. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  3264. */
  3265. createInternalLoader(context) {
  3266. const config = this.hls.config;
  3267. const PLoader = config.pLoader;
  3268. const Loader = config.loader;
  3269. const InternalLoader = PLoader || Loader;
  3270. const loader = new InternalLoader(config);
  3271. this.loaders[context.type] = loader;
  3272. return loader;
  3273. }
  3274. getInternalLoader(context) {
  3275. return this.loaders[context.type];
  3276. }
  3277. resetInternalLoader(contextType) {
  3278. if (this.loaders[contextType]) {
  3279. delete this.loaders[contextType];
  3280. }
  3281. }
  3282. /**
  3283. * Call `destroy` on all internal loader instances mapped (one per context type)
  3284. */
  3285. destroyInternalLoaders() {
  3286. for (const contextType in this.loaders) {
  3287. const loader = this.loaders[contextType];
  3288. if (loader) {
  3289. loader.destroy();
  3290. }
  3291. this.resetInternalLoader(contextType);
  3292. }
  3293. }
  3294. destroy() {
  3295. this.variableList = null;
  3296. this.unregisterListeners();
  3297. this.destroyInternalLoaders();
  3298. }
  3299. onManifestLoading(event, data) {
  3300. const {
  3301. url
  3302. } = data;
  3303. this.variableList = null;
  3304. this.load({
  3305. id: null,
  3306. level: 0,
  3307. responseType: 'text',
  3308. type: PlaylistContextType.MANIFEST,
  3309. url,
  3310. deliveryDirectives: null
  3311. });
  3312. }
  3313. onLevelLoading(event, data) {
  3314. const {
  3315. id,
  3316. level,
  3317. pathwayId,
  3318. url,
  3319. deliveryDirectives
  3320. } = data;
  3321. this.load({
  3322. id,
  3323. level,
  3324. pathwayId,
  3325. responseType: 'text',
  3326. type: PlaylistContextType.LEVEL,
  3327. url,
  3328. deliveryDirectives
  3329. });
  3330. }
  3331. onAudioTrackLoading(event, data) {
  3332. const {
  3333. id,
  3334. groupId,
  3335. url,
  3336. deliveryDirectives
  3337. } = data;
  3338. this.load({
  3339. id,
  3340. groupId,
  3341. level: null,
  3342. responseType: 'text',
  3343. type: PlaylistContextType.AUDIO_TRACK,
  3344. url,
  3345. deliveryDirectives
  3346. });
  3347. }
  3348. onSubtitleTrackLoading(event, data) {
  3349. const {
  3350. id,
  3351. groupId,
  3352. url,
  3353. deliveryDirectives
  3354. } = data;
  3355. this.load({
  3356. id,
  3357. groupId,
  3358. level: null,
  3359. responseType: 'text',
  3360. type: PlaylistContextType.SUBTITLE_TRACK,
  3361. url,
  3362. deliveryDirectives
  3363. });
  3364. }
  3365. load(context) {
  3366. var _context$deliveryDire;
  3367. const config = this.hls.config;
  3368. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  3369. // Check if a loader for this context already exists
  3370. let loader = this.getInternalLoader(context);
  3371. if (loader) {
  3372. const loaderContext = loader.context;
  3373. if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) {
  3374. // same URL can't overlap
  3375. logger.trace('[playlist-loader]: playlist request ongoing');
  3376. return;
  3377. }
  3378. logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  3379. loader.abort();
  3380. }
  3381. // apply different configs for retries depending on
  3382. // context (manifest, level, audio/subs playlist)
  3383. let loadPolicy;
  3384. if (context.type === PlaylistContextType.MANIFEST) {
  3385. loadPolicy = config.manifestLoadPolicy.default;
  3386. } else {
  3387. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  3388. timeoutRetry: null,
  3389. errorRetry: null
  3390. });
  3391. }
  3392. loader = this.createInternalLoader(context);
  3393. // Override level/track timeout for LL-HLS requests
  3394. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  3395. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  3396. let levelDetails;
  3397. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  3398. levelDetails = this.hls.levels[context.level].details;
  3399. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  3400. levelDetails = this.hls.audioTracks[context.id].details;
  3401. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  3402. levelDetails = this.hls.subtitleTracks[context.id].details;
  3403. }
  3404. if (levelDetails) {
  3405. const partTarget = levelDetails.partTarget;
  3406. const targetDuration = levelDetails.targetduration;
  3407. if (partTarget && targetDuration) {
  3408. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  3409. loadPolicy = _extends({}, loadPolicy, {
  3410. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  3411. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  3412. });
  3413. }
  3414. }
  3415. }
  3416. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  3417. const loaderConfig = {
  3418. loadPolicy,
  3419. timeout: loadPolicy.maxLoadTimeMs,
  3420. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  3421. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  3422. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  3423. };
  3424. const loaderCallbacks = {
  3425. onSuccess: (response, stats, context, networkDetails) => {
  3426. const loader = this.getInternalLoader(context);
  3427. this.resetInternalLoader(context.type);
  3428. const string = response.data;
  3429. // Validate if it is an M3U8 at all
  3430. if (string.indexOf('#EXTM3U') !== 0) {
  3431. this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  3432. return;
  3433. }
  3434. stats.parsing.start = performance.now();
  3435. if (M3U8Parser.isMediaPlaylist(string)) {
  3436. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  3437. } else {
  3438. this.handleMasterPlaylist(response, stats, context, networkDetails);
  3439. }
  3440. },
  3441. onError: (response, context, networkDetails, stats) => {
  3442. this.handleNetworkError(context, networkDetails, false, response, stats);
  3443. },
  3444. onTimeout: (stats, context, networkDetails) => {
  3445. this.handleNetworkError(context, networkDetails, true, undefined, stats);
  3446. }
  3447. };
  3448. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  3449. loader.load(context, loaderConfig, loaderCallbacks);
  3450. }
  3451. handleMasterPlaylist(response, stats, context, networkDetails) {
  3452. const hls = this.hls;
  3453. const string = response.data;
  3454. const url = getResponseUrl(response, context);
  3455. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  3456. if (parsedResult.playlistParsingError) {
  3457. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  3458. return;
  3459. }
  3460. const {
  3461. contentSteering,
  3462. levels,
  3463. sessionData,
  3464. sessionKeys,
  3465. startTimeOffset,
  3466. variableList
  3467. } = parsedResult;
  3468. this.variableList = variableList;
  3469. const {
  3470. AUDIO: audioTracks = [],
  3471. SUBTITLES: subtitles,
  3472. 'CLOSED-CAPTIONS': captions
  3473. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  3474. if (audioTracks.length) {
  3475. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3476. const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);
  3477. // if no embedded audio track defined, but audio codec signaled in quality level,
  3478. // we need to signal this main audio track this could happen with playlists with
  3479. // alt audio rendition in which quality levels (main)
  3480. // contains both audio+video. but with mixed audio track not signaled
  3481. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3482. logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3483. audioTracks.unshift({
  3484. type: 'main',
  3485. name: 'main',
  3486. groupId: 'main',
  3487. default: false,
  3488. autoselect: false,
  3489. forced: false,
  3490. id: -1,
  3491. attrs: new AttrList({}),
  3492. bitrate: 0,
  3493. url: ''
  3494. });
  3495. }
  3496. }
  3497. hls.trigger(Events.MANIFEST_LOADED, {
  3498. levels,
  3499. audioTracks,
  3500. subtitles,
  3501. captions,
  3502. contentSteering,
  3503. url,
  3504. stats,
  3505. networkDetails,
  3506. sessionData,
  3507. sessionKeys,
  3508. startTimeOffset,
  3509. variableList
  3510. });
  3511. }
  3512. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  3513. const hls = this.hls;
  3514. const {
  3515. id,
  3516. level,
  3517. type
  3518. } = context;
  3519. const url = getResponseUrl(response, context);
  3520. const levelUrlId = 0;
  3521. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  3522. const levelType = mapContextToLevelType(context);
  3523. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList);
  3524. // We have done our first request (Manifest-type) and receive
  3525. // not a master playlist but a chunk-list (track/level)
  3526. // We fire the manifest-loaded event anyway with the parsed level-details
  3527. // by creating a single-level structure for it.
  3528. if (type === PlaylistContextType.MANIFEST) {
  3529. const singleLevel = {
  3530. attrs: new AttrList({}),
  3531. bitrate: 0,
  3532. details: levelDetails,
  3533. name: '',
  3534. url
  3535. };
  3536. hls.trigger(Events.MANIFEST_LOADED, {
  3537. levels: [singleLevel],
  3538. audioTracks: [],
  3539. url,
  3540. stats,
  3541. networkDetails,
  3542. sessionData: null,
  3543. sessionKeys: null,
  3544. contentSteering: null,
  3545. startTimeOffset: null,
  3546. variableList: null
  3547. });
  3548. }
  3549. // save parsing time
  3550. stats.parsing.end = performance.now();
  3551. // extend the context with the new levelDetails property
  3552. context.levelDetails = levelDetails;
  3553. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  3554. }
  3555. handleManifestParsingError(response, context, error, networkDetails, stats) {
  3556. this.hls.trigger(Events.ERROR, {
  3557. type: ErrorTypes.NETWORK_ERROR,
  3558. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  3559. fatal: context.type === PlaylistContextType.MANIFEST,
  3560. url: response.url,
  3561. err: error,
  3562. error,
  3563. reason: error.message,
  3564. response,
  3565. context,
  3566. networkDetails,
  3567. stats
  3568. });
  3569. }
  3570. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  3571. let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;
  3572. if (context.type === PlaylistContextType.LEVEL) {
  3573. message += `: ${context.level} id: ${context.id}`;
  3574. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  3575. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  3576. }
  3577. const error = new Error(message);
  3578. logger.warn(`[playlist-loader]: ${message}`);
  3579. let details = ErrorDetails.UNKNOWN;
  3580. let fatal = false;
  3581. const loader = this.getInternalLoader(context);
  3582. switch (context.type) {
  3583. case PlaylistContextType.MANIFEST:
  3584. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  3585. fatal = true;
  3586. break;
  3587. case PlaylistContextType.LEVEL:
  3588. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  3589. fatal = false;
  3590. break;
  3591. case PlaylistContextType.AUDIO_TRACK:
  3592. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  3593. fatal = false;
  3594. break;
  3595. case PlaylistContextType.SUBTITLE_TRACK:
  3596. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  3597. fatal = false;
  3598. break;
  3599. }
  3600. if (loader) {
  3601. this.resetInternalLoader(context.type);
  3602. }
  3603. const errorData = {
  3604. type: ErrorTypes.NETWORK_ERROR,
  3605. details,
  3606. fatal,
  3607. url: context.url,
  3608. loader,
  3609. context,
  3610. error,
  3611. networkDetails,
  3612. stats
  3613. };
  3614. if (response) {
  3615. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  3616. errorData.response = _objectSpread2({
  3617. url,
  3618. data: undefined
  3619. }, response);
  3620. }
  3621. this.hls.trigger(Events.ERROR, errorData);
  3622. }
  3623. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  3624. const hls = this.hls;
  3625. const {
  3626. type,
  3627. level,
  3628. id,
  3629. groupId,
  3630. deliveryDirectives
  3631. } = context;
  3632. const url = getResponseUrl(response, context);
  3633. const parent = mapContextToLevelType(context);
  3634. const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  3635. if (!levelDetails.fragments.length) {
  3636. const _error = new Error('No Segments found in Playlist');
  3637. hls.trigger(Events.ERROR, {
  3638. type: ErrorTypes.NETWORK_ERROR,
  3639. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  3640. fatal: false,
  3641. url,
  3642. error: _error,
  3643. reason: _error.message,
  3644. response,
  3645. context,
  3646. level: levelIndex,
  3647. parent,
  3648. networkDetails,
  3649. stats
  3650. });
  3651. return;
  3652. }
  3653. if (!levelDetails.targetduration) {
  3654. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  3655. }
  3656. const error = levelDetails.playlistParsingError;
  3657. if (error) {
  3658. hls.trigger(Events.ERROR, {
  3659. type: ErrorTypes.NETWORK_ERROR,
  3660. details: ErrorDetails.LEVEL_PARSING_ERROR,
  3661. fatal: false,
  3662. url,
  3663. error,
  3664. reason: error.message,
  3665. response,
  3666. context,
  3667. level: levelIndex,
  3668. parent,
  3669. networkDetails,
  3670. stats
  3671. });
  3672. return;
  3673. }
  3674. if (levelDetails.live && loader) {
  3675. if (loader.getCacheAge) {
  3676. levelDetails.ageHeader = loader.getCacheAge() || 0;
  3677. }
  3678. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  3679. levelDetails.ageHeader = 0;
  3680. }
  3681. }
  3682. switch (type) {
  3683. case PlaylistContextType.MANIFEST:
  3684. case PlaylistContextType.LEVEL:
  3685. hls.trigger(Events.LEVEL_LOADED, {
  3686. details: levelDetails,
  3687. level: levelIndex || 0,
  3688. id: id || 0,
  3689. stats,
  3690. networkDetails,
  3691. deliveryDirectives
  3692. });
  3693. break;
  3694. case PlaylistContextType.AUDIO_TRACK:
  3695. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  3696. details: levelDetails,
  3697. id: id || 0,
  3698. groupId: groupId || '',
  3699. stats,
  3700. networkDetails,
  3701. deliveryDirectives
  3702. });
  3703. break;
  3704. case PlaylistContextType.SUBTITLE_TRACK:
  3705. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  3706. details: levelDetails,
  3707. id: id || 0,
  3708. groupId: groupId || '',
  3709. stats,
  3710. networkDetails,
  3711. deliveryDirectives
  3712. });
  3713. break;
  3714. }
  3715. }
  3716. }
  3717. function sendAddTrackEvent(track, videoEl) {
  3718. let event;
  3719. try {
  3720. event = new Event('addtrack');
  3721. } catch (err) {
  3722. // for IE11
  3723. event = document.createEvent('Event');
  3724. event.initEvent('addtrack', false, false);
  3725. }
  3726. event.track = track;
  3727. videoEl.dispatchEvent(event);
  3728. }
  3729. function clearCurrentCues(track) {
  3730. // When track.mode is disabled, track.cues will be null.
  3731. // To guarantee the removal of cues, we need to temporarily
  3732. // change the mode to hidden
  3733. const mode = track.mode;
  3734. if (mode === 'disabled') {
  3735. track.mode = 'hidden';
  3736. }
  3737. if (track.cues) {
  3738. for (let i = track.cues.length; i--;) {
  3739. track.removeCue(track.cues[i]);
  3740. }
  3741. }
  3742. if (mode === 'disabled') {
  3743. track.mode = mode;
  3744. }
  3745. }
  3746. function removeCuesInRange(track, start, end, predicate) {
  3747. const mode = track.mode;
  3748. if (mode === 'disabled') {
  3749. track.mode = 'hidden';
  3750. }
  3751. if (track.cues && track.cues.length > 0) {
  3752. const cues = getCuesInRange(track.cues, start, end);
  3753. for (let i = 0; i < cues.length; i++) {
  3754. if (!predicate || predicate(cues[i])) {
  3755. track.removeCue(cues[i]);
  3756. }
  3757. }
  3758. }
  3759. if (mode === 'disabled') {
  3760. track.mode = mode;
  3761. }
  3762. }
  3763. // Find first cue starting after given time.
  3764. // Modified version of binary search O(log(n)).
  3765. function getFirstCueIndexAfterTime(cues, time) {
  3766. // If first cue starts after time, start there
  3767. if (time < cues[0].startTime) {
  3768. return 0;
  3769. }
  3770. // If the last cue ends before time there is no overlap
  3771. const len = cues.length - 1;
  3772. if (time > cues[len].endTime) {
  3773. return -1;
  3774. }
  3775. let left = 0;
  3776. let right = len;
  3777. while (left <= right) {
  3778. const mid = Math.floor((right + left) / 2);
  3779. if (time < cues[mid].startTime) {
  3780. right = mid - 1;
  3781. } else if (time > cues[mid].startTime && left < len) {
  3782. left = mid + 1;
  3783. } else {
  3784. // If it's not lower or higher, it must be equal.
  3785. return mid;
  3786. }
  3787. }
  3788. // At this point, left and right have swapped.
  3789. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  3790. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  3791. }
  3792. function getCuesInRange(cues, start, end) {
  3793. const cuesFound = [];
  3794. const firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  3795. if (firstCueInRange > -1) {
  3796. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  3797. const cue = cues[i];
  3798. if (cue.startTime >= start && cue.endTime <= end) {
  3799. cuesFound.push(cue);
  3800. } else if (cue.startTime > end) {
  3801. return cuesFound;
  3802. }
  3803. }
  3804. }
  3805. return cuesFound;
  3806. }
  3807. var MetadataSchema = {
  3808. audioId3: "org.id3",
  3809. dateRange: "com.apple.quicktime.HLS",
  3810. emsg: "https://aomedia.org/emsg/ID3"
  3811. };
  3812. const MIN_CUE_DURATION = 0.25;
  3813. function getCueClass() {
  3814. if (typeof self === 'undefined') return undefined;
  3815. return self.VTTCue || self.TextTrackCue;
  3816. }
  3817. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  3818. let cue = new Cue(startTime, endTime, '');
  3819. try {
  3820. cue.value = data;
  3821. if (type) {
  3822. cue.type = type;
  3823. }
  3824. } catch (e) {
  3825. cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread2({
  3826. type
  3827. }, data) : data));
  3828. }
  3829. return cue;
  3830. }
  3831. // VTTCue latest draft allows an infinite duration, fallback
  3832. // to MAX_VALUE if necessary
  3833. const MAX_CUE_ENDTIME = (() => {
  3834. const Cue = getCueClass();
  3835. try {
  3836. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  3837. } catch (e) {
  3838. return Number.MAX_VALUE;
  3839. }
  3840. return Number.POSITIVE_INFINITY;
  3841. })();
  3842. function dateRangeDateToTimelineSeconds(date, offset) {
  3843. return date.getTime() / 1000 - offset;
  3844. }
  3845. function hexToArrayBuffer(str) {
  3846. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  3847. }
  3848. class ID3TrackController {
  3849. constructor(hls) {
  3850. this.hls = void 0;
  3851. this.id3Track = null;
  3852. this.media = null;
  3853. this.dateRangeCuesAppended = {};
  3854. this.hls = hls;
  3855. this._registerListeners();
  3856. }
  3857. destroy() {
  3858. this._unregisterListeners();
  3859. this.id3Track = null;
  3860. this.media = null;
  3861. this.dateRangeCuesAppended = {};
  3862. // @ts-ignore
  3863. this.hls = null;
  3864. }
  3865. _registerListeners() {
  3866. const {
  3867. hls
  3868. } = this;
  3869. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  3870. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  3871. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3872. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  3873. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  3874. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3875. }
  3876. _unregisterListeners() {
  3877. const {
  3878. hls
  3879. } = this;
  3880. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  3881. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  3882. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3883. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  3884. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  3885. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3886. }
  3887. // Add ID3 metatadata text track.
  3888. onMediaAttached(event, data) {
  3889. this.media = data.media;
  3890. }
  3891. onMediaDetaching() {
  3892. if (!this.id3Track) {
  3893. return;
  3894. }
  3895. clearCurrentCues(this.id3Track);
  3896. this.id3Track = null;
  3897. this.media = null;
  3898. this.dateRangeCuesAppended = {};
  3899. }
  3900. onManifestLoading() {
  3901. this.dateRangeCuesAppended = {};
  3902. }
  3903. createTrack(media) {
  3904. const track = this.getID3Track(media.textTracks);
  3905. track.mode = 'hidden';
  3906. return track;
  3907. }
  3908. getID3Track(textTracks) {
  3909. if (!this.media) {
  3910. return;
  3911. }
  3912. for (let i = 0; i < textTracks.length; i++) {
  3913. const textTrack = textTracks[i];
  3914. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  3915. // send 'addtrack' when reusing the textTrack for metadata,
  3916. // same as what we do for captions
  3917. sendAddTrackEvent(textTrack, this.media);
  3918. return textTrack;
  3919. }
  3920. }
  3921. return this.media.addTextTrack('metadata', 'id3');
  3922. }
  3923. onFragParsingMetadata(event, data) {
  3924. if (!this.media) {
  3925. return;
  3926. }
  3927. const {
  3928. hls: {
  3929. config: {
  3930. enableEmsgMetadataCues,
  3931. enableID3MetadataCues
  3932. }
  3933. }
  3934. } = this;
  3935. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  3936. return;
  3937. }
  3938. const {
  3939. samples
  3940. } = data;
  3941. // create track dynamically
  3942. if (!this.id3Track) {
  3943. this.id3Track = this.createTrack(this.media);
  3944. }
  3945. const Cue = getCueClass();
  3946. if (!Cue) {
  3947. return;
  3948. }
  3949. for (let i = 0; i < samples.length; i++) {
  3950. const type = samples[i].type;
  3951. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  3952. continue;
  3953. }
  3954. const frames = getID3Frames(samples[i].data);
  3955. if (frames) {
  3956. const startTime = samples[i].pts;
  3957. let endTime = startTime + samples[i].duration;
  3958. if (endTime > MAX_CUE_ENDTIME) {
  3959. endTime = MAX_CUE_ENDTIME;
  3960. }
  3961. const timeDiff = endTime - startTime;
  3962. if (timeDiff <= 0) {
  3963. endTime = startTime + MIN_CUE_DURATION;
  3964. }
  3965. for (let j = 0; j < frames.length; j++) {
  3966. const frame = frames[j];
  3967. // Safari doesn't put the timestamp frame in the TextTrack
  3968. if (!isTimeStampFrame(frame)) {
  3969. // add a bounds to any unbounded cues
  3970. this.updateId3CueEnds(startTime, type);
  3971. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  3972. if (cue) {
  3973. this.id3Track.addCue(cue);
  3974. }
  3975. }
  3976. }
  3977. }
  3978. }
  3979. }
  3980. updateId3CueEnds(startTime, type) {
  3981. var _this$id3Track;
  3982. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  3983. if (cues) {
  3984. for (let i = cues.length; i--;) {
  3985. const cue = cues[i];
  3986. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  3987. cue.endTime = startTime;
  3988. }
  3989. }
  3990. }
  3991. }
  3992. onBufferFlushing(event, {
  3993. startOffset,
  3994. endOffset,
  3995. type
  3996. }) {
  3997. const {
  3998. id3Track,
  3999. hls
  4000. } = this;
  4001. if (!hls) {
  4002. return;
  4003. }
  4004. const {
  4005. config: {
  4006. enableEmsgMetadataCues,
  4007. enableID3MetadataCues
  4008. }
  4009. } = hls;
  4010. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4011. let predicate;
  4012. if (type === 'audio') {
  4013. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  4014. } else if (type === 'video') {
  4015. predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4016. } else {
  4017. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4018. }
  4019. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  4020. }
  4021. }
  4022. onLevelUpdated(event, {
  4023. details
  4024. }) {
  4025. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4026. return;
  4027. }
  4028. const {
  4029. dateRangeCuesAppended,
  4030. id3Track
  4031. } = this;
  4032. const {
  4033. dateRanges
  4034. } = details;
  4035. const ids = Object.keys(dateRanges);
  4036. // Remove cues from track not found in details.dateRanges
  4037. if (id3Track) {
  4038. const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));
  4039. for (let i = idsToRemove.length; i--;) {
  4040. const id = idsToRemove[i];
  4041. Object.keys(dateRangeCuesAppended[id].cues).forEach(key => {
  4042. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4043. });
  4044. delete dateRangeCuesAppended[id];
  4045. }
  4046. }
  4047. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4048. const lastFragment = details.fragments[details.fragments.length - 1];
  4049. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  4050. return;
  4051. }
  4052. if (!this.id3Track) {
  4053. this.id3Track = this.createTrack(this.media);
  4054. }
  4055. const dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4056. const Cue = getCueClass();
  4057. for (let i = 0; i < ids.length; i++) {
  4058. const id = ids[i];
  4059. const dateRange = dateRanges[id];
  4060. const startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4061. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  4062. const appendedDateRangeCues = dateRangeCuesAppended[id];
  4063. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  4064. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4065. let endTime = MAX_CUE_ENDTIME;
  4066. const endDate = dateRange.endDate;
  4067. if (endDate) {
  4068. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4069. durationKnown = true;
  4070. } else if (dateRange.endOnNext && !durationKnown) {
  4071. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {
  4072. if (id !== dateRange.id) {
  4073. const otherDateRange = dateRanges[id];
  4074. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  4075. return otherDateRange;
  4076. }
  4077. }
  4078. return candidateDateRange;
  4079. }, null);
  4080. if (nextDateRangeWithSameClass) {
  4081. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4082. durationKnown = true;
  4083. }
  4084. }
  4085. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  4086. // This is to emulate Safari HLS playback handling of DateRange tags
  4087. const attributes = Object.keys(dateRange.attr);
  4088. for (let j = 0; j < attributes.length; j++) {
  4089. const key = attributes[j];
  4090. if (!isDateRangeCueAttribute(key)) {
  4091. continue;
  4092. }
  4093. const cue = cues[key];
  4094. if (cue) {
  4095. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4096. cue.endTime = endTime;
  4097. }
  4098. } else if (Cue) {
  4099. let data = dateRange.attr[key];
  4100. if (isSCTE35Attribute(key)) {
  4101. data = hexToArrayBuffer(data);
  4102. }
  4103. const _cue = createCueWithDataFields(Cue, startTime, endTime, {
  4104. key,
  4105. data
  4106. }, MetadataSchema.dateRange);
  4107. if (_cue) {
  4108. _cue.id = id;
  4109. this.id3Track.addCue(_cue);
  4110. cues[key] = _cue;
  4111. }
  4112. }
  4113. }
  4114. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  4115. dateRangeCuesAppended[id] = {
  4116. cues,
  4117. dateRange,
  4118. durationKnown
  4119. };
  4120. }
  4121. }
  4122. }
  4123. class LatencyController {
  4124. constructor(hls) {
  4125. this.hls = void 0;
  4126. this.config = void 0;
  4127. this.media = null;
  4128. this.levelDetails = null;
  4129. this.currentTime = 0;
  4130. this.stallCount = 0;
  4131. this._latency = null;
  4132. this.timeupdateHandler = () => this.timeupdate();
  4133. this.hls = hls;
  4134. this.config = hls.config;
  4135. this.registerListeners();
  4136. }
  4137. get latency() {
  4138. return this._latency || 0;
  4139. }
  4140. get maxLatency() {
  4141. const {
  4142. config,
  4143. levelDetails
  4144. } = this;
  4145. if (config.liveMaxLatencyDuration !== undefined) {
  4146. return config.liveMaxLatencyDuration;
  4147. }
  4148. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4149. }
  4150. get targetLatency() {
  4151. const {
  4152. levelDetails
  4153. } = this;
  4154. if (levelDetails === null) {
  4155. return null;
  4156. }
  4157. const {
  4158. holdBack,
  4159. partHoldBack,
  4160. targetduration
  4161. } = levelDetails;
  4162. const {
  4163. liveSyncDuration,
  4164. liveSyncDurationCount,
  4165. lowLatencyMode
  4166. } = this.config;
  4167. const userConfig = this.hls.userConfig;
  4168. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4169. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4170. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4171. }
  4172. const maxLiveSyncOnStallIncrease = targetduration;
  4173. const liveSyncOnStallIncrease = 1.0;
  4174. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4175. }
  4176. get liveSyncPosition() {
  4177. const liveEdge = this.estimateLiveEdge();
  4178. const targetLatency = this.targetLatency;
  4179. const levelDetails = this.levelDetails;
  4180. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4181. return null;
  4182. }
  4183. const edge = levelDetails.edge;
  4184. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4185. const min = edge - levelDetails.totalduration;
  4186. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4187. return Math.min(Math.max(min, syncPosition), max);
  4188. }
  4189. get drift() {
  4190. const {
  4191. levelDetails
  4192. } = this;
  4193. if (levelDetails === null) {
  4194. return 1;
  4195. }
  4196. return levelDetails.drift;
  4197. }
  4198. get edgeStalled() {
  4199. const {
  4200. levelDetails
  4201. } = this;
  4202. if (levelDetails === null) {
  4203. return 0;
  4204. }
  4205. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4206. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4207. }
  4208. get forwardBufferLength() {
  4209. const {
  4210. media,
  4211. levelDetails
  4212. } = this;
  4213. if (!media || !levelDetails) {
  4214. return 0;
  4215. }
  4216. const bufferedRanges = media.buffered.length;
  4217. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4218. }
  4219. destroy() {
  4220. this.unregisterListeners();
  4221. this.onMediaDetaching();
  4222. this.levelDetails = null;
  4223. // @ts-ignore
  4224. this.hls = this.timeupdateHandler = null;
  4225. }
  4226. registerListeners() {
  4227. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4228. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4229. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4230. this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4231. this.hls.on(Events.ERROR, this.onError, this);
  4232. }
  4233. unregisterListeners() {
  4234. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4235. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4236. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4237. this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4238. this.hls.off(Events.ERROR, this.onError, this);
  4239. }
  4240. onMediaAttached(event, data) {
  4241. this.media = data.media;
  4242. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4243. }
  4244. onMediaDetaching() {
  4245. if (this.media) {
  4246. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4247. this.media = null;
  4248. }
  4249. }
  4250. onManifestLoading() {
  4251. this.levelDetails = null;
  4252. this._latency = null;
  4253. this.stallCount = 0;
  4254. }
  4255. onLevelUpdated(event, {
  4256. details
  4257. }) {
  4258. this.levelDetails = details;
  4259. if (details.advanced) {
  4260. this.timeupdate();
  4261. }
  4262. if (!details.live && this.media) {
  4263. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4264. }
  4265. }
  4266. onError(event, data) {
  4267. var _this$levelDetails;
  4268. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  4269. return;
  4270. }
  4271. this.stallCount++;
  4272. if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  4273. logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4274. }
  4275. }
  4276. timeupdate() {
  4277. const {
  4278. media,
  4279. levelDetails
  4280. } = this;
  4281. if (!media || !levelDetails) {
  4282. return;
  4283. }
  4284. this.currentTime = media.currentTime;
  4285. const latency = this.computeLatency();
  4286. if (latency === null) {
  4287. return;
  4288. }
  4289. this._latency = latency;
  4290. // Adapt playbackRate to meet target latency in low-latency mode
  4291. const {
  4292. lowLatencyMode,
  4293. maxLiveSyncPlaybackRate
  4294. } = this.config;
  4295. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  4296. return;
  4297. }
  4298. const targetLatency = this.targetLatency;
  4299. if (targetLatency === null) {
  4300. return;
  4301. }
  4302. const distanceFromTarget = latency - targetLatency;
  4303. // Only adjust playbackRate when within one target duration of targetLatency
  4304. // and more than one second from under-buffering.
  4305. // Playback further than one target duration from target can be considered DVR playback.
  4306. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4307. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4308. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4309. const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4310. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4311. media.playbackRate = Math.min(max, Math.max(1, rate));
  4312. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4313. media.playbackRate = 1;
  4314. }
  4315. }
  4316. estimateLiveEdge() {
  4317. const {
  4318. levelDetails
  4319. } = this;
  4320. if (levelDetails === null) {
  4321. return null;
  4322. }
  4323. return levelDetails.edge + levelDetails.age;
  4324. }
  4325. computeLatency() {
  4326. const liveEdge = this.estimateLiveEdge();
  4327. if (liveEdge === null) {
  4328. return null;
  4329. }
  4330. return liveEdge - this.currentTime;
  4331. }
  4332. }
  4333. const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  4334. function isHdcpLevel(value) {
  4335. return HdcpLevels.indexOf(value) > -1;
  4336. }
  4337. const VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  4338. function isVideoRange(value) {
  4339. return !!value && VideoRangeValues.indexOf(value) > -1;
  4340. }
  4341. var HlsSkip = {
  4342. No: "",
  4343. Yes: "YES",
  4344. v2: "v2"
  4345. };
  4346. function getSkipValue(details) {
  4347. const {
  4348. canSkipUntil,
  4349. canSkipDateRanges,
  4350. age
  4351. } = details;
  4352. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  4353. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  4354. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  4355. const playlistRecentEnough = age < canSkipUntil / 2;
  4356. if (canSkipUntil && playlistRecentEnough) {
  4357. if (canSkipDateRanges) {
  4358. return HlsSkip.v2;
  4359. }
  4360. return HlsSkip.Yes;
  4361. }
  4362. return HlsSkip.No;
  4363. }
  4364. class HlsUrlParameters {
  4365. constructor(msn, part, skip) {
  4366. this.msn = void 0;
  4367. this.part = void 0;
  4368. this.skip = void 0;
  4369. this.msn = msn;
  4370. this.part = part;
  4371. this.skip = skip;
  4372. }
  4373. addDirectives(uri) {
  4374. const url = new self.URL(uri);
  4375. if (this.msn !== undefined) {
  4376. url.searchParams.set('_HLS_msn', this.msn.toString());
  4377. }
  4378. if (this.part !== undefined) {
  4379. url.searchParams.set('_HLS_part', this.part.toString());
  4380. }
  4381. if (this.skip) {
  4382. url.searchParams.set('_HLS_skip', this.skip);
  4383. }
  4384. return url.href;
  4385. }
  4386. }
  4387. class Level {
  4388. constructor(data) {
  4389. this._attrs = void 0;
  4390. this.audioCodec = void 0;
  4391. this.bitrate = void 0;
  4392. this.codecSet = void 0;
  4393. this.url = void 0;
  4394. this.frameRate = void 0;
  4395. this.height = void 0;
  4396. this.id = void 0;
  4397. this.name = void 0;
  4398. this.videoCodec = void 0;
  4399. this.width = void 0;
  4400. this.details = void 0;
  4401. this.fragmentError = 0;
  4402. this.loadError = 0;
  4403. this.loaded = void 0;
  4404. this.realBitrate = 0;
  4405. this.supportedPromise = void 0;
  4406. this.supportedResult = void 0;
  4407. this._avgBitrate = 0;
  4408. this._audioGroups = void 0;
  4409. this._subtitleGroups = void 0;
  4410. // Deprecated (retained for backwards compatibility)
  4411. this._urlId = 0;
  4412. this.url = [data.url];
  4413. this._attrs = [data.attrs];
  4414. this.bitrate = data.bitrate;
  4415. if (data.details) {
  4416. this.details = data.details;
  4417. }
  4418. this.id = data.id || 0;
  4419. this.name = data.name;
  4420. this.width = data.width || 0;
  4421. this.height = data.height || 0;
  4422. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  4423. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  4424. this.audioCodec = data.audioCodec;
  4425. this.videoCodec = data.videoCodec;
  4426. this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');
  4427. this.addGroupId('audio', data.attrs.AUDIO);
  4428. this.addGroupId('text', data.attrs.SUBTITLES);
  4429. }
  4430. get maxBitrate() {
  4431. return Math.max(this.realBitrate, this.bitrate);
  4432. }
  4433. get averageBitrate() {
  4434. return this._avgBitrate || this.realBitrate || this.bitrate;
  4435. }
  4436. get attrs() {
  4437. return this._attrs[0];
  4438. }
  4439. get codecs() {
  4440. return this.attrs.CODECS || '';
  4441. }
  4442. get pathwayId() {
  4443. return this.attrs['PATHWAY-ID'] || '.';
  4444. }
  4445. get videoRange() {
  4446. return this.attrs['VIDEO-RANGE'] || 'SDR';
  4447. }
  4448. get score() {
  4449. return this.attrs.optionalFloat('SCORE', 0);
  4450. }
  4451. get uri() {
  4452. return this.url[0] || '';
  4453. }
  4454. hasAudioGroup(groupId) {
  4455. return hasGroup(this._audioGroups, groupId);
  4456. }
  4457. hasSubtitleGroup(groupId) {
  4458. return hasGroup(this._subtitleGroups, groupId);
  4459. }
  4460. get audioGroups() {
  4461. return this._audioGroups;
  4462. }
  4463. get subtitleGroups() {
  4464. return this._subtitleGroups;
  4465. }
  4466. addGroupId(type, groupId) {
  4467. if (!groupId) {
  4468. return;
  4469. }
  4470. if (type === 'audio') {
  4471. let audioGroups = this._audioGroups;
  4472. if (!audioGroups) {
  4473. audioGroups = this._audioGroups = [];
  4474. }
  4475. if (audioGroups.indexOf(groupId) === -1) {
  4476. audioGroups.push(groupId);
  4477. }
  4478. } else if (type === 'text') {
  4479. let subtitleGroups = this._subtitleGroups;
  4480. if (!subtitleGroups) {
  4481. subtitleGroups = this._subtitleGroups = [];
  4482. }
  4483. if (subtitleGroups.indexOf(groupId) === -1) {
  4484. subtitleGroups.push(groupId);
  4485. }
  4486. }
  4487. }
  4488. // Deprecated methods (retained for backwards compatibility)
  4489. get urlId() {
  4490. return 0;
  4491. }
  4492. set urlId(value) {}
  4493. get audioGroupIds() {
  4494. return this.audioGroups ? [this.audioGroupId] : undefined;
  4495. }
  4496. get textGroupIds() {
  4497. return this.subtitleGroups ? [this.textGroupId] : undefined;
  4498. }
  4499. get audioGroupId() {
  4500. var _this$audioGroups;
  4501. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  4502. }
  4503. get textGroupId() {
  4504. var _this$subtitleGroups;
  4505. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  4506. }
  4507. addFallback() {}
  4508. }
  4509. function hasGroup(groups, groupId) {
  4510. if (!groupId || !groups) {
  4511. return false;
  4512. }
  4513. return groups.indexOf(groupId) !== -1;
  4514. }
  4515. function updateFromToPTS(fragFrom, fragTo) {
  4516. const fragToPTS = fragTo.startPTS;
  4517. // if we know startPTS[toIdx]
  4518. if (isFiniteNumber(fragToPTS)) {
  4519. // update fragment duration.
  4520. // it helps to fix drifts between playlist reported duration and fragment real duration
  4521. let duration = 0;
  4522. let frag;
  4523. if (fragTo.sn > fragFrom.sn) {
  4524. duration = fragToPTS - fragFrom.start;
  4525. frag = fragFrom;
  4526. } else {
  4527. duration = fragFrom.start - fragToPTS;
  4528. frag = fragTo;
  4529. }
  4530. if (frag.duration !== duration) {
  4531. frag.duration = duration;
  4532. }
  4533. // we dont know startPTS[toIdx]
  4534. } else if (fragTo.sn > fragFrom.sn) {
  4535. const contiguous = fragFrom.cc === fragTo.cc;
  4536. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  4537. if (contiguous && fragFrom.minEndPTS) {
  4538. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  4539. } else {
  4540. fragTo.start = fragFrom.start + fragFrom.duration;
  4541. }
  4542. } else {
  4543. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  4544. }
  4545. }
  4546. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  4547. const parsedMediaDuration = endPTS - startPTS;
  4548. if (parsedMediaDuration <= 0) {
  4549. logger.warn('Fragment should have a positive duration', frag);
  4550. endPTS = startPTS + frag.duration;
  4551. endDTS = startDTS + frag.duration;
  4552. }
  4553. let maxStartPTS = startPTS;
  4554. let minEndPTS = endPTS;
  4555. const fragStartPts = frag.startPTS;
  4556. const fragEndPts = frag.endPTS;
  4557. if (isFiniteNumber(fragStartPts)) {
  4558. // delta PTS between audio and video
  4559. const deltaPTS = Math.abs(fragStartPts - startPTS);
  4560. if (!isFiniteNumber(frag.deltaPTS)) {
  4561. frag.deltaPTS = deltaPTS;
  4562. } else {
  4563. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  4564. }
  4565. maxStartPTS = Math.max(startPTS, fragStartPts);
  4566. startPTS = Math.min(startPTS, fragStartPts);
  4567. startDTS = Math.min(startDTS, frag.startDTS);
  4568. minEndPTS = Math.min(endPTS, fragEndPts);
  4569. endPTS = Math.max(endPTS, fragEndPts);
  4570. endDTS = Math.max(endDTS, frag.endDTS);
  4571. }
  4572. const drift = startPTS - frag.start;
  4573. if (frag.start !== 0) {
  4574. frag.start = startPTS;
  4575. }
  4576. frag.duration = endPTS - frag.start;
  4577. frag.startPTS = startPTS;
  4578. frag.maxStartPTS = maxStartPTS;
  4579. frag.startDTS = startDTS;
  4580. frag.endPTS = endPTS;
  4581. frag.minEndPTS = minEndPTS;
  4582. frag.endDTS = endDTS;
  4583. const sn = frag.sn; // 'initSegment'
  4584. // exit if sn out of range
  4585. if (!details || sn < details.startSN || sn > details.endSN) {
  4586. return 0;
  4587. }
  4588. let i;
  4589. const fragIdx = sn - details.startSN;
  4590. const fragments = details.fragments;
  4591. // update frag reference in fragments array
  4592. // rationale is that fragments array might not contain this frag object.
  4593. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  4594. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  4595. // resulting in invalid sliding computation
  4596. fragments[fragIdx] = frag;
  4597. // adjust fragment PTS/duration from seqnum-1 to frag 0
  4598. for (i = fragIdx; i > 0; i--) {
  4599. updateFromToPTS(fragments[i], fragments[i - 1]);
  4600. }
  4601. // adjust fragment PTS/duration from seqnum to last frag
  4602. for (i = fragIdx; i < fragments.length - 1; i++) {
  4603. updateFromToPTS(fragments[i], fragments[i + 1]);
  4604. }
  4605. if (details.fragmentHint) {
  4606. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  4607. }
  4608. details.PTSKnown = details.alignedSliding = true;
  4609. return drift;
  4610. }
  4611. function mergeDetails(oldDetails, newDetails) {
  4612. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  4613. let currentInitSegment = null;
  4614. const oldFragments = oldDetails.fragments;
  4615. for (let i = oldFragments.length - 1; i >= 0; i--) {
  4616. const oldInit = oldFragments[i].initSegment;
  4617. if (oldInit) {
  4618. currentInitSegment = oldInit;
  4619. break;
  4620. }
  4621. }
  4622. if (oldDetails.fragmentHint) {
  4623. // prevent PTS and duration from being adjusted on the next hint
  4624. delete oldDetails.fragmentHint.endPTS;
  4625. }
  4626. // check if old/new playlists have fragments in common
  4627. // loop through overlapping SN and update startPTS , cc, and duration if any found
  4628. let ccOffset = 0;
  4629. let PTSFrag;
  4630. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {
  4631. if (oldFrag.relurl) {
  4632. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  4633. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  4634. // of the playlist.
  4635. ccOffset = oldFrag.cc - newFrag.cc;
  4636. }
  4637. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  4638. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  4639. newFrag.startDTS = oldFrag.startDTS;
  4640. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  4641. newFrag.endPTS = oldFrag.endPTS;
  4642. newFrag.endDTS = oldFrag.endDTS;
  4643. newFrag.minEndPTS = oldFrag.minEndPTS;
  4644. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  4645. if (newFrag.duration) {
  4646. PTSFrag = newFrag;
  4647. }
  4648. // PTS is known when any segment has startPTS and endPTS
  4649. newDetails.PTSKnown = newDetails.alignedSliding = true;
  4650. }
  4651. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  4652. newFrag.loader = oldFrag.loader;
  4653. newFrag.stats = oldFrag.stats;
  4654. if (oldFrag.initSegment) {
  4655. newFrag.initSegment = oldFrag.initSegment;
  4656. currentInitSegment = oldFrag.initSegment;
  4657. }
  4658. });
  4659. if (currentInitSegment) {
  4660. const fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  4661. fragmentsToCheck.forEach(frag => {
  4662. var _currentInitSegment;
  4663. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  4664. frag.initSegment = currentInitSegment;
  4665. }
  4666. });
  4667. }
  4668. if (newDetails.skippedSegments) {
  4669. newDetails.deltaUpdateFailed = newDetails.fragments.some(frag => !frag);
  4670. if (newDetails.deltaUpdateFailed) {
  4671. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  4672. for (let i = newDetails.skippedSegments; i--;) {
  4673. newDetails.fragments.shift();
  4674. }
  4675. newDetails.startSN = newDetails.fragments[0].sn;
  4676. newDetails.startCC = newDetails.fragments[0].cc;
  4677. } else if (newDetails.canSkipDateRanges) {
  4678. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  4679. }
  4680. }
  4681. const newFragments = newDetails.fragments;
  4682. if (ccOffset) {
  4683. logger.warn('discontinuity sliding from playlist, take drift into account');
  4684. for (let i = 0; i < newFragments.length; i++) {
  4685. newFragments[i].cc += ccOffset;
  4686. }
  4687. }
  4688. if (newDetails.skippedSegments) {
  4689. newDetails.startCC = newDetails.fragments[0].cc;
  4690. }
  4691. // Merge parts
  4692. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  4693. newPart.elementaryStreams = oldPart.elementaryStreams;
  4694. newPart.stats = oldPart.stats;
  4695. });
  4696. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  4697. if (PTSFrag) {
  4698. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  4699. } else {
  4700. // ensure that delta is within oldFragments range
  4701. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  4702. // in that case we also need to adjust start offset of all fragments
  4703. adjustSliding(oldDetails, newDetails);
  4704. }
  4705. if (newFragments.length) {
  4706. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  4707. }
  4708. newDetails.driftStartTime = oldDetails.driftStartTime;
  4709. newDetails.driftStart = oldDetails.driftStart;
  4710. const advancedDateTime = newDetails.advancedDateTime;
  4711. if (newDetails.advanced && advancedDateTime) {
  4712. const edge = newDetails.edge;
  4713. if (!newDetails.driftStart) {
  4714. newDetails.driftStartTime = advancedDateTime;
  4715. newDetails.driftStart = edge;
  4716. }
  4717. newDetails.driftEndTime = advancedDateTime;
  4718. newDetails.driftEnd = edge;
  4719. } else {
  4720. newDetails.driftEndTime = oldDetails.driftEndTime;
  4721. newDetails.driftEnd = oldDetails.driftEnd;
  4722. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  4723. }
  4724. }
  4725. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  4726. const dateRanges = _extends({}, oldDateRanges);
  4727. if (recentlyRemovedDateranges) {
  4728. recentlyRemovedDateranges.forEach(id => {
  4729. delete dateRanges[id];
  4730. });
  4731. }
  4732. Object.keys(deltaDateRanges).forEach(id => {
  4733. const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  4734. if (dateRange.isValid) {
  4735. dateRanges[id] = dateRange;
  4736. } else {
  4737. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(deltaDateRanges[id].attr)}"`);
  4738. }
  4739. });
  4740. return dateRanges;
  4741. }
  4742. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  4743. if (oldParts && newParts) {
  4744. let delta = 0;
  4745. for (let i = 0, len = oldParts.length; i <= len; i++) {
  4746. const oldPart = oldParts[i];
  4747. const newPart = newParts[i + delta];
  4748. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  4749. intersectionFn(oldPart, newPart);
  4750. } else {
  4751. delta--;
  4752. }
  4753. }
  4754. }
  4755. }
  4756. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  4757. const skippedSegments = newDetails.skippedSegments;
  4758. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  4759. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  4760. const delta = newDetails.startSN - oldDetails.startSN;
  4761. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  4762. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  4763. for (let i = start; i <= end; i++) {
  4764. const oldFrag = oldFrags[delta + i];
  4765. let newFrag = newFrags[i];
  4766. if (skippedSegments && !newFrag && i < skippedSegments) {
  4767. // Fill in skipped segments in delta playlist
  4768. newFrag = newDetails.fragments[i] = oldFrag;
  4769. }
  4770. if (oldFrag && newFrag) {
  4771. intersectionFn(oldFrag, newFrag);
  4772. }
  4773. }
  4774. }
  4775. function adjustSliding(oldDetails, newDetails) {
  4776. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  4777. const oldFragments = oldDetails.fragments;
  4778. if (delta < 0 || delta >= oldFragments.length) {
  4779. return;
  4780. }
  4781. addSliding(newDetails, oldFragments[delta].start);
  4782. }
  4783. function addSliding(details, start) {
  4784. if (start) {
  4785. const fragments = details.fragments;
  4786. for (let i = details.skippedSegments; i < fragments.length; i++) {
  4787. fragments[i].start += start;
  4788. }
  4789. if (details.fragmentHint) {
  4790. details.fragmentHint.start += start;
  4791. }
  4792. }
  4793. }
  4794. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  4795. let reloadInterval = 1000 * newDetails.targetduration;
  4796. if (newDetails.updated) {
  4797. // Use last segment duration when shorter than target duration and near live edge
  4798. const fragments = newDetails.fragments;
  4799. const liveEdgeMaxTargetDurations = 4;
  4800. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  4801. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  4802. if (lastSegmentDuration < reloadInterval) {
  4803. reloadInterval = lastSegmentDuration;
  4804. }
  4805. }
  4806. } else {
  4807. // estimate = 'miss half average';
  4808. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  4809. // changed then it MUST wait for a period of one-half the target
  4810. // duration before retrying.
  4811. reloadInterval /= 2;
  4812. }
  4813. return Math.round(reloadInterval);
  4814. }
  4815. function getFragmentWithSN(level, sn, fragCurrent) {
  4816. if (!(level != null && level.details)) {
  4817. return null;
  4818. }
  4819. const levelDetails = level.details;
  4820. let fragment = levelDetails.fragments[sn - levelDetails.startSN];
  4821. if (fragment) {
  4822. return fragment;
  4823. }
  4824. fragment = levelDetails.fragmentHint;
  4825. if (fragment && fragment.sn === sn) {
  4826. return fragment;
  4827. }
  4828. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  4829. return fragCurrent;
  4830. }
  4831. return null;
  4832. }
  4833. function getPartWith(level, sn, partIndex) {
  4834. var _level$details;
  4835. if (!(level != null && level.details)) {
  4836. return null;
  4837. }
  4838. return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex);
  4839. }
  4840. function findPart(partList, sn, partIndex) {
  4841. if (partList) {
  4842. for (let i = partList.length; i--;) {
  4843. const part = partList[i];
  4844. if (part.index === partIndex && part.fragment.sn === sn) {
  4845. return part;
  4846. }
  4847. }
  4848. }
  4849. return null;
  4850. }
  4851. function reassignFragmentLevelIndexes(levels) {
  4852. levels.forEach((level, index) => {
  4853. const {
  4854. details
  4855. } = level;
  4856. if (details != null && details.fragments) {
  4857. details.fragments.forEach(fragment => {
  4858. fragment.level = index;
  4859. });
  4860. }
  4861. });
  4862. }
  4863. function isTimeoutError(error) {
  4864. switch (error.details) {
  4865. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4866. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4867. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4868. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  4869. return true;
  4870. }
  4871. return false;
  4872. }
  4873. function getRetryConfig(loadPolicy, error) {
  4874. const isTimeout = isTimeoutError(error);
  4875. return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];
  4876. }
  4877. function getRetryDelay(retryConfig, retryCount) {
  4878. // exponential backoff capped to max retry delay
  4879. const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  4880. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  4881. }
  4882. function getLoaderConfigWithoutReties(loderConfig) {
  4883. return _objectSpread2(_objectSpread2({}, loderConfig), {
  4884. errorRetry: null,
  4885. timeoutRetry: null
  4886. });
  4887. }
  4888. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  4889. if (!retryConfig) {
  4890. return false;
  4891. }
  4892. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  4893. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  4894. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  4895. }
  4896. function retryForHttpStatus(httpStatus) {
  4897. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  4898. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  4899. }
  4900. const BinarySearch = {
  4901. /**
  4902. * Searches for an item in an array which matches a certain condition.
  4903. * This requires the condition to only match one item in the array,
  4904. * and for the array to be ordered.
  4905. *
  4906. * @param list The array to search.
  4907. * @param comparisonFn
  4908. * Called and provided a candidate item as the first argument.
  4909. * Should return:
  4910. * > -1 if the item should be located at a lower index than the provided item.
  4911. * > 1 if the item should be located at a higher index than the provided item.
  4912. * > 0 if the item is the item you're looking for.
  4913. *
  4914. * @returns the object if found, otherwise returns null
  4915. */
  4916. search: function (list, comparisonFn) {
  4917. let minIndex = 0;
  4918. let maxIndex = list.length - 1;
  4919. let currentIndex = null;
  4920. let currentElement = null;
  4921. while (minIndex <= maxIndex) {
  4922. currentIndex = (minIndex + maxIndex) / 2 | 0;
  4923. currentElement = list[currentIndex];
  4924. const comparisonResult = comparisonFn(currentElement);
  4925. if (comparisonResult > 0) {
  4926. minIndex = currentIndex + 1;
  4927. } else if (comparisonResult < 0) {
  4928. maxIndex = currentIndex - 1;
  4929. } else {
  4930. return currentElement;
  4931. }
  4932. }
  4933. return null;
  4934. }
  4935. };
  4936. /**
  4937. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  4938. * @param fragments - The array of candidate fragments
  4939. * @param PDTValue - The PDT value which must be exceeded
  4940. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4941. */
  4942. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  4943. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  4944. return null;
  4945. }
  4946. // if less than start
  4947. const startPDT = fragments[0].programDateTime;
  4948. if (PDTValue < (startPDT || 0)) {
  4949. return null;
  4950. }
  4951. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  4952. if (PDTValue >= (endPDT || 0)) {
  4953. return null;
  4954. }
  4955. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  4956. for (let seg = 0; seg < fragments.length; ++seg) {
  4957. const frag = fragments[seg];
  4958. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  4959. return frag;
  4960. }
  4961. }
  4962. return null;
  4963. }
  4964. /**
  4965. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  4966. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  4967. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  4968. * @param fragPrevious - The last frag successfully appended
  4969. * @param fragments - The array of candidate fragments
  4970. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  4971. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4972. * @returns a matching fragment or null
  4973. */
  4974. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {
  4975. let fragNext = null;
  4976. if (fragPrevious) {
  4977. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  4978. // check for buffer-end rounding error
  4979. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  4980. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  4981. bufferEnd += 0.0000015;
  4982. }
  4983. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  4984. fragNext = fragments[0];
  4985. }
  4986. // Prefer the next fragment if it's within tolerance
  4987. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  4988. return fragNext;
  4989. }
  4990. // We might be seeking past the tolerance so find the best match
  4991. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  4992. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  4993. return foundFragment;
  4994. }
  4995. // If no match was found return the next fragment after fragPrevious, or null
  4996. return fragNext;
  4997. }
  4998. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  4999. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  5000. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  5001. if (tag[0] === 'INF') {
  5002. duration += parseFloat(tag[1]);
  5003. }
  5004. return duration;
  5005. }, nextFragLookupTolerance);
  5006. return fragNext.start <= firstDuration;
  5007. }
  5008. return false;
  5009. }
  5010. /**
  5011. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5012. * @param candidate - The fragment to test
  5013. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  5014. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5015. * @returns 0 if it matches, 1 if too low, -1 if too high
  5016. */
  5017. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  5018. // eagerly accept an accurate match (no tolerance)
  5019. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  5020. return 0;
  5021. }
  5022. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5023. // this is to cope with situations like
  5024. // bufferEnd = 9.991
  5025. // frag[Ø] : [0,10]
  5026. // frag[1] : [10,20]
  5027. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5028. // frag start frag start+duration
  5029. // |-----------------------------|
  5030. // <---> <--->
  5031. // ...--------><-----------------------------><---------....
  5032. // previous frag matching fragment next frag
  5033. // return -1 return 0 return 1
  5034. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5035. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5036. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5037. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5038. return 1;
  5039. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5040. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5041. return -1;
  5042. }
  5043. return 0;
  5044. }
  5045. /**
  5046. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5047. * This function tests the candidate's program date time values, as represented in Unix time
  5048. * @param candidate - The fragment to test
  5049. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  5050. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5051. * @returns true if contiguous, false otherwise
  5052. */
  5053. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5054. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5055. // endProgramDateTime can be null, default to zero
  5056. const endProgramDateTime = candidate.endProgramDateTime || 0;
  5057. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5058. }
  5059. function findFragWithCC(fragments, cc) {
  5060. return BinarySearch.search(fragments, candidate => {
  5061. if (candidate.cc < cc) {
  5062. return 1;
  5063. } else if (candidate.cc > cc) {
  5064. return -1;
  5065. } else {
  5066. return 0;
  5067. }
  5068. });
  5069. }
  5070. var NetworkErrorAction = {
  5071. DoNothing: 0,
  5072. SendEndCallback: 1,
  5073. SendAlternateToPenaltyBox: 2,
  5074. RemoveAlternatePermanently: 3,
  5075. InsertDiscontinuity: 4,
  5076. RetryRequest: 5
  5077. };
  5078. var ErrorActionFlags = {
  5079. None: 0,
  5080. MoveAllAlternatesMatchingHost: 1,
  5081. MoveAllAlternatesMatchingHDCP: 2,
  5082. SwitchToSDR: 4
  5083. }; // Reserved for future use
  5084. class ErrorController {
  5085. constructor(hls) {
  5086. this.hls = void 0;
  5087. this.playlistError = 0;
  5088. this.penalizedRenditions = {};
  5089. this.log = void 0;
  5090. this.warn = void 0;
  5091. this.error = void 0;
  5092. this.hls = hls;
  5093. this.log = logger.log.bind(logger, `[info]:`);
  5094. this.warn = logger.warn.bind(logger, `[warning]:`);
  5095. this.error = logger.error.bind(logger, `[error]:`);
  5096. this.registerListeners();
  5097. }
  5098. registerListeners() {
  5099. const hls = this.hls;
  5100. hls.on(Events.ERROR, this.onError, this);
  5101. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5102. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5103. }
  5104. unregisterListeners() {
  5105. const hls = this.hls;
  5106. if (!hls) {
  5107. return;
  5108. }
  5109. hls.off(Events.ERROR, this.onError, this);
  5110. hls.off(Events.ERROR, this.onErrorOut, this);
  5111. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5112. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5113. }
  5114. destroy() {
  5115. this.unregisterListeners();
  5116. // @ts-ignore
  5117. this.hls = null;
  5118. this.penalizedRenditions = {};
  5119. }
  5120. startLoad(startPosition) {}
  5121. stopLoad() {
  5122. this.playlistError = 0;
  5123. }
  5124. getVariantLevelIndex(frag) {
  5125. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  5126. }
  5127. onManifestLoading() {
  5128. this.playlistError = 0;
  5129. this.penalizedRenditions = {};
  5130. }
  5131. onLevelUpdated() {
  5132. this.playlistError = 0;
  5133. }
  5134. onError(event, data) {
  5135. var _data$frag, _data$level;
  5136. if (data.fatal) {
  5137. return;
  5138. }
  5139. const hls = this.hls;
  5140. const context = data.context;
  5141. switch (data.details) {
  5142. case ErrorDetails.FRAG_LOAD_ERROR:
  5143. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5144. case ErrorDetails.KEY_LOAD_ERROR:
  5145. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5146. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5147. return;
  5148. case ErrorDetails.FRAG_PARSING_ERROR:
  5149. // ignore empty segment errors marked as gap
  5150. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  5151. data.errorAction = {
  5152. action: NetworkErrorAction.DoNothing,
  5153. flags: ErrorActionFlags.None
  5154. };
  5155. return;
  5156. }
  5157. // falls through
  5158. case ErrorDetails.FRAG_GAP:
  5159. case ErrorDetails.FRAG_DECRYPT_ERROR:
  5160. {
  5161. // Switch level if possible, otherwise allow retry count to reach max error retries
  5162. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5163. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5164. return;
  5165. }
  5166. case ErrorDetails.LEVEL_EMPTY_ERROR:
  5167. case ErrorDetails.LEVEL_PARSING_ERROR:
  5168. {
  5169. var _data$context, _data$context$levelDe;
  5170. // Only retry when empty and live
  5171. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  5172. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  5173. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  5174. } else {
  5175. // Escalate to fatal if not retrying or switching
  5176. data.levelRetry = false;
  5177. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5178. }
  5179. }
  5180. return;
  5181. case ErrorDetails.LEVEL_LOAD_ERROR:
  5182. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5183. if (typeof (context == null ? void 0 : context.level) === 'number') {
  5184. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  5185. }
  5186. return;
  5187. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  5188. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  5189. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  5190. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  5191. if (context) {
  5192. const level = hls.levels[hls.loadLevel];
  5193. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  5194. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  5195. // otherwise allow playlist retry count to reach max error retries
  5196. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  5197. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5198. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  5199. return;
  5200. }
  5201. }
  5202. return;
  5203. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  5204. {
  5205. const level = hls.levels[hls.loadLevel];
  5206. const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];
  5207. if (restrictedHdcpLevel) {
  5208. data.errorAction = {
  5209. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5210. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  5211. hdcpLevel: restrictedHdcpLevel
  5212. };
  5213. } else {
  5214. this.keySystemError(data);
  5215. }
  5216. }
  5217. return;
  5218. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  5219. case ErrorDetails.REMUX_ALLOC_ERROR:
  5220. case ErrorDetails.BUFFER_APPEND_ERROR:
  5221. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  5222. return;
  5223. case ErrorDetails.INTERNAL_EXCEPTION:
  5224. case ErrorDetails.BUFFER_APPENDING_ERROR:
  5225. case ErrorDetails.BUFFER_FULL_ERROR:
  5226. case ErrorDetails.LEVEL_SWITCH_ERROR:
  5227. case ErrorDetails.BUFFER_STALLED_ERROR:
  5228. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  5229. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  5230. data.errorAction = {
  5231. action: NetworkErrorAction.DoNothing,
  5232. flags: ErrorActionFlags.None
  5233. };
  5234. return;
  5235. }
  5236. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  5237. this.keySystemError(data);
  5238. }
  5239. }
  5240. keySystemError(data) {
  5241. const levelIndex = this.getVariantLevelIndex(data.frag);
  5242. // Do not retry level. Escalate to fatal if switching levels fails.
  5243. data.levelRetry = false;
  5244. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5245. }
  5246. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  5247. const hls = this.hls;
  5248. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  5249. const retryCount = this.playlistError++;
  5250. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  5251. if (retry) {
  5252. return {
  5253. action: NetworkErrorAction.RetryRequest,
  5254. flags: ErrorActionFlags.None,
  5255. retryConfig,
  5256. retryCount
  5257. };
  5258. }
  5259. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  5260. if (retryConfig) {
  5261. errorAction.retryConfig = retryConfig;
  5262. errorAction.retryCount = retryCount;
  5263. }
  5264. return errorAction;
  5265. }
  5266. getFragRetryOrSwitchAction(data) {
  5267. const hls = this.hls;
  5268. // Share fragment error count accross media options (main, audio, subs)
  5269. // This allows for level based rendition switching when media option assets fail
  5270. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  5271. const level = hls.levels[variantLevelIndex];
  5272. const {
  5273. fragLoadPolicy,
  5274. keyLoadPolicy
  5275. } = hls.config;
  5276. const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  5277. const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);
  5278. // Switch levels when out of retried or level index out of bounds
  5279. if (level) {
  5280. if (data.details !== ErrorDetails.FRAG_GAP) {
  5281. level.fragmentError++;
  5282. }
  5283. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  5284. if (retry) {
  5285. return {
  5286. action: NetworkErrorAction.RetryRequest,
  5287. flags: ErrorActionFlags.None,
  5288. retryConfig,
  5289. retryCount: fragmentErrors
  5290. };
  5291. }
  5292. }
  5293. // Reach max retry count, or Missing level reference
  5294. // Switch to valid index
  5295. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  5296. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  5297. if (retryConfig) {
  5298. errorAction.retryConfig = retryConfig;
  5299. errorAction.retryCount = fragmentErrors;
  5300. }
  5301. return errorAction;
  5302. }
  5303. getLevelSwitchAction(data, levelIndex) {
  5304. const hls = this.hls;
  5305. if (levelIndex === null || levelIndex === undefined) {
  5306. levelIndex = hls.loadLevel;
  5307. }
  5308. const level = this.hls.levels[levelIndex];
  5309. if (level) {
  5310. var _data$frag2, _data$context2;
  5311. const errorDetails = data.details;
  5312. level.loadError++;
  5313. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  5314. level.fragmentError++;
  5315. }
  5316. // Search for next level to retry
  5317. let nextLevel = -1;
  5318. const {
  5319. levels,
  5320. loadLevel,
  5321. minAutoLevel,
  5322. maxAutoLevel
  5323. } = hls;
  5324. if (!hls.autoLevelEnabled) {
  5325. hls.loadLevel = -1;
  5326. }
  5327. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  5328. // Find alternate audio codec if available on audio codec error
  5329. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5330. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  5331. audioCodec
  5332. }) => level.audioCodec !== audioCodec);
  5333. // Find alternate video codec if available on video codec error
  5334. const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5335. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  5336. codecSet,
  5337. audioCodec
  5338. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  5339. const {
  5340. type: playlistErrorType,
  5341. groupId: playlistErrorGroupId
  5342. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  5343. for (let i = levels.length; i--;) {
  5344. const candidate = (i + loadLevel) % levels.length;
  5345. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  5346. var _level$audioGroups, _level$subtitleGroups;
  5347. const levelCandidate = levels[candidate];
  5348. // Skip level switch if GAP tag is found in next level at same position
  5349. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  5350. const levelDetails = levels[candidate].details;
  5351. if (levelDetails) {
  5352. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  5353. if (fragCandidate != null && fragCandidate.gap) {
  5354. continue;
  5355. }
  5356. }
  5357. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  5358. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  5359. continue;
  5360. } 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) {
  5361. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  5362. continue;
  5363. }
  5364. nextLevel = candidate;
  5365. break;
  5366. }
  5367. }
  5368. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5369. data.levelRetry = true;
  5370. this.playlistError = 0;
  5371. return {
  5372. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5373. flags: ErrorActionFlags.None,
  5374. nextAutoLevel: nextLevel
  5375. };
  5376. }
  5377. }
  5378. // No levels to switch / Manual level selection / Level not found
  5379. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5380. return {
  5381. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5382. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5383. };
  5384. }
  5385. onErrorOut(event, data) {
  5386. var _data$errorAction;
  5387. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5388. case NetworkErrorAction.DoNothing:
  5389. break;
  5390. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5391. this.sendAlternateToPenaltyBox(data);
  5392. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5393. data.fatal = true;
  5394. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5395. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  5396. this.hls.recoverMediaError();
  5397. }
  5398. break;
  5399. case NetworkErrorAction.RetryRequest:
  5400. // handled by stream and playlist/level controllers
  5401. break;
  5402. }
  5403. if (data.fatal) {
  5404. this.hls.stopLoad();
  5405. return;
  5406. }
  5407. }
  5408. sendAlternateToPenaltyBox(data) {
  5409. const hls = this.hls;
  5410. const errorAction = data.errorAction;
  5411. if (!errorAction) {
  5412. return;
  5413. }
  5414. const {
  5415. flags,
  5416. hdcpLevel,
  5417. nextAutoLevel
  5418. } = errorAction;
  5419. switch (flags) {
  5420. case ErrorActionFlags.None:
  5421. this.switchLevel(data, nextAutoLevel);
  5422. break;
  5423. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5424. if (hdcpLevel) {
  5425. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5426. errorAction.resolved = true;
  5427. }
  5428. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  5429. break;
  5430. }
  5431. // If not resolved by previous actions try to switch to next level
  5432. if (!errorAction.resolved) {
  5433. this.switchLevel(data, nextAutoLevel);
  5434. }
  5435. }
  5436. switchLevel(data, levelIndex) {
  5437. if (levelIndex !== undefined && data.errorAction) {
  5438. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  5439. this.hls.nextAutoLevel = levelIndex;
  5440. data.errorAction.resolved = true;
  5441. // Stream controller is responsible for this but won't switch on false start
  5442. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5443. }
  5444. }
  5445. }
  5446. class BasePlaylistController {
  5447. constructor(hls, logPrefix) {
  5448. this.hls = void 0;
  5449. this.timer = -1;
  5450. this.requestScheduled = -1;
  5451. this.canLoad = false;
  5452. this.log = void 0;
  5453. this.warn = void 0;
  5454. this.log = logger.log.bind(logger, `${logPrefix}:`);
  5455. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  5456. this.hls = hls;
  5457. }
  5458. destroy() {
  5459. this.clearTimer();
  5460. // @ts-ignore
  5461. this.hls = this.log = this.warn = null;
  5462. }
  5463. clearTimer() {
  5464. if (this.timer !== -1) {
  5465. self.clearTimeout(this.timer);
  5466. this.timer = -1;
  5467. }
  5468. }
  5469. startLoad() {
  5470. this.canLoad = true;
  5471. this.requestScheduled = -1;
  5472. this.loadPlaylist();
  5473. }
  5474. stopLoad() {
  5475. this.canLoad = false;
  5476. this.clearTimer();
  5477. }
  5478. switchParams(playlistUri, previous, current) {
  5479. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  5480. if (renditionReports) {
  5481. let foundIndex = -1;
  5482. for (let i = 0; i < renditionReports.length; i++) {
  5483. const attr = renditionReports[i];
  5484. let uri;
  5485. try {
  5486. uri = new self.URL(attr.URI, previous.url).href;
  5487. } catch (error) {
  5488. logger.warn(`Could not construct new URL for Rendition Report: ${error}`);
  5489. uri = attr.URI || '';
  5490. }
  5491. // Use exact match. Otherwise, the last partial match, if any, will be used
  5492. // (Playlist URI includes a query string that the Rendition Report does not)
  5493. if (uri === playlistUri) {
  5494. foundIndex = i;
  5495. break;
  5496. } else if (uri === playlistUri.substring(0, uri.length)) {
  5497. foundIndex = i;
  5498. }
  5499. }
  5500. if (foundIndex !== -1) {
  5501. const attr = renditionReports[foundIndex];
  5502. const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  5503. let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  5504. if (this.hls.config.lowLatencyMode) {
  5505. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  5506. if (part >= 0 && currentGoal > previous.partTarget) {
  5507. part += 1;
  5508. }
  5509. }
  5510. const skip = current && getSkipValue(current);
  5511. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  5512. }
  5513. }
  5514. }
  5515. loadPlaylist(hlsUrlParameters) {
  5516. if (this.requestScheduled === -1) {
  5517. this.requestScheduled = self.performance.now();
  5518. }
  5519. // Loading is handled by the subclasses
  5520. }
  5521. shouldLoadPlaylist(playlist) {
  5522. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  5523. }
  5524. shouldReloadPlaylist(playlist) {
  5525. return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist);
  5526. }
  5527. playlistLoaded(index, data, previousDetails) {
  5528. const {
  5529. details,
  5530. stats
  5531. } = data;
  5532. // Set last updated date-time
  5533. const now = self.performance.now();
  5534. const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  5535. details.advancedDateTime = Date.now() - elapsed;
  5536. // if current playlist is a live playlist, arm a timer to reload it
  5537. if (details.live || previousDetails != null && previousDetails.live) {
  5538. details.reloaded(previousDetails);
  5539. if (previousDetails) {
  5540. this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);
  5541. }
  5542. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  5543. if (previousDetails && details.fragments.length > 0) {
  5544. mergeDetails(previousDetails, details);
  5545. }
  5546. if (!this.canLoad || !details.live) {
  5547. return;
  5548. }
  5549. let deliveryDirectives;
  5550. let msn = undefined;
  5551. let part = undefined;
  5552. if (details.canBlockReload && details.endSN && details.advanced) {
  5553. // Load level with LL-HLS delivery directives
  5554. const lowLatencyMode = this.hls.config.lowLatencyMode;
  5555. const lastPartSn = details.lastPartSn;
  5556. const endSn = details.endSN;
  5557. const lastPartIndex = details.lastPartIndex;
  5558. const hasParts = lastPartIndex !== -1;
  5559. const lastPart = lastPartSn === endSn;
  5560. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  5561. const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  5562. if (hasParts) {
  5563. msn = lastPart ? endSn + 1 : lastPartSn;
  5564. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  5565. } else {
  5566. msn = endSn + 1;
  5567. }
  5568. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  5569. // Update directives to obtain the Playlist that has the estimated additional duration of media
  5570. const lastAdvanced = details.age;
  5571. const cdnAge = lastAdvanced + details.ageHeader;
  5572. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  5573. if (currentGoal > 0) {
  5574. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  5575. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  5576. // then we either can't catchup, or the "age" header cannot be trusted.
  5577. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  5578. currentGoal = 0;
  5579. } else {
  5580. const segments = Math.floor(currentGoal / details.targetduration);
  5581. msn += segments;
  5582. if (part !== undefined) {
  5583. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  5584. part += parts;
  5585. }
  5586. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  5587. }
  5588. details.tuneInGoal = currentGoal;
  5589. }
  5590. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5591. if (lowLatencyMode || !lastPart) {
  5592. this.loadPlaylist(deliveryDirectives);
  5593. return;
  5594. }
  5595. } else if (details.canBlockReload || details.canSkipUntil) {
  5596. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5597. }
  5598. const bufferInfo = this.hls.mainForwardBufferInfo;
  5599. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  5600. const distanceToLiveEdgeMs = (details.edge - position) * 1000;
  5601. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  5602. if (details.updated && now > this.requestScheduled + reloadInterval) {
  5603. this.requestScheduled = stats.loading.start;
  5604. }
  5605. if (msn !== undefined && details.canBlockReload) {
  5606. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  5607. } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now) {
  5608. this.requestScheduled = now;
  5609. } else if (this.requestScheduled - now <= 0) {
  5610. this.requestScheduled += reloadInterval;
  5611. }
  5612. let estimatedTimeUntilUpdate = this.requestScheduled - now;
  5613. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  5614. this.log(`reload live playlist ${index} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  5615. // this.log(
  5616. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  5617. // reload in ${estimatedTimeUntilUpdate / 1000}
  5618. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  5619. // diff ${
  5620. // (reloadInterval -
  5621. // (estimatedTimeUntilUpdate +
  5622. // stats.loading.end -
  5623. // stats.loading.start)) /
  5624. // 1000
  5625. // }
  5626. // reload interval ${reloadInterval / 1000}
  5627. // target duration ${details.targetduration}
  5628. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  5629. // );
  5630. this.timer = self.setTimeout(() => this.loadPlaylist(deliveryDirectives), estimatedTimeUntilUpdate);
  5631. } else {
  5632. this.clearTimer();
  5633. }
  5634. }
  5635. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  5636. let skip = getSkipValue(details);
  5637. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  5638. msn = previousDeliveryDirectives.msn;
  5639. part = previousDeliveryDirectives.part;
  5640. skip = HlsSkip.No;
  5641. }
  5642. return new HlsUrlParameters(msn, part, skip);
  5643. }
  5644. checkRetry(errorEvent) {
  5645. const errorDetails = errorEvent.details;
  5646. const isTimeout = isTimeoutError(errorEvent);
  5647. const errorAction = errorEvent.errorAction;
  5648. const {
  5649. action,
  5650. retryCount = 0,
  5651. retryConfig
  5652. } = errorAction || {};
  5653. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  5654. if (retry) {
  5655. var _errorEvent$context;
  5656. this.requestScheduled = -1;
  5657. if (retryCount >= retryConfig.maxNumRetry) {
  5658. return false;
  5659. }
  5660. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  5661. // The LL-HLS request already timed out so retry immediately
  5662. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  5663. this.loadPlaylist();
  5664. } else {
  5665. const delay = getRetryDelay(retryConfig, retryCount);
  5666. // Schedule level/track reload
  5667. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  5668. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  5669. }
  5670. // `levelRetry = true` used to inform other controllers that a retry is happening
  5671. errorEvent.levelRetry = true;
  5672. errorAction.resolved = true;
  5673. }
  5674. return retry;
  5675. }
  5676. }
  5677. /*
  5678. * compute an Exponential Weighted moving average
  5679. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  5680. * - heavily inspired from shaka-player
  5681. */
  5682. class EWMA {
  5683. // About half of the estimated value will be from the last |halfLife| samples by weight.
  5684. constructor(halfLife, estimate = 0, weight = 0) {
  5685. this.halfLife = void 0;
  5686. this.alpha_ = void 0;
  5687. this.estimate_ = void 0;
  5688. this.totalWeight_ = void 0;
  5689. this.halfLife = halfLife;
  5690. // Larger values of alpha expire historical data more slowly.
  5691. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  5692. this.estimate_ = estimate;
  5693. this.totalWeight_ = weight;
  5694. }
  5695. sample(weight, value) {
  5696. const adjAlpha = Math.pow(this.alpha_, weight);
  5697. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  5698. this.totalWeight_ += weight;
  5699. }
  5700. getTotalWeight() {
  5701. return this.totalWeight_;
  5702. }
  5703. getEstimate() {
  5704. if (this.alpha_) {
  5705. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  5706. if (zeroFactor) {
  5707. return this.estimate_ / zeroFactor;
  5708. }
  5709. }
  5710. return this.estimate_;
  5711. }
  5712. }
  5713. /*
  5714. * EWMA Bandwidth Estimator
  5715. * - heavily inspired from shaka-player
  5716. * Tracks bandwidth samples and estimates available bandwidth.
  5717. * Based on the minimum of two exponentially-weighted moving averages with
  5718. * different half-lives.
  5719. */
  5720. class EwmaBandWidthEstimator {
  5721. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  5722. this.defaultEstimate_ = void 0;
  5723. this.minWeight_ = void 0;
  5724. this.minDelayMs_ = void 0;
  5725. this.slow_ = void 0;
  5726. this.fast_ = void 0;
  5727. this.defaultTTFB_ = void 0;
  5728. this.ttfb_ = void 0;
  5729. this.defaultEstimate_ = defaultEstimate;
  5730. this.minWeight_ = 0.001;
  5731. this.minDelayMs_ = 50;
  5732. this.slow_ = new EWMA(slow);
  5733. this.fast_ = new EWMA(fast);
  5734. this.defaultTTFB_ = defaultTTFB;
  5735. this.ttfb_ = new EWMA(slow);
  5736. }
  5737. update(slow, fast) {
  5738. const {
  5739. slow_,
  5740. fast_,
  5741. ttfb_
  5742. } = this;
  5743. if (slow_.halfLife !== slow) {
  5744. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  5745. }
  5746. if (fast_.halfLife !== fast) {
  5747. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  5748. }
  5749. if (ttfb_.halfLife !== slow) {
  5750. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  5751. }
  5752. }
  5753. sample(durationMs, numBytes) {
  5754. durationMs = Math.max(durationMs, this.minDelayMs_);
  5755. const numBits = 8 * numBytes;
  5756. // weight is duration in seconds
  5757. const durationS = durationMs / 1000;
  5758. // value is bandwidth in bits/s
  5759. const bandwidthInBps = numBits / durationS;
  5760. this.fast_.sample(durationS, bandwidthInBps);
  5761. this.slow_.sample(durationS, bandwidthInBps);
  5762. }
  5763. sampleTTFB(ttfb) {
  5764. // weight is frequency curve applied to TTFB in seconds
  5765. // (longer times have less weight with expected input under 1 second)
  5766. const seconds = ttfb / 1000;
  5767. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  5768. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  5769. }
  5770. canEstimate() {
  5771. return this.fast_.getTotalWeight() >= this.minWeight_;
  5772. }
  5773. getEstimate() {
  5774. if (this.canEstimate()) {
  5775. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  5776. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  5777. // Take the minimum of these two estimates. This should have the effect of
  5778. // adapting down quickly, but up more slowly.
  5779. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  5780. } else {
  5781. return this.defaultEstimate_;
  5782. }
  5783. }
  5784. getEstimateTTFB() {
  5785. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  5786. return this.ttfb_.getEstimate();
  5787. } else {
  5788. return this.defaultTTFB_;
  5789. }
  5790. }
  5791. destroy() {}
  5792. }
  5793. /**
  5794. * @returns Whether we can detect and validate HDR capability within the window context
  5795. */
  5796. function isHdrSupported() {
  5797. if (typeof matchMedia === 'function') {
  5798. const mediaQueryList = matchMedia('(dynamic-range: high)');
  5799. const badQuery = matchMedia('bad query');
  5800. if (mediaQueryList.media !== badQuery.media) {
  5801. return mediaQueryList.matches === true;
  5802. }
  5803. }
  5804. return false;
  5805. }
  5806. /**
  5807. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  5808. * When both inputs are null:
  5809. *
  5810. * `{ preferHDR: false, allowedVideoRanges: [] }`
  5811. *
  5812. * When `currentVideoRange` non-null, maintain the active range:
  5813. *
  5814. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  5815. *
  5816. * When VideoSelectionOption non-null:
  5817. *
  5818. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  5819. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  5820. * - Else check window for HDR support and set `preferHDR` to the result.
  5821. *
  5822. * @param currentVideoRange
  5823. * @param videoPreference
  5824. */
  5825. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  5826. let preferHDR = false;
  5827. let allowedVideoRanges = [];
  5828. if (currentVideoRange) {
  5829. preferHDR = currentVideoRange !== 'SDR';
  5830. allowedVideoRanges = [currentVideoRange];
  5831. }
  5832. if (videoPreference) {
  5833. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  5834. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : isHdrSupported();
  5835. if (preferHDR) {
  5836. allowedVideoRanges = allowedVideoRanges.filter(range => range !== 'SDR');
  5837. } else {
  5838. allowedVideoRanges = ['SDR'];
  5839. }
  5840. }
  5841. return {
  5842. preferHDR,
  5843. allowedVideoRanges
  5844. };
  5845. }
  5846. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  5847. const codecSets = Object.keys(codecTiers);
  5848. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  5849. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  5850. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  5851. // Use first level set to determine stereo, and minimum resolution and framerate
  5852. let hasStereo = true;
  5853. let hasCurrentVideoRange = false;
  5854. let minHeight = Infinity;
  5855. let minFramerate = Infinity;
  5856. let minBitrate = Infinity;
  5857. let selectedScore = 0;
  5858. let videoRanges = [];
  5859. const {
  5860. preferHDR,
  5861. allowedVideoRanges
  5862. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  5863. for (let i = codecSets.length; i--;) {
  5864. const tier = codecTiers[codecSets[i]];
  5865. hasStereo = tier.channels[2] > 0;
  5866. minHeight = Math.min(minHeight, tier.minHeight);
  5867. minFramerate = Math.min(minFramerate, tier.minFramerate);
  5868. minBitrate = Math.min(minBitrate, tier.minBitrate);
  5869. const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);
  5870. if (matchingVideoRanges.length > 0) {
  5871. hasCurrentVideoRange = true;
  5872. videoRanges = matchingVideoRanges;
  5873. }
  5874. }
  5875. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  5876. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  5877. const maxHeight = Math.max(1080, minHeight);
  5878. const maxFramerate = Math.max(30, minFramerate);
  5879. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  5880. currentBw = Math.max(minBitrate, currentBw);
  5881. // If there are no variants with matching preference, set currentVideoRange to undefined
  5882. if (!hasCurrentVideoRange) {
  5883. currentVideoRange = undefined;
  5884. videoRanges = [];
  5885. }
  5886. const codecSet = codecSets.reduce((selected, candidate) => {
  5887. // 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
  5888. const candidateTier = codecTiers[candidate];
  5889. if (candidate === selected) {
  5890. return selected;
  5891. }
  5892. if (candidateTier.minBitrate > currentBw) {
  5893. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  5894. return selected;
  5895. }
  5896. if (!candidateTier.hasDefaultAudio) {
  5897. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  5898. return selected;
  5899. }
  5900. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  5901. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  5902. return selected;
  5903. }
  5904. if (channelsPreference && !preferStereo) {
  5905. if (!candidateTier.channels[channelsPreference]) {
  5906. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  5907. return selected;
  5908. }
  5909. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  5910. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  5911. return selected;
  5912. }
  5913. if (candidateTier.minHeight > maxHeight) {
  5914. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  5915. return selected;
  5916. }
  5917. if (candidateTier.minFramerate > maxFramerate) {
  5918. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  5919. return selected;
  5920. }
  5921. if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {
  5922. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${JSON.stringify(videoRanges)} found`);
  5923. return selected;
  5924. }
  5925. if (candidateTier.maxScore < selectedScore) {
  5926. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  5927. return selected;
  5928. }
  5929. // Remove candiates with less preferred codecs or more errors
  5930. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  5931. return selected;
  5932. }
  5933. selectedScore = candidateTier.maxScore;
  5934. return candidate;
  5935. }, undefined);
  5936. return {
  5937. codecSet,
  5938. videoRanges,
  5939. preferHDR,
  5940. minFramerate,
  5941. minBitrate
  5942. };
  5943. }
  5944. function logStartCodecCandidateIgnored(codeSet, reason) {
  5945. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  5946. }
  5947. function getAudioTracksByGroup(allAudioTracks) {
  5948. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  5949. let trackGroup = audioTracksByGroup.groups[track.groupId];
  5950. if (!trackGroup) {
  5951. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  5952. tracks: [],
  5953. channels: {
  5954. 2: 0
  5955. },
  5956. hasDefault: false,
  5957. hasAutoSelect: false
  5958. };
  5959. }
  5960. trackGroup.tracks.push(track);
  5961. const channelsKey = track.channels || '2';
  5962. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  5963. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  5964. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  5965. if (trackGroup.hasDefault) {
  5966. audioTracksByGroup.hasDefaultAudio = true;
  5967. }
  5968. if (trackGroup.hasAutoSelect) {
  5969. audioTracksByGroup.hasAutoSelectAudio = true;
  5970. }
  5971. return audioTracksByGroup;
  5972. }, {
  5973. hasDefaultAudio: false,
  5974. hasAutoSelectAudio: false,
  5975. groups: {}
  5976. });
  5977. }
  5978. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  5979. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level) => {
  5980. if (!level.codecSet) {
  5981. return tiers;
  5982. }
  5983. const audioGroups = level.audioGroups;
  5984. let tier = tiers[level.codecSet];
  5985. if (!tier) {
  5986. tiers[level.codecSet] = tier = {
  5987. minBitrate: Infinity,
  5988. minHeight: Infinity,
  5989. minFramerate: Infinity,
  5990. maxScore: 0,
  5991. videoRanges: {
  5992. SDR: 0
  5993. },
  5994. channels: {
  5995. '2': 0
  5996. },
  5997. hasDefaultAudio: !audioGroups,
  5998. fragmentError: 0
  5999. };
  6000. }
  6001. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  6002. const lesserWidthOrHeight = Math.min(level.height, level.width);
  6003. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  6004. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  6005. tier.maxScore = Math.max(tier.maxScore, level.score);
  6006. tier.fragmentError += level.fragmentError;
  6007. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  6008. return tiers;
  6009. }, {});
  6010. }
  6011. class AbrController {
  6012. constructor(_hls) {
  6013. this.hls = void 0;
  6014. this.lastLevelLoadSec = 0;
  6015. this.lastLoadedFragLevel = -1;
  6016. this.firstSelection = -1;
  6017. this._nextAutoLevel = -1;
  6018. this.nextAutoLevelKey = '';
  6019. this.audioTracksByGroup = null;
  6020. this.codecTiers = null;
  6021. this.timer = -1;
  6022. this.fragCurrent = null;
  6023. this.partCurrent = null;
  6024. this.bitrateTestDelay = 0;
  6025. this.bwEstimator = void 0;
  6026. /*
  6027. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  6028. quickly enough to prevent underbuffering
  6029. */
  6030. this._abandonRulesCheck = () => {
  6031. const {
  6032. fragCurrent: frag,
  6033. partCurrent: part,
  6034. hls
  6035. } = this;
  6036. const {
  6037. autoLevelEnabled,
  6038. media
  6039. } = hls;
  6040. if (!frag || !media) {
  6041. return;
  6042. }
  6043. const now = performance.now();
  6044. const stats = part ? part.stats : frag.stats;
  6045. const duration = part ? part.duration : frag.duration;
  6046. const timeLoading = now - stats.loading.start;
  6047. const minAutoLevel = hls.minAutoLevel;
  6048. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  6049. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) {
  6050. this.clearTimer();
  6051. // reset forced auto level value so that next level will be selected
  6052. this._nextAutoLevel = -1;
  6053. return;
  6054. }
  6055. // This check only runs if we're in ABR mode and actually playing
  6056. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  6057. return;
  6058. }
  6059. const bufferInfo = hls.mainForwardBufferInfo;
  6060. if (bufferInfo === null) {
  6061. return;
  6062. }
  6063. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6064. const playbackRate = Math.abs(media.playbackRate);
  6065. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  6066. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  6067. return;
  6068. }
  6069. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  6070. const bufferStarvationDelay = bufferInfo.len / playbackRate;
  6071. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6072. const loadedFirstByte = stats.loaded && ttfb > -1;
  6073. const bwEstimate = this.getBwEstimate();
  6074. const levels = hls.levels;
  6075. const level = levels[frag.level];
  6076. const expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8));
  6077. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  6078. if (timeStreaming < 1 && loadedFirstByte) {
  6079. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  6080. }
  6081. const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  6082. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  6083. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1000;
  6084. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  6085. if (fragLoadedDelay <= bufferStarvationDelay) {
  6086. return;
  6087. }
  6088. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  6089. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  6090. let nextLoadLevel;
  6091. // Iterate through lower level and try to find the largest one that avoids rebuffering
  6092. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  6093. // compute time to load next fragment at lower level
  6094. // 8 = bits per byte (bps/Bps)
  6095. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  6096. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbEstimate / 1000, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details);
  6097. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  6098. break;
  6099. }
  6100. }
  6101. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  6102. // to load the current one
  6103. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  6104. return;
  6105. }
  6106. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  6107. if (fragLevelNextLoadedDelay > duration * 10) {
  6108. return;
  6109. }
  6110. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  6111. if (loadedFirstByte) {
  6112. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  6113. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6114. } else {
  6115. // If there has been no loading progress, sample TTFB
  6116. this.bwEstimator.sampleTTFB(timeLoading);
  6117. }
  6118. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  6119. if (this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) {
  6120. this.resetEstimator(nextLoadLevelBitrate);
  6121. }
  6122. this.clearTimer();
  6123. logger.warn(`[abr] Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} is loading too slowly;
  6124. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  6125. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  6126. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  6127. TTFB estimate: ${ttfb | 0} ms
  6128. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps
  6129. New BW estimate: ${this.getBwEstimate() | 0} bps
  6130. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  6131. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  6132. frag,
  6133. part,
  6134. stats
  6135. });
  6136. };
  6137. this.hls = _hls;
  6138. this.bwEstimator = this.initEstimator();
  6139. this.registerListeners();
  6140. }
  6141. resetEstimator(abrEwmaDefaultEstimate) {
  6142. if (abrEwmaDefaultEstimate) {
  6143. logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  6144. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  6145. }
  6146. this.firstSelection = -1;
  6147. this.bwEstimator = this.initEstimator();
  6148. }
  6149. initEstimator() {
  6150. const config = this.hls.config;
  6151. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  6152. }
  6153. registerListeners() {
  6154. const {
  6155. hls
  6156. } = this;
  6157. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6158. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  6159. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6160. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6161. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6162. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6163. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6164. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6165. hls.on(Events.ERROR, this.onError, this);
  6166. }
  6167. unregisterListeners() {
  6168. const {
  6169. hls
  6170. } = this;
  6171. if (!hls) {
  6172. return;
  6173. }
  6174. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6175. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  6176. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6177. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6178. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6179. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6180. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6181. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6182. hls.off(Events.ERROR, this.onError, this);
  6183. }
  6184. destroy() {
  6185. this.unregisterListeners();
  6186. this.clearTimer();
  6187. // @ts-ignore
  6188. this.hls = this._abandonRulesCheck = null;
  6189. this.fragCurrent = this.partCurrent = null;
  6190. }
  6191. onManifestLoading(event, data) {
  6192. this.lastLoadedFragLevel = -1;
  6193. this.firstSelection = -1;
  6194. this.lastLevelLoadSec = 0;
  6195. this.fragCurrent = this.partCurrent = null;
  6196. this.onLevelsUpdated();
  6197. this.clearTimer();
  6198. }
  6199. onLevelsUpdated() {
  6200. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  6201. this.lastLoadedFragLevel = this.fragCurrent.level;
  6202. }
  6203. this._nextAutoLevel = -1;
  6204. this.onMaxAutoLevelUpdated();
  6205. this.codecTiers = null;
  6206. this.audioTracksByGroup = null;
  6207. }
  6208. onMaxAutoLevelUpdated() {
  6209. this.firstSelection = -1;
  6210. this.nextAutoLevelKey = '';
  6211. }
  6212. onFragLoading(event, data) {
  6213. const frag = data.frag;
  6214. if (this.ignoreFragment(frag)) {
  6215. return;
  6216. }
  6217. if (!frag.bitrateTest) {
  6218. var _data$part;
  6219. this.fragCurrent = frag;
  6220. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  6221. }
  6222. this.clearTimer();
  6223. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  6224. }
  6225. onLevelSwitching(event, data) {
  6226. this.clearTimer();
  6227. }
  6228. onError(event, data) {
  6229. if (data.fatal) {
  6230. return;
  6231. }
  6232. switch (data.details) {
  6233. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  6234. case ErrorDetails.BUFFER_APPEND_ERROR:
  6235. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  6236. this.lastLoadedFragLevel = -1;
  6237. this.firstSelection = -1;
  6238. break;
  6239. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  6240. {
  6241. const frag = data.frag;
  6242. const {
  6243. fragCurrent,
  6244. partCurrent: part
  6245. } = this;
  6246. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  6247. const now = performance.now();
  6248. const stats = part ? part.stats : frag.stats;
  6249. const timeLoading = now - stats.loading.start;
  6250. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6251. const loadedFirstByte = stats.loaded && ttfb > -1;
  6252. if (loadedFirstByte) {
  6253. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6254. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6255. } else {
  6256. this.bwEstimator.sampleTTFB(timeLoading);
  6257. }
  6258. }
  6259. break;
  6260. }
  6261. }
  6262. }
  6263. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  6264. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  6265. const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
  6266. return fragLoadSec + playlistLoadSec;
  6267. }
  6268. onLevelLoaded(event, data) {
  6269. const config = this.hls.config;
  6270. const {
  6271. loading
  6272. } = data.stats;
  6273. const timeLoadingMs = loading.end - loading.start;
  6274. if (isFiniteNumber(timeLoadingMs)) {
  6275. this.lastLevelLoadSec = timeLoadingMs / 1000;
  6276. }
  6277. if (data.details.live) {
  6278. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  6279. } else {
  6280. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  6281. }
  6282. }
  6283. onFragLoaded(event, {
  6284. frag,
  6285. part
  6286. }) {
  6287. const stats = part ? part.stats : frag.stats;
  6288. if (frag.type === PlaylistLevelType.MAIN) {
  6289. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  6290. }
  6291. if (this.ignoreFragment(frag)) {
  6292. return;
  6293. }
  6294. // stop monitoring bw once frag loaded
  6295. this.clearTimer();
  6296. // reset forced auto level value so that next level will be selected
  6297. if (frag.level === this._nextAutoLevel) {
  6298. this._nextAutoLevel = -1;
  6299. }
  6300. this.firstSelection = -1;
  6301. // compute level average bitrate
  6302. if (this.hls.config.abrMaxWithRealBitrate) {
  6303. const duration = part ? part.duration : frag.duration;
  6304. const level = this.hls.levels[frag.level];
  6305. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  6306. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  6307. level.loaded = {
  6308. bytes: loadedBytes,
  6309. duration: loadedDuration
  6310. };
  6311. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  6312. }
  6313. if (frag.bitrateTest) {
  6314. const fragBufferedData = {
  6315. stats,
  6316. frag,
  6317. part,
  6318. id: frag.type
  6319. };
  6320. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  6321. frag.bitrateTest = false;
  6322. } else {
  6323. // store level id after successful fragment load for playback
  6324. this.lastLoadedFragLevel = frag.level;
  6325. }
  6326. }
  6327. onFragBuffered(event, data) {
  6328. const {
  6329. frag,
  6330. part
  6331. } = data;
  6332. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  6333. if (stats.aborted) {
  6334. return;
  6335. }
  6336. if (this.ignoreFragment(frag)) {
  6337. return;
  6338. }
  6339. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  6340. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  6341. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  6342. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  6343. this.bwEstimator.sample(processingMs, stats.loaded);
  6344. stats.bwEstimate = this.getBwEstimate();
  6345. if (frag.bitrateTest) {
  6346. this.bitrateTestDelay = processingMs / 1000;
  6347. } else {
  6348. this.bitrateTestDelay = 0;
  6349. }
  6350. }
  6351. ignoreFragment(frag) {
  6352. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  6353. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  6354. }
  6355. clearTimer() {
  6356. if (this.timer > -1) {
  6357. self.clearInterval(this.timer);
  6358. this.timer = -1;
  6359. }
  6360. }
  6361. get firstAutoLevel() {
  6362. const {
  6363. maxAutoLevel,
  6364. minAutoLevel
  6365. } = this.hls;
  6366. const bwEstimate = this.getBwEstimate();
  6367. const maxStartDelay = this.hls.config.maxStarvationDelay;
  6368. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  6369. if (abrAutoLevel > -1) {
  6370. return abrAutoLevel;
  6371. }
  6372. const firstLevel = this.hls.firstLevel;
  6373. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  6374. logger.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  6375. return clamped;
  6376. }
  6377. get forcedAutoLevel() {
  6378. if (this.nextAutoLevelKey) {
  6379. return -1;
  6380. }
  6381. return this._nextAutoLevel;
  6382. }
  6383. // return next auto level
  6384. get nextAutoLevel() {
  6385. const forcedAutoLevel = this.forcedAutoLevel;
  6386. const bwEstimator = this.bwEstimator;
  6387. const useEstimate = bwEstimator.canEstimate();
  6388. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  6389. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  6390. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  6391. return forcedAutoLevel;
  6392. }
  6393. // compute next level using ABR logic
  6394. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  6395. // use forced auto level while it hasn't errored more than ABR selection
  6396. if (forcedAutoLevel !== -1) {
  6397. const levels = this.hls.levels;
  6398. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  6399. return forcedAutoLevel;
  6400. }
  6401. }
  6402. // save result until state has changed
  6403. this._nextAutoLevel = nextABRAutoLevel;
  6404. this.nextAutoLevelKey = this.getAutoLevelKey();
  6405. return nextABRAutoLevel;
  6406. }
  6407. getAutoLevelKey() {
  6408. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  6409. }
  6410. getNextABRAutoLevel() {
  6411. const {
  6412. fragCurrent,
  6413. partCurrent,
  6414. hls
  6415. } = this;
  6416. const {
  6417. maxAutoLevel,
  6418. config,
  6419. minAutoLevel
  6420. } = hls;
  6421. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6422. const avgbw = this.getBwEstimate();
  6423. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  6424. const bufferStarvationDelay = this.getStarvationDelay();
  6425. let bwFactor = config.abrBandWidthFactor;
  6426. let bwUpFactor = config.abrBandWidthUpFactor;
  6427. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  6428. if (bufferStarvationDelay) {
  6429. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  6430. if (_bestLevel >= 0) {
  6431. return _bestLevel;
  6432. }
  6433. }
  6434. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  6435. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  6436. if (!bufferStarvationDelay) {
  6437. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  6438. const bitrateTestDelay = this.bitrateTestDelay;
  6439. if (bitrateTestDelay) {
  6440. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  6441. // max video loading delay used in automatic start level selection :
  6442. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  6443. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  6444. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  6445. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  6446. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  6447. logger.info(`[abr] bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);
  6448. // don't use conservative factor on bitrate test
  6449. bwFactor = bwUpFactor = 1;
  6450. }
  6451. }
  6452. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  6453. logger.info(`[abr] ${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);
  6454. if (bestLevel > -1) {
  6455. return bestLevel;
  6456. }
  6457. // If no matching level found, see if min auto level would be a better option
  6458. const minLevel = hls.levels[minAutoLevel];
  6459. const autoLevel = hls.levels[hls.loadLevel];
  6460. if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) {
  6461. return minAutoLevel;
  6462. }
  6463. // or if bitrate is not lower, continue to use loadLevel
  6464. return hls.loadLevel;
  6465. }
  6466. getStarvationDelay() {
  6467. const hls = this.hls;
  6468. const media = hls.media;
  6469. if (!media) {
  6470. return Infinity;
  6471. }
  6472. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  6473. // if we're playing back at the normal rate.
  6474. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  6475. const bufferInfo = hls.mainForwardBufferInfo;
  6476. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  6477. }
  6478. getBwEstimate() {
  6479. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  6480. }
  6481. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  6482. var _level$details;
  6483. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  6484. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  6485. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  6486. const {
  6487. fragCurrent,
  6488. partCurrent
  6489. } = this;
  6490. const {
  6491. levels,
  6492. allAudioTracks,
  6493. loadLevel,
  6494. config
  6495. } = this.hls;
  6496. if (levels.length === 1) {
  6497. return 0;
  6498. }
  6499. const level = levels[selectionBaseLevel];
  6500. const live = !!(level != null && (_level$details = level.details) != null && _level$details.live);
  6501. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  6502. let currentCodecSet;
  6503. let currentVideoRange = 'SDR';
  6504. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  6505. const {
  6506. audioPreference,
  6507. videoPreference
  6508. } = config;
  6509. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  6510. if (firstSelection) {
  6511. if (this.firstSelection !== -1) {
  6512. return this.firstSelection;
  6513. }
  6514. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  6515. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  6516. const {
  6517. codecSet,
  6518. videoRanges,
  6519. minFramerate,
  6520. minBitrate,
  6521. preferHDR
  6522. } = startTier;
  6523. currentCodecSet = codecSet;
  6524. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  6525. currentFrameRate = minFramerate;
  6526. currentBw = Math.max(currentBw, minBitrate);
  6527. logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`);
  6528. } else {
  6529. currentCodecSet = level == null ? void 0 : level.codecSet;
  6530. currentVideoRange = level == null ? void 0 : level.videoRange;
  6531. }
  6532. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6533. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  6534. const levelsSkipped = [];
  6535. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  6536. var _levelInfo$supportedR;
  6537. const levelInfo = levels[i];
  6538. const upSwitch = i > selectionBaseLevel;
  6539. if (!levelInfo) {
  6540. continue;
  6541. }
  6542. // skip candidates which change codec-family or video-range,
  6543. // and which decrease or increase frame-rate for up and down-switch respectfully
  6544. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) {
  6545. levelsSkipped.push(i);
  6546. continue;
  6547. }
  6548. const levelDetails = levelInfo.details;
  6549. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  6550. let adjustedbw;
  6551. // follow algorithm captured from stagefright :
  6552. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  6553. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  6554. // consider only 80% of the available bandwidth, but if we are switching up,
  6555. // be even more conservative (70%) to avoid overestimating and immediately
  6556. // switching back.
  6557. if (!upSwitch) {
  6558. adjustedbw = bwFactor * currentBw;
  6559. } else {
  6560. adjustedbw = bwUpFactor * currentBw;
  6561. }
  6562. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  6563. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i].averageBitrate : levels[i].maxBitrate;
  6564. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  6565. const canSwitchWithinTolerance =
  6566. // if adjusted bw is greater than level bitrate AND
  6567. adjustedbw >= bitrate && (
  6568. // no level change, or new level has no error history
  6569. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  6570. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  6571. // 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 ...
  6572. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  6573. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  6574. if (canSwitchWithinTolerance) {
  6575. const forcedAutoLevel = this.forcedAutoLevel;
  6576. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  6577. if (levelsSkipped.length) {
  6578. logger.trace(`[abr] Skipped level(s) ${levelsSkipped.join(',')} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${level.codecs}" ${currentVideoRange}`);
  6579. }
  6580. logger.info(`[abr] 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:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`);
  6581. }
  6582. if (firstSelection) {
  6583. this.firstSelection = i;
  6584. }
  6585. // as we are looping from highest to lowest, this will return the best achievable quality level
  6586. return i;
  6587. }
  6588. }
  6589. // not enough time budget even with quality level 0 ... rebuffering might happen
  6590. return -1;
  6591. }
  6592. set nextAutoLevel(nextLevel) {
  6593. const {
  6594. maxAutoLevel,
  6595. minAutoLevel
  6596. } = this.hls;
  6597. const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  6598. if (this._nextAutoLevel !== value) {
  6599. this.nextAutoLevelKey = '';
  6600. this._nextAutoLevel = value;
  6601. }
  6602. }
  6603. }
  6604. /**
  6605. * Provides methods dealing with buffer length retrieval for example.
  6606. *
  6607. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  6608. *
  6609. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  6610. */
  6611. const noopBuffered = {
  6612. length: 0,
  6613. start: () => 0,
  6614. end: () => 0
  6615. };
  6616. class BufferHelper {
  6617. /**
  6618. * Return true if `media`'s buffered include `position`
  6619. */
  6620. static isBuffered(media, position) {
  6621. try {
  6622. if (media) {
  6623. const buffered = BufferHelper.getBuffered(media);
  6624. for (let i = 0; i < buffered.length; i++) {
  6625. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  6626. return true;
  6627. }
  6628. }
  6629. }
  6630. } catch (error) {
  6631. // this is to catch
  6632. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6633. // This SourceBuffer has been removed from the parent media source
  6634. }
  6635. return false;
  6636. }
  6637. static bufferInfo(media, pos, maxHoleDuration) {
  6638. try {
  6639. if (media) {
  6640. const vbuffered = BufferHelper.getBuffered(media);
  6641. const buffered = [];
  6642. let i;
  6643. for (i = 0; i < vbuffered.length; i++) {
  6644. buffered.push({
  6645. start: vbuffered.start(i),
  6646. end: vbuffered.end(i)
  6647. });
  6648. }
  6649. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  6650. }
  6651. } catch (error) {
  6652. // this is to catch
  6653. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6654. // This SourceBuffer has been removed from the parent media source
  6655. }
  6656. return {
  6657. len: 0,
  6658. start: pos,
  6659. end: pos,
  6660. nextStart: undefined
  6661. };
  6662. }
  6663. static bufferedInfo(buffered, pos, maxHoleDuration) {
  6664. pos = Math.max(0, pos);
  6665. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  6666. buffered.sort(function (a, b) {
  6667. const diff = a.start - b.start;
  6668. if (diff) {
  6669. return diff;
  6670. } else {
  6671. return b.end - a.end;
  6672. }
  6673. });
  6674. let buffered2 = [];
  6675. if (maxHoleDuration) {
  6676. // there might be some small holes between buffer time range
  6677. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6678. // buffer time range representations that discards those holes
  6679. for (let i = 0; i < buffered.length; i++) {
  6680. const buf2len = buffered2.length;
  6681. if (buf2len) {
  6682. const buf2end = buffered2[buf2len - 1].end;
  6683. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6684. if (buffered[i].start - buf2end < maxHoleDuration) {
  6685. // merge overlapping time ranges
  6686. // update lastRange.end only if smaller than item.end
  6687. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6688. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6689. if (buffered[i].end > buf2end) {
  6690. buffered2[buf2len - 1].end = buffered[i].end;
  6691. }
  6692. } else {
  6693. // big hole
  6694. buffered2.push(buffered[i]);
  6695. }
  6696. } else {
  6697. // first value
  6698. buffered2.push(buffered[i]);
  6699. }
  6700. }
  6701. } else {
  6702. buffered2 = buffered;
  6703. }
  6704. let bufferLen = 0;
  6705. // bufferStartNext can possibly be undefined based on the conditional logic below
  6706. let bufferStartNext;
  6707. // bufferStart and bufferEnd are buffer boundaries around current video position
  6708. let bufferStart = pos;
  6709. let bufferEnd = pos;
  6710. for (let i = 0; i < buffered2.length; i++) {
  6711. const start = buffered2[i].start;
  6712. const end = buffered2[i].end;
  6713. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  6714. if (pos + maxHoleDuration >= start && pos < end) {
  6715. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  6716. bufferStart = start;
  6717. bufferEnd = end;
  6718. bufferLen = bufferEnd - pos;
  6719. } else if (pos + maxHoleDuration < start) {
  6720. bufferStartNext = start;
  6721. break;
  6722. }
  6723. }
  6724. return {
  6725. len: bufferLen,
  6726. start: bufferStart || 0,
  6727. end: bufferEnd || 0,
  6728. nextStart: bufferStartNext
  6729. };
  6730. }
  6731. /**
  6732. * Safe method to get buffered property.
  6733. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  6734. */
  6735. static getBuffered(media) {
  6736. try {
  6737. return media.buffered;
  6738. } catch (e) {
  6739. logger.log('failed to get media.buffered', e);
  6740. return noopBuffered;
  6741. }
  6742. }
  6743. }
  6744. class BufferOperationQueue {
  6745. constructor(sourceBufferReference) {
  6746. this.buffers = void 0;
  6747. this.queues = {
  6748. video: [],
  6749. audio: [],
  6750. audiovideo: []
  6751. };
  6752. this.buffers = sourceBufferReference;
  6753. }
  6754. append(operation, type, pending) {
  6755. const queue = this.queues[type];
  6756. queue.push(operation);
  6757. if (queue.length === 1 && !pending) {
  6758. this.executeNext(type);
  6759. }
  6760. }
  6761. insertAbort(operation, type) {
  6762. const queue = this.queues[type];
  6763. queue.unshift(operation);
  6764. this.executeNext(type);
  6765. }
  6766. appendBlocker(type) {
  6767. let execute;
  6768. const promise = new Promise(resolve => {
  6769. execute = resolve;
  6770. });
  6771. const operation = {
  6772. execute,
  6773. onStart: () => {},
  6774. onComplete: () => {},
  6775. onError: () => {}
  6776. };
  6777. this.append(operation, type);
  6778. return promise;
  6779. }
  6780. executeNext(type) {
  6781. const queue = this.queues[type];
  6782. if (queue.length) {
  6783. const operation = queue[0];
  6784. try {
  6785. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  6786. // which do not end with this event must call _onSBUpdateEnd manually
  6787. operation.execute();
  6788. } catch (error) {
  6789. logger.warn(`[buffer-operation-queue]: Exception executing "${type}" SourceBuffer operation: ${error}`);
  6790. operation.onError(error);
  6791. // Only shift the current operation off, otherwise the updateend handler will do this for us
  6792. const sb = this.buffers[type];
  6793. if (!(sb != null && sb.updating)) {
  6794. this.shiftAndExecuteNext(type);
  6795. }
  6796. }
  6797. }
  6798. }
  6799. shiftAndExecuteNext(type) {
  6800. this.queues[type].shift();
  6801. this.executeNext(type);
  6802. }
  6803. current(type) {
  6804. return this.queues[type][0];
  6805. }
  6806. }
  6807. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  6808. class BufferController {
  6809. constructor(hls) {
  6810. // The level details used to determine duration, target-duration and live
  6811. this.details = null;
  6812. // cache the self generated object url to detect hijack of video tag
  6813. this._objectUrl = null;
  6814. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  6815. this.operationQueue = void 0;
  6816. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  6817. this.listeners = void 0;
  6818. this.hls = void 0;
  6819. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  6820. this.bufferCodecEventsExpected = 0;
  6821. // The total number of BUFFER_CODEC events received
  6822. this._bufferCodecEventsTotal = 0;
  6823. // A reference to the attached media element
  6824. this.media = null;
  6825. // A reference to the active media source
  6826. this.mediaSource = null;
  6827. // Last MP3 audio chunk appended
  6828. this.lastMpegAudioChunk = null;
  6829. this.appendSource = void 0;
  6830. // counters
  6831. this.appendErrors = {
  6832. audio: 0,
  6833. video: 0,
  6834. audiovideo: 0
  6835. };
  6836. this.tracks = {};
  6837. this.pendingTracks = {};
  6838. this.sourceBuffer = void 0;
  6839. this.log = void 0;
  6840. this.warn = void 0;
  6841. this.error = void 0;
  6842. this._onEndStreaming = event => {
  6843. if (!this.hls) {
  6844. return;
  6845. }
  6846. this.hls.pauseBuffering();
  6847. };
  6848. this._onStartStreaming = event => {
  6849. if (!this.hls) {
  6850. return;
  6851. }
  6852. this.hls.resumeBuffering();
  6853. };
  6854. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  6855. this._onMediaSourceOpen = () => {
  6856. const {
  6857. media,
  6858. mediaSource
  6859. } = this;
  6860. this.log('Media source opened');
  6861. if (media) {
  6862. media.removeEventListener('emptied', this._onMediaEmptied);
  6863. this.updateMediaElementDuration();
  6864. this.hls.trigger(Events.MEDIA_ATTACHED, {
  6865. media,
  6866. mediaSource: mediaSource
  6867. });
  6868. }
  6869. if (mediaSource) {
  6870. // once received, don't listen anymore to sourceopen event
  6871. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  6872. }
  6873. this.checkPendingTracks();
  6874. };
  6875. this._onMediaSourceClose = () => {
  6876. this.log('Media source closed');
  6877. };
  6878. this._onMediaSourceEnded = () => {
  6879. this.log('Media source ended');
  6880. };
  6881. this._onMediaEmptied = () => {
  6882. const {
  6883. mediaSrc,
  6884. _objectUrl
  6885. } = this;
  6886. if (mediaSrc !== _objectUrl) {
  6887. logger.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  6888. }
  6889. };
  6890. this.hls = hls;
  6891. const logPrefix = '[buffer-controller]';
  6892. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  6893. this.log = logger.log.bind(logger, logPrefix);
  6894. this.warn = logger.warn.bind(logger, logPrefix);
  6895. this.error = logger.error.bind(logger, logPrefix);
  6896. this._initSourceBuffer();
  6897. this.registerListeners();
  6898. }
  6899. hasSourceTypes() {
  6900. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  6901. }
  6902. destroy() {
  6903. this.unregisterListeners();
  6904. this.details = null;
  6905. this.lastMpegAudioChunk = null;
  6906. // @ts-ignore
  6907. this.hls = null;
  6908. }
  6909. registerListeners() {
  6910. const {
  6911. hls
  6912. } = this;
  6913. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  6914. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  6915. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6916. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  6917. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  6918. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  6919. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  6920. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  6921. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  6922. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  6923. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  6924. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  6925. }
  6926. unregisterListeners() {
  6927. const {
  6928. hls
  6929. } = this;
  6930. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  6931. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  6932. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6933. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  6934. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  6935. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  6936. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  6937. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  6938. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  6939. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  6940. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  6941. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  6942. }
  6943. _initSourceBuffer() {
  6944. this.sourceBuffer = {};
  6945. this.operationQueue = new BufferOperationQueue(this.sourceBuffer);
  6946. this.listeners = {
  6947. audio: [],
  6948. video: [],
  6949. audiovideo: []
  6950. };
  6951. this.appendErrors = {
  6952. audio: 0,
  6953. video: 0,
  6954. audiovideo: 0
  6955. };
  6956. this.lastMpegAudioChunk = null;
  6957. }
  6958. onManifestLoading() {
  6959. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;
  6960. this.details = null;
  6961. }
  6962. onManifestParsed(event, data) {
  6963. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  6964. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  6965. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  6966. // it will contain the expected nb of source buffers, no need to compute it
  6967. let codecEvents = 2;
  6968. if (data.audio && !data.video || !data.altAudio || !false) {
  6969. codecEvents = 1;
  6970. }
  6971. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  6972. this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);
  6973. }
  6974. onMediaAttaching(event, data) {
  6975. const media = this.media = data.media;
  6976. const MediaSource = getMediaSource(this.appendSource);
  6977. if (media && MediaSource) {
  6978. var _ms$constructor;
  6979. const ms = this.mediaSource = new MediaSource();
  6980. this.log(`created media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
  6981. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  6982. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  6983. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  6984. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  6985. if (this.appendSource) {
  6986. ms.addEventListener('startstreaming', this._onStartStreaming);
  6987. ms.addEventListener('endstreaming', this._onEndStreaming);
  6988. }
  6989. // cache the locally generated object url
  6990. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  6991. // link video and media Source
  6992. if (this.appendSource) {
  6993. try {
  6994. media.removeAttribute('src');
  6995. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  6996. const MMS = self.ManagedMediaSource;
  6997. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  6998. removeSourceChildren(media);
  6999. addSource(media, objectUrl);
  7000. media.load();
  7001. } catch (error) {
  7002. media.src = objectUrl;
  7003. }
  7004. } else {
  7005. media.src = objectUrl;
  7006. }
  7007. media.addEventListener('emptied', this._onMediaEmptied);
  7008. }
  7009. }
  7010. onMediaDetaching() {
  7011. const {
  7012. media,
  7013. mediaSource,
  7014. _objectUrl
  7015. } = this;
  7016. if (mediaSource) {
  7017. this.log('media source detaching');
  7018. if (mediaSource.readyState === 'open') {
  7019. try {
  7020. // endOfStream could trigger exception if any sourcebuffer is in updating state
  7021. // we don't really care about checking sourcebuffer state here,
  7022. // as we are anyway detaching the MediaSource
  7023. // let's just avoid this exception to propagate
  7024. mediaSource.endOfStream();
  7025. } catch (err) {
  7026. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  7027. }
  7028. }
  7029. // Clean up the SourceBuffers by invoking onBufferReset
  7030. this.onBufferReset();
  7031. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  7032. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  7033. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  7034. if (this.appendSource) {
  7035. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  7036. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  7037. }
  7038. // Detach properly the MediaSource from the HTMLMediaElement as
  7039. // suggested in https://github.com/w3c/media-source/issues/53.
  7040. if (media) {
  7041. media.removeEventListener('emptied', this._onMediaEmptied);
  7042. if (_objectUrl) {
  7043. self.URL.revokeObjectURL(_objectUrl);
  7044. }
  7045. // clean up video tag src only if it's our own url. some external libraries might
  7046. // hijack the video tag and change its 'src' without destroying the Hls instance first
  7047. if (this.mediaSrc === _objectUrl) {
  7048. media.removeAttribute('src');
  7049. if (this.appendSource) {
  7050. removeSourceChildren(media);
  7051. }
  7052. media.load();
  7053. } else {
  7054. this.warn('media|source.src was changed by a third party - skip cleanup');
  7055. }
  7056. }
  7057. this.mediaSource = null;
  7058. this.media = null;
  7059. this._objectUrl = null;
  7060. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  7061. this.pendingTracks = {};
  7062. this.tracks = {};
  7063. }
  7064. this.hls.trigger(Events.MEDIA_DETACHED, undefined);
  7065. }
  7066. onBufferReset() {
  7067. this.getSourceBufferTypes().forEach(type => {
  7068. this.resetBuffer(type);
  7069. });
  7070. this._initSourceBuffer();
  7071. }
  7072. resetBuffer(type) {
  7073. const sb = this.sourceBuffer[type];
  7074. try {
  7075. if (sb) {
  7076. var _this$mediaSource;
  7077. this.removeBufferListeners(type);
  7078. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  7079. // accessing it
  7080. this.sourceBuffer[type] = undefined;
  7081. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  7082. this.mediaSource.removeSourceBuffer(sb);
  7083. }
  7084. }
  7085. } catch (err) {
  7086. this.warn(`onBufferReset ${type}`, err);
  7087. }
  7088. }
  7089. onBufferCodecs(event, data) {
  7090. const sourceBufferCount = this.getSourceBufferTypes().length;
  7091. const trackNames = Object.keys(data);
  7092. trackNames.forEach(trackName => {
  7093. if (sourceBufferCount) {
  7094. // check if SourceBuffer codec needs to change
  7095. const track = this.tracks[trackName];
  7096. if (track && typeof track.buffer.changeType === 'function') {
  7097. var _trackCodec;
  7098. const {
  7099. id,
  7100. codec,
  7101. levelCodec,
  7102. container,
  7103. metadata
  7104. } = data[trackName];
  7105. const currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec);
  7106. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7107. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  7108. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7109. if (trackCodec && currentCodec !== nextCodec) {
  7110. if (trackName.slice(0, 5) === 'audio') {
  7111. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  7112. }
  7113. const mimeType = `${container};codecs=${trackCodec}`;
  7114. this.appendChangeType(trackName, mimeType);
  7115. this.log(`switching codec ${currentCodecFull} to ${trackCodec}`);
  7116. this.tracks[trackName] = {
  7117. buffer: track.buffer,
  7118. codec,
  7119. container,
  7120. levelCodec,
  7121. metadata,
  7122. id
  7123. };
  7124. }
  7125. }
  7126. } else {
  7127. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  7128. this.pendingTracks[trackName] = data[trackName];
  7129. }
  7130. });
  7131. // if sourcebuffers already created, do nothing ...
  7132. if (sourceBufferCount) {
  7133. return;
  7134. }
  7135. const bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  7136. if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {
  7137. this.log(`${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(',')}`);
  7138. this.bufferCodecEventsExpected = bufferCodecEventsExpected;
  7139. }
  7140. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  7141. this.checkPendingTracks();
  7142. }
  7143. }
  7144. appendChangeType(type, mimeType) {
  7145. const {
  7146. operationQueue
  7147. } = this;
  7148. const operation = {
  7149. execute: () => {
  7150. const sb = this.sourceBuffer[type];
  7151. if (sb) {
  7152. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  7153. sb.changeType(mimeType);
  7154. }
  7155. operationQueue.shiftAndExecuteNext(type);
  7156. },
  7157. onStart: () => {},
  7158. onComplete: () => {},
  7159. onError: error => {
  7160. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  7161. }
  7162. };
  7163. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7164. }
  7165. onBufferAppending(event, eventData) {
  7166. const {
  7167. hls,
  7168. operationQueue,
  7169. tracks
  7170. } = this;
  7171. const {
  7172. data,
  7173. type,
  7174. frag,
  7175. part,
  7176. chunkMeta
  7177. } = eventData;
  7178. const chunkStats = chunkMeta.buffering[type];
  7179. const bufferAppendingStart = self.performance.now();
  7180. chunkStats.start = bufferAppendingStart;
  7181. const fragBuffering = frag.stats.buffering;
  7182. const partBuffering = part ? part.stats.buffering : null;
  7183. if (fragBuffering.start === 0) {
  7184. fragBuffering.start = bufferAppendingStart;
  7185. }
  7186. if (partBuffering && partBuffering.start === 0) {
  7187. partBuffering.start = bufferAppendingStart;
  7188. }
  7189. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  7190. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  7191. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  7192. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  7193. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  7194. const audioTrack = tracks.audio;
  7195. let checkTimestampOffset = false;
  7196. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  7197. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  7198. this.lastMpegAudioChunk = chunkMeta;
  7199. }
  7200. const fragStart = frag.start;
  7201. const operation = {
  7202. execute: () => {
  7203. chunkStats.executeStart = self.performance.now();
  7204. if (checkTimestampOffset) {
  7205. const sb = this.sourceBuffer[type];
  7206. if (sb) {
  7207. const delta = fragStart - sb.timestampOffset;
  7208. if (Math.abs(delta) >= 0.1) {
  7209. this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`);
  7210. sb.timestampOffset = fragStart;
  7211. }
  7212. }
  7213. }
  7214. this.appendExecutor(data, type);
  7215. },
  7216. onStart: () => {
  7217. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  7218. },
  7219. onComplete: () => {
  7220. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  7221. const end = self.performance.now();
  7222. chunkStats.executeEnd = chunkStats.end = end;
  7223. if (fragBuffering.first === 0) {
  7224. fragBuffering.first = end;
  7225. }
  7226. if (partBuffering && partBuffering.first === 0) {
  7227. partBuffering.first = end;
  7228. }
  7229. const {
  7230. sourceBuffer
  7231. } = this;
  7232. const timeRanges = {};
  7233. for (const type in sourceBuffer) {
  7234. timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);
  7235. }
  7236. this.appendErrors[type] = 0;
  7237. if (type === 'audio' || type === 'video') {
  7238. this.appendErrors.audiovideo = 0;
  7239. } else {
  7240. this.appendErrors.audio = 0;
  7241. this.appendErrors.video = 0;
  7242. }
  7243. this.hls.trigger(Events.BUFFER_APPENDED, {
  7244. type,
  7245. frag,
  7246. part,
  7247. chunkMeta,
  7248. parent: frag.type,
  7249. timeRanges
  7250. });
  7251. },
  7252. onError: error => {
  7253. // in case any error occured while appending, put back segment in segments table
  7254. const event = {
  7255. type: ErrorTypes.MEDIA_ERROR,
  7256. parent: frag.type,
  7257. details: ErrorDetails.BUFFER_APPEND_ERROR,
  7258. sourceBufferName: type,
  7259. frag,
  7260. part,
  7261. chunkMeta,
  7262. error,
  7263. err: error,
  7264. fatal: false
  7265. };
  7266. if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
  7267. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  7268. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  7269. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  7270. } else {
  7271. const appendErrorCount = ++this.appendErrors[type];
  7272. event.details = ErrorDetails.BUFFER_APPEND_ERROR;
  7273. /* with UHD content, we could get loop of quota exceeded error until
  7274. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  7275. */
  7276. this.warn(`Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer`);
  7277. if (appendErrorCount >= hls.config.appendErrorMaxRetry) {
  7278. event.fatal = true;
  7279. }
  7280. }
  7281. hls.trigger(Events.ERROR, event);
  7282. }
  7283. };
  7284. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7285. }
  7286. onBufferFlushing(event, data) {
  7287. const {
  7288. operationQueue
  7289. } = this;
  7290. const flushOperation = type => ({
  7291. execute: this.removeExecutor.bind(this, type, data.startOffset, data.endOffset),
  7292. onStart: () => {
  7293. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7294. },
  7295. onComplete: () => {
  7296. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7297. this.hls.trigger(Events.BUFFER_FLUSHED, {
  7298. type
  7299. });
  7300. },
  7301. onError: error => {
  7302. this.warn(`Failed to remove from ${type} SourceBuffer`, error);
  7303. }
  7304. });
  7305. if (data.type) {
  7306. operationQueue.append(flushOperation(data.type), data.type);
  7307. } else {
  7308. this.getSourceBufferTypes().forEach(type => {
  7309. operationQueue.append(flushOperation(type), type);
  7310. });
  7311. }
  7312. }
  7313. onFragParsed(event, data) {
  7314. const {
  7315. frag,
  7316. part
  7317. } = data;
  7318. const buffersAppendedTo = [];
  7319. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  7320. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  7321. buffersAppendedTo.push('audiovideo');
  7322. } else {
  7323. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  7324. buffersAppendedTo.push('audio');
  7325. }
  7326. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  7327. buffersAppendedTo.push('video');
  7328. }
  7329. }
  7330. const onUnblocked = () => {
  7331. const now = self.performance.now();
  7332. frag.stats.buffering.end = now;
  7333. if (part) {
  7334. part.stats.buffering.end = now;
  7335. }
  7336. const stats = part ? part.stats : frag.stats;
  7337. this.hls.trigger(Events.FRAG_BUFFERED, {
  7338. frag,
  7339. part,
  7340. stats,
  7341. id: frag.type
  7342. });
  7343. };
  7344. if (buffersAppendedTo.length === 0) {
  7345. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  7346. }
  7347. this.blockBuffers(onUnblocked, buffersAppendedTo);
  7348. }
  7349. onFragChanged(event, data) {
  7350. this.trimBuffers();
  7351. }
  7352. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  7353. // an undefined data.type will mark all buffers as EOS.
  7354. onBufferEos(event, data) {
  7355. const ended = this.getSourceBufferTypes().reduce((acc, type) => {
  7356. const sb = this.sourceBuffer[type];
  7357. if (sb && (!data.type || data.type === type)) {
  7358. sb.ending = true;
  7359. if (!sb.ended) {
  7360. sb.ended = true;
  7361. this.log(`${type} sourceBuffer now EOS`);
  7362. }
  7363. }
  7364. return acc && !!(!sb || sb.ended);
  7365. }, true);
  7366. if (ended) {
  7367. this.log(`Queueing mediaSource.endOfStream()`);
  7368. this.blockBuffers(() => {
  7369. this.getSourceBufferTypes().forEach(type => {
  7370. const sb = this.sourceBuffer[type];
  7371. if (sb) {
  7372. sb.ending = false;
  7373. }
  7374. });
  7375. const {
  7376. mediaSource
  7377. } = this;
  7378. if (!mediaSource || mediaSource.readyState !== 'open') {
  7379. if (mediaSource) {
  7380. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  7381. }
  7382. return;
  7383. }
  7384. this.log(`Calling mediaSource.endOfStream()`);
  7385. // Allow this to throw and be caught by the enqueueing function
  7386. mediaSource.endOfStream();
  7387. });
  7388. }
  7389. }
  7390. onLevelUpdated(event, {
  7391. details
  7392. }) {
  7393. if (!details.fragments.length) {
  7394. return;
  7395. }
  7396. this.details = details;
  7397. if (this.getSourceBufferTypes().length) {
  7398. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  7399. } else {
  7400. this.updateMediaElementDuration();
  7401. }
  7402. }
  7403. trimBuffers() {
  7404. const {
  7405. hls,
  7406. details,
  7407. media
  7408. } = this;
  7409. if (!media || details === null) {
  7410. return;
  7411. }
  7412. const sourceBufferTypes = this.getSourceBufferTypes();
  7413. if (!sourceBufferTypes.length) {
  7414. return;
  7415. }
  7416. const config = hls.config;
  7417. const currentTime = media.currentTime;
  7418. const targetDuration = details.levelTargetDuration;
  7419. // Support for deprecated liveBackBufferLength
  7420. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  7421. if (isFiniteNumber(backBufferLength) && backBufferLength > 0) {
  7422. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  7423. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  7424. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  7425. }
  7426. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  7427. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  7428. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  7429. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  7430. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  7431. }
  7432. }
  7433. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  7434. const {
  7435. details,
  7436. sourceBuffer
  7437. } = this;
  7438. const sourceBufferTypes = this.getSourceBufferTypes();
  7439. sourceBufferTypes.forEach(type => {
  7440. const sb = sourceBuffer[type];
  7441. if (sb) {
  7442. const buffered = BufferHelper.getBuffered(sb);
  7443. // when target buffer start exceeds actual buffer start
  7444. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  7445. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  7446. bufferEnd: targetBackBufferPosition
  7447. });
  7448. // Support for deprecated event:
  7449. if (details != null && details.live) {
  7450. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  7451. bufferEnd: targetBackBufferPosition
  7452. });
  7453. } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) {
  7454. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  7455. return;
  7456. }
  7457. this.hls.trigger(Events.BUFFER_FLUSHING, {
  7458. startOffset: 0,
  7459. endOffset: targetBackBufferPosition,
  7460. type
  7461. });
  7462. }
  7463. }
  7464. });
  7465. }
  7466. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  7467. const {
  7468. sourceBuffer
  7469. } = this;
  7470. const sourceBufferTypes = this.getSourceBufferTypes();
  7471. sourceBufferTypes.forEach(type => {
  7472. const sb = sourceBuffer[type];
  7473. if (sb) {
  7474. const buffered = BufferHelper.getBuffered(sb);
  7475. const numBufferedRanges = buffered.length;
  7476. // The buffer is either empty or contiguous
  7477. if (numBufferedRanges < 2) {
  7478. return;
  7479. }
  7480. const bufferStart = buffered.start(numBufferedRanges - 1);
  7481. const bufferEnd = buffered.end(numBufferedRanges - 1);
  7482. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  7483. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  7484. return;
  7485. } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {
  7486. this.log(`Cannot flush ${type} front buffer while SourceBuffer is in ended state`);
  7487. return;
  7488. }
  7489. this.hls.trigger(Events.BUFFER_FLUSHING, {
  7490. startOffset: bufferStart,
  7491. endOffset: Infinity,
  7492. type
  7493. });
  7494. }
  7495. });
  7496. }
  7497. /**
  7498. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  7499. * 'liveDurationInfinity` is set to `true`
  7500. * More details: https://github.com/video-dev/hls.js/issues/355
  7501. */
  7502. updateMediaElementDuration() {
  7503. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  7504. return;
  7505. }
  7506. const {
  7507. details,
  7508. hls,
  7509. media,
  7510. mediaSource
  7511. } = this;
  7512. const levelDuration = details.fragments[0].start + details.totalduration;
  7513. const mediaDuration = media.duration;
  7514. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  7515. if (details.live && hls.config.liveDurationInfinity) {
  7516. // Override duration to Infinity
  7517. mediaSource.duration = Infinity;
  7518. this.updateSeekableRange(details);
  7519. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) {
  7520. // levelDuration was the last value we set.
  7521. // not using mediaSource.duration as the browser may tweak this value
  7522. // only update Media Source duration if its value increase, this is to avoid
  7523. // flushing already buffered portion when switching between quality level
  7524. this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`);
  7525. mediaSource.duration = levelDuration;
  7526. }
  7527. }
  7528. updateSeekableRange(levelDetails) {
  7529. const mediaSource = this.mediaSource;
  7530. const fragments = levelDetails.fragments;
  7531. const len = fragments.length;
  7532. if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) {
  7533. const start = Math.max(0, fragments[0].start);
  7534. const end = Math.max(start, start + levelDetails.totalduration);
  7535. this.log(`Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  7536. mediaSource.setLiveSeekableRange(start, end);
  7537. }
  7538. }
  7539. checkPendingTracks() {
  7540. const {
  7541. bufferCodecEventsExpected,
  7542. operationQueue,
  7543. pendingTracks
  7544. } = this;
  7545. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  7546. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  7547. // data has been appended to existing ones.
  7548. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  7549. const pendingTracksCount = Object.keys(pendingTracks).length;
  7550. if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || 'audiovideo' in pendingTracks)) {
  7551. // ok, let's create them now !
  7552. this.createSourceBuffers(pendingTracks);
  7553. this.pendingTracks = {};
  7554. // append any pending segments now !
  7555. const buffers = this.getSourceBufferTypes();
  7556. if (buffers.length) {
  7557. this.hls.trigger(Events.BUFFER_CREATED, {
  7558. tracks: this.tracks
  7559. });
  7560. buffers.forEach(type => {
  7561. operationQueue.executeNext(type);
  7562. });
  7563. } else {
  7564. const error = new Error('could not create source buffer for media codec(s)');
  7565. this.hls.trigger(Events.ERROR, {
  7566. type: ErrorTypes.MEDIA_ERROR,
  7567. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  7568. fatal: true,
  7569. error,
  7570. reason: error.message
  7571. });
  7572. }
  7573. }
  7574. }
  7575. createSourceBuffers(tracks) {
  7576. const {
  7577. sourceBuffer,
  7578. mediaSource
  7579. } = this;
  7580. if (!mediaSource) {
  7581. throw Error('createSourceBuffers called when mediaSource was null');
  7582. }
  7583. for (const trackName in tracks) {
  7584. if (!sourceBuffer[trackName]) {
  7585. var _track$levelCodec;
  7586. const track = tracks[trackName];
  7587. if (!track) {
  7588. throw Error(`source buffer exists for track ${trackName}, however track does not`);
  7589. }
  7590. // use levelCodec as first priority unless it contains multiple comma-separated codec values
  7591. let codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(',')) === -1 ? track.levelCodec : track.codec;
  7592. if (codec) {
  7593. if (trackName.slice(0, 5) === 'audio') {
  7594. codec = getCodecCompatibleName(codec, this.appendSource);
  7595. }
  7596. }
  7597. const mimeType = `${track.container};codecs=${codec}`;
  7598. this.log(`creating sourceBuffer(${mimeType})`);
  7599. try {
  7600. const sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  7601. const sbName = trackName;
  7602. this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
  7603. this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
  7604. this.addBufferListener(sbName, 'error', this._onSBUpdateError);
  7605. // ManagedSourceBuffer bufferedchange event
  7606. if (this.appendSource) {
  7607. this.addBufferListener(sbName, 'bufferedchange', (type, event) => {
  7608. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  7609. const removedRanges = event.removedRanges;
  7610. if (removedRanges != null && removedRanges.length) {
  7611. this.hls.trigger(Events.BUFFER_FLUSHED, {
  7612. type: trackName
  7613. });
  7614. }
  7615. });
  7616. }
  7617. this.tracks[trackName] = {
  7618. buffer: sb,
  7619. codec: codec,
  7620. container: track.container,
  7621. levelCodec: track.levelCodec,
  7622. metadata: track.metadata,
  7623. id: track.id
  7624. };
  7625. } catch (err) {
  7626. this.error(`error while trying to add sourceBuffer: ${err.message}`);
  7627. this.hls.trigger(Events.ERROR, {
  7628. type: ErrorTypes.MEDIA_ERROR,
  7629. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  7630. fatal: false,
  7631. error: err,
  7632. sourceBufferName: trackName,
  7633. mimeType: mimeType
  7634. });
  7635. }
  7636. }
  7637. }
  7638. }
  7639. get mediaSrc() {
  7640. var _this$media, _this$media$querySele;
  7641. const media = ((_this$media = this.media) == null ? void 0 : (_this$media$querySele = _this$media.querySelector) == null ? void 0 : _this$media$querySele.call(_this$media, 'source')) || this.media;
  7642. return media == null ? void 0 : media.src;
  7643. }
  7644. _onSBUpdateStart(type) {
  7645. const {
  7646. operationQueue
  7647. } = this;
  7648. const operation = operationQueue.current(type);
  7649. operation.onStart();
  7650. }
  7651. _onSBUpdateEnd(type) {
  7652. var _this$mediaSource2;
  7653. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  7654. this.resetBuffer(type);
  7655. return;
  7656. }
  7657. const {
  7658. operationQueue
  7659. } = this;
  7660. const operation = operationQueue.current(type);
  7661. operation.onComplete();
  7662. operationQueue.shiftAndExecuteNext(type);
  7663. }
  7664. _onSBUpdateError(type, event) {
  7665. var _this$mediaSource3;
  7666. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState}`);
  7667. this.error(`${error}`, event);
  7668. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  7669. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  7670. this.hls.trigger(Events.ERROR, {
  7671. type: ErrorTypes.MEDIA_ERROR,
  7672. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  7673. sourceBufferName: type,
  7674. error,
  7675. fatal: false
  7676. });
  7677. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  7678. const operation = this.operationQueue.current(type);
  7679. if (operation) {
  7680. operation.onError(error);
  7681. }
  7682. }
  7683. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  7684. removeExecutor(type, startOffset, endOffset) {
  7685. const {
  7686. media,
  7687. mediaSource,
  7688. operationQueue,
  7689. sourceBuffer
  7690. } = this;
  7691. const sb = sourceBuffer[type];
  7692. if (!media || !mediaSource || !sb) {
  7693. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  7694. operationQueue.shiftAndExecuteNext(type);
  7695. return;
  7696. }
  7697. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  7698. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  7699. const removeStart = Math.max(0, startOffset);
  7700. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  7701. if (removeEnd > removeStart && (!sb.ending || sb.ended)) {
  7702. sb.ended = false;
  7703. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  7704. sb.remove(removeStart, removeEnd);
  7705. } else {
  7706. // Cycle the queue
  7707. operationQueue.shiftAndExecuteNext(type);
  7708. }
  7709. }
  7710. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  7711. appendExecutor(data, type) {
  7712. const sb = this.sourceBuffer[type];
  7713. if (!sb) {
  7714. if (!this.pendingTracks[type]) {
  7715. throw new Error(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  7716. }
  7717. return;
  7718. }
  7719. sb.ended = false;
  7720. sb.appendBuffer(data);
  7721. }
  7722. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  7723. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  7724. // upon completion, since we already do it here
  7725. blockBuffers(onUnblocked, buffers = this.getSourceBufferTypes()) {
  7726. if (!buffers.length) {
  7727. this.log('Blocking operation requested, but no SourceBuffers exist');
  7728. Promise.resolve().then(onUnblocked);
  7729. return;
  7730. }
  7731. const {
  7732. operationQueue
  7733. } = this;
  7734. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  7735. const blockingOperations = buffers.map(type => operationQueue.appendBlocker(type));
  7736. Promise.all(blockingOperations).then(() => {
  7737. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  7738. onUnblocked();
  7739. buffers.forEach(type => {
  7740. const sb = this.sourceBuffer[type];
  7741. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  7742. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  7743. // While this is a workaround, it's probably useful to have around
  7744. if (!(sb != null && sb.updating)) {
  7745. operationQueue.shiftAndExecuteNext(type);
  7746. }
  7747. });
  7748. });
  7749. }
  7750. getSourceBufferTypes() {
  7751. return Object.keys(this.sourceBuffer);
  7752. }
  7753. addBufferListener(type, event, fn) {
  7754. const buffer = this.sourceBuffer[type];
  7755. if (!buffer) {
  7756. return;
  7757. }
  7758. const listener = fn.bind(this, type);
  7759. this.listeners[type].push({
  7760. event,
  7761. listener
  7762. });
  7763. buffer.addEventListener(event, listener);
  7764. }
  7765. removeBufferListeners(type) {
  7766. const buffer = this.sourceBuffer[type];
  7767. if (!buffer) {
  7768. return;
  7769. }
  7770. this.listeners[type].forEach(l => {
  7771. buffer.removeEventListener(l.event, l.listener);
  7772. });
  7773. }
  7774. }
  7775. function removeSourceChildren(node) {
  7776. const sourceChildren = node.querySelectorAll('source');
  7777. [].slice.call(sourceChildren).forEach(source => {
  7778. node.removeChild(source);
  7779. });
  7780. }
  7781. function addSource(media, url) {
  7782. const source = self.document.createElement('source');
  7783. source.type = 'video/mp4';
  7784. source.src = url;
  7785. media.appendChild(source);
  7786. }
  7787. class CapLevelController {
  7788. constructor(hls) {
  7789. this.hls = void 0;
  7790. this.autoLevelCapping = void 0;
  7791. this.firstLevel = void 0;
  7792. this.media = void 0;
  7793. this.restrictedLevels = void 0;
  7794. this.timer = void 0;
  7795. this.clientRect = void 0;
  7796. this.streamController = void 0;
  7797. this.hls = hls;
  7798. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  7799. this.firstLevel = -1;
  7800. this.media = null;
  7801. this.restrictedLevels = [];
  7802. this.timer = undefined;
  7803. this.clientRect = null;
  7804. this.registerListeners();
  7805. }
  7806. setStreamController(streamController) {
  7807. this.streamController = streamController;
  7808. }
  7809. destroy() {
  7810. if (this.hls) {
  7811. this.unregisterListener();
  7812. }
  7813. if (this.timer) {
  7814. this.stopCapping();
  7815. }
  7816. this.media = null;
  7817. this.clientRect = null;
  7818. // @ts-ignore
  7819. this.hls = this.streamController = null;
  7820. }
  7821. registerListeners() {
  7822. const {
  7823. hls
  7824. } = this;
  7825. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  7826. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7827. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7828. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  7829. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7830. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7831. }
  7832. unregisterListener() {
  7833. const {
  7834. hls
  7835. } = this;
  7836. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  7837. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7838. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7839. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  7840. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7841. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7842. }
  7843. onFpsDropLevelCapping(event, data) {
  7844. // Don't add a restricted level more than once
  7845. const level = this.hls.levels[data.droppedLevel];
  7846. if (this.isLevelAllowed(level)) {
  7847. this.restrictedLevels.push({
  7848. bitrate: level.bitrate,
  7849. height: level.height,
  7850. width: level.width
  7851. });
  7852. }
  7853. }
  7854. onMediaAttaching(event, data) {
  7855. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  7856. this.clientRect = null;
  7857. if (this.timer && this.hls.levels.length) {
  7858. this.detectPlayerSize();
  7859. }
  7860. }
  7861. onManifestParsed(event, data) {
  7862. const hls = this.hls;
  7863. this.restrictedLevels = [];
  7864. this.firstLevel = data.firstLevel;
  7865. if (hls.config.capLevelToPlayerSize && data.video) {
  7866. // Start capping immediately if the manifest has signaled video codecs
  7867. this.startCapping();
  7868. }
  7869. }
  7870. onLevelsUpdated(event, data) {
  7871. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  7872. this.detectPlayerSize();
  7873. }
  7874. }
  7875. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  7876. // to the first level
  7877. onBufferCodecs(event, data) {
  7878. const hls = this.hls;
  7879. if (hls.config.capLevelToPlayerSize && data.video) {
  7880. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  7881. this.startCapping();
  7882. }
  7883. }
  7884. onMediaDetaching() {
  7885. this.stopCapping();
  7886. }
  7887. detectPlayerSize() {
  7888. if (this.media) {
  7889. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  7890. this.clientRect = null;
  7891. return;
  7892. }
  7893. const levels = this.hls.levels;
  7894. if (levels.length) {
  7895. const hls = this.hls;
  7896. const maxLevel = this.getMaxLevel(levels.length - 1);
  7897. if (maxLevel !== this.autoLevelCapping) {
  7898. logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  7899. }
  7900. hls.autoLevelCapping = maxLevel;
  7901. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  7902. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  7903. // usually happen when the user go to the fullscreen mode.
  7904. this.streamController.nextLevelSwitch();
  7905. }
  7906. this.autoLevelCapping = hls.autoLevelCapping;
  7907. }
  7908. }
  7909. }
  7910. /*
  7911. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  7912. */
  7913. getMaxLevel(capLevelIndex) {
  7914. const levels = this.hls.levels;
  7915. if (!levels.length) {
  7916. return -1;
  7917. }
  7918. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  7919. this.clientRect = null;
  7920. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  7921. }
  7922. startCapping() {
  7923. if (this.timer) {
  7924. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  7925. return;
  7926. }
  7927. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  7928. self.clearInterval(this.timer);
  7929. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  7930. this.detectPlayerSize();
  7931. }
  7932. stopCapping() {
  7933. this.restrictedLevels = [];
  7934. this.firstLevel = -1;
  7935. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  7936. if (this.timer) {
  7937. self.clearInterval(this.timer);
  7938. this.timer = undefined;
  7939. }
  7940. }
  7941. getDimensions() {
  7942. if (this.clientRect) {
  7943. return this.clientRect;
  7944. }
  7945. const media = this.media;
  7946. const boundsRect = {
  7947. width: 0,
  7948. height: 0
  7949. };
  7950. if (media) {
  7951. const clientRect = media.getBoundingClientRect();
  7952. boundsRect.width = clientRect.width;
  7953. boundsRect.height = clientRect.height;
  7954. if (!boundsRect.width && !boundsRect.height) {
  7955. // When the media element has no width or height (equivalent to not being in the DOM),
  7956. // then use its width and height attributes (media.width, media.height)
  7957. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  7958. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  7959. }
  7960. }
  7961. this.clientRect = boundsRect;
  7962. return boundsRect;
  7963. }
  7964. get mediaWidth() {
  7965. return this.getDimensions().width * this.contentScaleFactor;
  7966. }
  7967. get mediaHeight() {
  7968. return this.getDimensions().height * this.contentScaleFactor;
  7969. }
  7970. get contentScaleFactor() {
  7971. let pixelRatio = 1;
  7972. if (!this.hls.config.ignoreDevicePixelRatio) {
  7973. try {
  7974. pixelRatio = self.devicePixelRatio;
  7975. } catch (e) {
  7976. /* no-op */
  7977. }
  7978. }
  7979. return pixelRatio;
  7980. }
  7981. isLevelAllowed(level) {
  7982. const restrictedLevels = this.restrictedLevels;
  7983. return !restrictedLevels.some(restrictedLevel => {
  7984. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  7985. });
  7986. }
  7987. static getMaxLevelByMediaSize(levels, width, height) {
  7988. if (!(levels != null && levels.length)) {
  7989. return -1;
  7990. }
  7991. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  7992. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  7993. const atGreatestBandwidth = (curLevel, nextLevel) => {
  7994. if (!nextLevel) {
  7995. return true;
  7996. }
  7997. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  7998. };
  7999. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  8000. // the max level
  8001. let maxLevelIndex = levels.length - 1;
  8002. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  8003. const squareSize = Math.max(width, height);
  8004. for (let i = 0; i < levels.length; i += 1) {
  8005. const level = levels[i];
  8006. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  8007. maxLevelIndex = i;
  8008. break;
  8009. }
  8010. }
  8011. return maxLevelIndex;
  8012. }
  8013. }
  8014. class FPSController {
  8015. constructor(hls) {
  8016. this.hls = void 0;
  8017. this.isVideoPlaybackQualityAvailable = false;
  8018. this.timer = void 0;
  8019. this.media = null;
  8020. this.lastTime = void 0;
  8021. this.lastDroppedFrames = 0;
  8022. this.lastDecodedFrames = 0;
  8023. // stream controller must be provided as a dependency!
  8024. this.streamController = void 0;
  8025. this.hls = hls;
  8026. this.registerListeners();
  8027. }
  8028. setStreamController(streamController) {
  8029. this.streamController = streamController;
  8030. }
  8031. registerListeners() {
  8032. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8033. }
  8034. unregisterListeners() {
  8035. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8036. }
  8037. destroy() {
  8038. if (this.timer) {
  8039. clearInterval(this.timer);
  8040. }
  8041. this.unregisterListeners();
  8042. this.isVideoPlaybackQualityAvailable = false;
  8043. this.media = null;
  8044. }
  8045. onMediaAttaching(event, data) {
  8046. const config = this.hls.config;
  8047. if (config.capLevelOnFPSDrop) {
  8048. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  8049. this.media = media;
  8050. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  8051. this.isVideoPlaybackQualityAvailable = true;
  8052. }
  8053. self.clearInterval(this.timer);
  8054. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  8055. }
  8056. }
  8057. checkFPS(video, decodedFrames, droppedFrames) {
  8058. const currentTime = performance.now();
  8059. if (decodedFrames) {
  8060. if (this.lastTime) {
  8061. const currentPeriod = currentTime - this.lastTime;
  8062. const currentDropped = droppedFrames - this.lastDroppedFrames;
  8063. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  8064. const droppedFPS = 1000 * currentDropped / currentPeriod;
  8065. const hls = this.hls;
  8066. hls.trigger(Events.FPS_DROP, {
  8067. currentDropped: currentDropped,
  8068. currentDecoded: currentDecoded,
  8069. totalDroppedFrames: droppedFrames
  8070. });
  8071. if (droppedFPS > 0) {
  8072. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  8073. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  8074. let currentLevel = hls.currentLevel;
  8075. logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  8076. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  8077. currentLevel = currentLevel - 1;
  8078. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  8079. level: currentLevel,
  8080. droppedLevel: hls.currentLevel
  8081. });
  8082. hls.autoLevelCapping = currentLevel;
  8083. this.streamController.nextLevelSwitch();
  8084. }
  8085. }
  8086. }
  8087. }
  8088. this.lastTime = currentTime;
  8089. this.lastDroppedFrames = droppedFrames;
  8090. this.lastDecodedFrames = decodedFrames;
  8091. }
  8092. }
  8093. checkFPSInterval() {
  8094. const video = this.media;
  8095. if (video) {
  8096. if (this.isVideoPlaybackQualityAvailable) {
  8097. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  8098. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  8099. } else {
  8100. // HTMLVideoElement doesn't include the webkit types
  8101. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  8102. }
  8103. }
  8104. }
  8105. }
  8106. const PATHWAY_PENALTY_DURATION_MS = 300000;
  8107. class ContentSteeringController {
  8108. constructor(hls) {
  8109. this.hls = void 0;
  8110. this.log = void 0;
  8111. this.loader = null;
  8112. this.uri = null;
  8113. this.pathwayId = '.';
  8114. this.pathwayPriority = null;
  8115. this.timeToLoad = 300;
  8116. this.reloadTimer = -1;
  8117. this.updated = 0;
  8118. this.started = false;
  8119. this.enabled = true;
  8120. this.levels = null;
  8121. this.audioTracks = null;
  8122. this.subtitleTracks = null;
  8123. this.penalizedPathways = {};
  8124. this.hls = hls;
  8125. this.log = logger.log.bind(logger, `[content-steering]:`);
  8126. this.registerListeners();
  8127. }
  8128. registerListeners() {
  8129. const hls = this.hls;
  8130. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8131. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8132. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8133. hls.on(Events.ERROR, this.onError, this);
  8134. }
  8135. unregisterListeners() {
  8136. const hls = this.hls;
  8137. if (!hls) {
  8138. return;
  8139. }
  8140. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8141. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8142. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8143. hls.off(Events.ERROR, this.onError, this);
  8144. }
  8145. startLoad() {
  8146. this.started = true;
  8147. this.clearTimeout();
  8148. if (this.enabled && this.uri) {
  8149. if (this.updated) {
  8150. const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  8151. if (ttl > 0) {
  8152. this.scheduleRefresh(this.uri, ttl);
  8153. return;
  8154. }
  8155. }
  8156. this.loadSteeringManifest(this.uri);
  8157. }
  8158. }
  8159. stopLoad() {
  8160. this.started = false;
  8161. if (this.loader) {
  8162. this.loader.destroy();
  8163. this.loader = null;
  8164. }
  8165. this.clearTimeout();
  8166. }
  8167. clearTimeout() {
  8168. if (this.reloadTimer !== -1) {
  8169. self.clearTimeout(this.reloadTimer);
  8170. this.reloadTimer = -1;
  8171. }
  8172. }
  8173. destroy() {
  8174. this.unregisterListeners();
  8175. this.stopLoad();
  8176. // @ts-ignore
  8177. this.hls = null;
  8178. this.levels = this.audioTracks = this.subtitleTracks = null;
  8179. }
  8180. removeLevel(levelToRemove) {
  8181. const levels = this.levels;
  8182. if (levels) {
  8183. this.levels = levels.filter(level => level !== levelToRemove);
  8184. }
  8185. }
  8186. onManifestLoading() {
  8187. this.stopLoad();
  8188. this.enabled = true;
  8189. this.timeToLoad = 300;
  8190. this.updated = 0;
  8191. this.uri = null;
  8192. this.pathwayId = '.';
  8193. this.levels = this.audioTracks = this.subtitleTracks = null;
  8194. }
  8195. onManifestLoaded(event, data) {
  8196. const {
  8197. contentSteering
  8198. } = data;
  8199. if (contentSteering === null) {
  8200. return;
  8201. }
  8202. this.pathwayId = contentSteering.pathwayId;
  8203. this.uri = contentSteering.uri;
  8204. if (this.started) {
  8205. this.startLoad();
  8206. }
  8207. }
  8208. onManifestParsed(event, data) {
  8209. this.audioTracks = data.audioTracks;
  8210. this.subtitleTracks = data.subtitleTracks;
  8211. }
  8212. onError(event, data) {
  8213. const {
  8214. errorAction
  8215. } = data;
  8216. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  8217. const levels = this.levels;
  8218. let pathwayPriority = this.pathwayPriority;
  8219. let errorPathway = this.pathwayId;
  8220. if (data.context) {
  8221. const {
  8222. groupId,
  8223. pathwayId,
  8224. type
  8225. } = data.context;
  8226. if (groupId && levels) {
  8227. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  8228. } else if (pathwayId) {
  8229. errorPathway = pathwayId;
  8230. }
  8231. }
  8232. if (!(errorPathway in this.penalizedPathways)) {
  8233. this.penalizedPathways[errorPathway] = performance.now();
  8234. }
  8235. if (!pathwayPriority && levels) {
  8236. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  8237. pathwayPriority = levels.reduce((pathways, level) => {
  8238. if (pathways.indexOf(level.pathwayId) === -1) {
  8239. pathways.push(level.pathwayId);
  8240. }
  8241. return pathways;
  8242. }, []);
  8243. }
  8244. if (pathwayPriority && pathwayPriority.length > 1) {
  8245. this.updatePathwayPriority(pathwayPriority);
  8246. errorAction.resolved = this.pathwayId !== errorPathway;
  8247. }
  8248. if (!errorAction.resolved) {
  8249. logger.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${JSON.stringify(pathwayPriority)} penalized: ${JSON.stringify(this.penalizedPathways)}`);
  8250. }
  8251. }
  8252. }
  8253. filterParsedLevels(levels) {
  8254. // Filter levels to only include those that are in the initial pathway
  8255. this.levels = levels;
  8256. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  8257. if (pathwayLevels.length === 0) {
  8258. const pathwayId = levels[0].pathwayId;
  8259. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  8260. pathwayLevels = this.getLevelsForPathway(pathwayId);
  8261. this.pathwayId = pathwayId;
  8262. }
  8263. if (pathwayLevels.length !== levels.length) {
  8264. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  8265. return pathwayLevels;
  8266. }
  8267. return levels;
  8268. }
  8269. getLevelsForPathway(pathwayId) {
  8270. if (this.levels === null) {
  8271. return [];
  8272. }
  8273. return this.levels.filter(level => pathwayId === level.pathwayId);
  8274. }
  8275. updatePathwayPriority(pathwayPriority) {
  8276. this.pathwayPriority = pathwayPriority;
  8277. let levels;
  8278. // Evaluate if we should remove the pathway from the penalized list
  8279. const penalizedPathways = this.penalizedPathways;
  8280. const now = performance.now();
  8281. Object.keys(penalizedPathways).forEach(pathwayId => {
  8282. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  8283. delete penalizedPathways[pathwayId];
  8284. }
  8285. });
  8286. for (let i = 0; i < pathwayPriority.length; i++) {
  8287. const pathwayId = pathwayPriority[i];
  8288. if (pathwayId in penalizedPathways) {
  8289. continue;
  8290. }
  8291. if (pathwayId === this.pathwayId) {
  8292. return;
  8293. }
  8294. const selectedIndex = this.hls.nextLoadLevel;
  8295. const selectedLevel = this.hls.levels[selectedIndex];
  8296. levels = this.getLevelsForPathway(pathwayId);
  8297. if (levels.length > 0) {
  8298. this.log(`Setting Pathway to "${pathwayId}"`);
  8299. this.pathwayId = pathwayId;
  8300. reassignFragmentLevelIndexes(levels);
  8301. this.hls.trigger(Events.LEVELS_UPDATED, {
  8302. levels
  8303. });
  8304. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  8305. const levelAfterChange = this.hls.levels[selectedIndex];
  8306. if (selectedLevel && levelAfterChange && this.levels) {
  8307. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  8308. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  8309. }
  8310. this.hls.nextLoadLevel = selectedIndex;
  8311. }
  8312. break;
  8313. }
  8314. }
  8315. }
  8316. getPathwayForGroupId(groupId, type, defaultPathway) {
  8317. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  8318. for (let i = 0; i < levels.length; i++) {
  8319. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  8320. return levels[i].pathwayId;
  8321. }
  8322. }
  8323. return defaultPathway;
  8324. }
  8325. clonePathways(pathwayClones) {
  8326. const levels = this.levels;
  8327. if (!levels) {
  8328. return;
  8329. }
  8330. const audioGroupCloneMap = {};
  8331. const subtitleGroupCloneMap = {};
  8332. pathwayClones.forEach(pathwayClone => {
  8333. const {
  8334. ID: cloneId,
  8335. 'BASE-ID': baseId,
  8336. 'URI-REPLACEMENT': uriReplacement
  8337. } = pathwayClone;
  8338. if (levels.some(level => level.pathwayId === cloneId)) {
  8339. return;
  8340. }
  8341. const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {
  8342. const attributes = new AttrList(baseLevel.attrs);
  8343. attributes['PATHWAY-ID'] = cloneId;
  8344. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  8345. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  8346. if (clonedAudioGroupId) {
  8347. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  8348. attributes.AUDIO = clonedAudioGroupId;
  8349. }
  8350. if (clonedSubtitleGroupId) {
  8351. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  8352. attributes.SUBTITLES = clonedSubtitleGroupId;
  8353. }
  8354. const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  8355. const clonedLevel = new Level({
  8356. attrs: attributes,
  8357. audioCodec: baseLevel.audioCodec,
  8358. bitrate: baseLevel.bitrate,
  8359. height: baseLevel.height,
  8360. name: baseLevel.name,
  8361. url,
  8362. videoCodec: baseLevel.videoCodec,
  8363. width: baseLevel.width
  8364. });
  8365. if (baseLevel.audioGroups) {
  8366. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  8367. clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  8368. }
  8369. }
  8370. if (baseLevel.subtitleGroups) {
  8371. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  8372. clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  8373. }
  8374. }
  8375. return clonedLevel;
  8376. });
  8377. levels.push(...clonedVariants);
  8378. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  8379. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  8380. });
  8381. }
  8382. loadSteeringManifest(uri) {
  8383. const config = this.hls.config;
  8384. const Loader = config.loader;
  8385. if (this.loader) {
  8386. this.loader.destroy();
  8387. }
  8388. this.loader = new Loader(config);
  8389. let url;
  8390. try {
  8391. url = new self.URL(uri);
  8392. } catch (error) {
  8393. this.enabled = false;
  8394. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  8395. return;
  8396. }
  8397. if (url.protocol !== 'data:') {
  8398. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  8399. url.searchParams.set('_HLS_pathway', this.pathwayId);
  8400. url.searchParams.set('_HLS_throughput', '' + throughput);
  8401. }
  8402. const context = {
  8403. responseType: 'json',
  8404. url: url.href
  8405. };
  8406. const loadPolicy = config.steeringManifestLoadPolicy.default;
  8407. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  8408. const loaderConfig = {
  8409. loadPolicy,
  8410. timeout: loadPolicy.maxLoadTimeMs,
  8411. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  8412. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  8413. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  8414. };
  8415. const callbacks = {
  8416. onSuccess: (response, stats, context, networkDetails) => {
  8417. this.log(`Loaded steering manifest: "${url}"`);
  8418. const steeringData = response.data;
  8419. if (steeringData.VERSION !== 1) {
  8420. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  8421. return;
  8422. }
  8423. this.updated = performance.now();
  8424. this.timeToLoad = steeringData.TTL;
  8425. const {
  8426. 'RELOAD-URI': reloadUri,
  8427. 'PATHWAY-CLONES': pathwayClones,
  8428. 'PATHWAY-PRIORITY': pathwayPriority
  8429. } = steeringData;
  8430. if (reloadUri) {
  8431. try {
  8432. this.uri = new self.URL(reloadUri, url).href;
  8433. } catch (error) {
  8434. this.enabled = false;
  8435. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  8436. return;
  8437. }
  8438. }
  8439. this.scheduleRefresh(this.uri || context.url);
  8440. if (pathwayClones) {
  8441. this.clonePathways(pathwayClones);
  8442. }
  8443. const loadedSteeringData = {
  8444. steeringManifest: steeringData,
  8445. url: url.toString()
  8446. };
  8447. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  8448. if (pathwayPriority) {
  8449. this.updatePathwayPriority(pathwayPriority);
  8450. }
  8451. },
  8452. onError: (error, context, networkDetails, stats) => {
  8453. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);
  8454. this.stopLoad();
  8455. if (error.code === 410) {
  8456. this.enabled = false;
  8457. this.log(`Steering manifest ${context.url} no longer available`);
  8458. return;
  8459. }
  8460. let ttl = this.timeToLoad * 1000;
  8461. if (error.code === 429) {
  8462. const loader = this.loader;
  8463. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  8464. const retryAfter = loader.getResponseHeader('Retry-After');
  8465. if (retryAfter) {
  8466. ttl = parseFloat(retryAfter) * 1000;
  8467. }
  8468. }
  8469. this.log(`Steering manifest ${context.url} rate limited`);
  8470. return;
  8471. }
  8472. this.scheduleRefresh(this.uri || context.url, ttl);
  8473. },
  8474. onTimeout: (stats, context, networkDetails) => {
  8475. this.log(`Timeout loading steering manifest (${context.url})`);
  8476. this.scheduleRefresh(this.uri || context.url);
  8477. }
  8478. };
  8479. this.log(`Requesting steering manifest: ${url}`);
  8480. this.loader.load(context, loaderConfig, callbacks);
  8481. }
  8482. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {
  8483. this.clearTimeout();
  8484. this.reloadTimer = self.setTimeout(() => {
  8485. var _this$hls;
  8486. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  8487. if (media && !media.ended) {
  8488. this.loadSteeringManifest(uri);
  8489. return;
  8490. }
  8491. this.scheduleRefresh(uri, this.timeToLoad * 1000);
  8492. }, ttlMs);
  8493. }
  8494. }
  8495. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  8496. if (!tracks) {
  8497. return;
  8498. }
  8499. Object.keys(groupCloneMap).forEach(audioGroupId => {
  8500. const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {
  8501. const clonedTrack = _extends({}, track);
  8502. clonedTrack.details = undefined;
  8503. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  8504. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  8505. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  8506. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  8507. return clonedTrack;
  8508. });
  8509. tracks.push(...clonedTracks);
  8510. });
  8511. }
  8512. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  8513. const {
  8514. HOST: host,
  8515. PARAMS: params,
  8516. [perOptionKey]: perOptionUris
  8517. } = uriReplacement;
  8518. let perVariantUri;
  8519. if (stableId) {
  8520. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  8521. if (perVariantUri) {
  8522. uri = perVariantUri;
  8523. }
  8524. }
  8525. const url = new self.URL(uri);
  8526. if (host && !perVariantUri) {
  8527. url.host = host;
  8528. }
  8529. if (params) {
  8530. Object.keys(params).sort().forEach(key => {
  8531. if (key) {
  8532. url.searchParams.set(key, params[key]);
  8533. }
  8534. });
  8535. }
  8536. return url.href;
  8537. }
  8538. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  8539. class XhrLoader {
  8540. constructor(config) {
  8541. this.xhrSetup = void 0;
  8542. this.requestTimeout = void 0;
  8543. this.retryTimeout = void 0;
  8544. this.retryDelay = void 0;
  8545. this.config = null;
  8546. this.callbacks = null;
  8547. this.context = null;
  8548. this.loader = null;
  8549. this.stats = void 0;
  8550. this.xhrSetup = config ? config.xhrSetup || null : null;
  8551. this.stats = new LoadStats();
  8552. this.retryDelay = 0;
  8553. }
  8554. destroy() {
  8555. this.callbacks = null;
  8556. this.abortInternal();
  8557. this.loader = null;
  8558. this.config = null;
  8559. this.context = null;
  8560. this.xhrSetup = null;
  8561. }
  8562. abortInternal() {
  8563. const loader = this.loader;
  8564. self.clearTimeout(this.requestTimeout);
  8565. self.clearTimeout(this.retryTimeout);
  8566. if (loader) {
  8567. loader.onreadystatechange = null;
  8568. loader.onprogress = null;
  8569. if (loader.readyState !== 4) {
  8570. this.stats.aborted = true;
  8571. loader.abort();
  8572. }
  8573. }
  8574. }
  8575. abort() {
  8576. var _this$callbacks;
  8577. this.abortInternal();
  8578. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  8579. this.callbacks.onAbort(this.stats, this.context, this.loader);
  8580. }
  8581. }
  8582. load(context, config, callbacks) {
  8583. if (this.stats.loading.start) {
  8584. throw new Error('Loader can only be used once.');
  8585. }
  8586. this.stats.loading.start = self.performance.now();
  8587. this.context = context;
  8588. this.config = config;
  8589. this.callbacks = callbacks;
  8590. this.loadInternal();
  8591. }
  8592. loadInternal() {
  8593. const {
  8594. config,
  8595. context
  8596. } = this;
  8597. if (!config || !context) {
  8598. return;
  8599. }
  8600. const xhr = this.loader = new self.XMLHttpRequest();
  8601. const stats = this.stats;
  8602. stats.loading.first = 0;
  8603. stats.loaded = 0;
  8604. stats.aborted = false;
  8605. const xhrSetup = this.xhrSetup;
  8606. if (xhrSetup) {
  8607. Promise.resolve().then(() => {
  8608. if (this.loader !== xhr || this.stats.aborted) return;
  8609. return xhrSetup(xhr, context.url);
  8610. }).catch(error => {
  8611. if (this.loader !== xhr || this.stats.aborted) return;
  8612. xhr.open('GET', context.url, true);
  8613. return xhrSetup(xhr, context.url);
  8614. }).then(() => {
  8615. if (this.loader !== xhr || this.stats.aborted) return;
  8616. this.openAndSendXhr(xhr, context, config);
  8617. }).catch(error => {
  8618. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  8619. this.callbacks.onError({
  8620. code: xhr.status,
  8621. text: error.message
  8622. }, context, xhr, stats);
  8623. return;
  8624. });
  8625. } else {
  8626. this.openAndSendXhr(xhr, context, config);
  8627. }
  8628. }
  8629. openAndSendXhr(xhr, context, config) {
  8630. if (!xhr.readyState) {
  8631. xhr.open('GET', context.url, true);
  8632. }
  8633. const headers = context.headers;
  8634. const {
  8635. maxTimeToFirstByteMs,
  8636. maxLoadTimeMs
  8637. } = config.loadPolicy;
  8638. if (headers) {
  8639. for (const header in headers) {
  8640. xhr.setRequestHeader(header, headers[header]);
  8641. }
  8642. }
  8643. if (context.rangeEnd) {
  8644. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  8645. }
  8646. xhr.onreadystatechange = this.readystatechange.bind(this);
  8647. xhr.onprogress = this.loadprogress.bind(this);
  8648. xhr.responseType = context.responseType;
  8649. // setup timeout before we perform request
  8650. self.clearTimeout(this.requestTimeout);
  8651. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  8652. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  8653. xhr.send();
  8654. }
  8655. readystatechange() {
  8656. const {
  8657. context,
  8658. loader: xhr,
  8659. stats
  8660. } = this;
  8661. if (!context || !xhr) {
  8662. return;
  8663. }
  8664. const readyState = xhr.readyState;
  8665. const config = this.config;
  8666. // don't proceed if xhr has been aborted
  8667. if (stats.aborted) {
  8668. return;
  8669. }
  8670. // >= HEADERS_RECEIVED
  8671. if (readyState >= 2) {
  8672. if (stats.loading.first === 0) {
  8673. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  8674. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  8675. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  8676. self.clearTimeout(this.requestTimeout);
  8677. config.timeout = config.loadPolicy.maxLoadTimeMs;
  8678. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  8679. }
  8680. }
  8681. if (readyState === 4) {
  8682. self.clearTimeout(this.requestTimeout);
  8683. xhr.onreadystatechange = null;
  8684. xhr.onprogress = null;
  8685. const status = xhr.status;
  8686. // http status between 200 to 299 are all successful
  8687. const useResponse = xhr.responseType !== 'text';
  8688. if (status >= 200 && status < 300 && (useResponse && xhr.response || xhr.responseText !== null)) {
  8689. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  8690. const data = useResponse ? xhr.response : xhr.responseText;
  8691. const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  8692. stats.loaded = stats.total = len;
  8693. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  8694. if (!this.callbacks) {
  8695. return;
  8696. }
  8697. const onProgress = this.callbacks.onProgress;
  8698. if (onProgress) {
  8699. onProgress(stats, context, data, xhr);
  8700. }
  8701. if (!this.callbacks) {
  8702. return;
  8703. }
  8704. const response = {
  8705. url: xhr.responseURL,
  8706. data: data,
  8707. code: status
  8708. };
  8709. this.callbacks.onSuccess(response, stats, context, xhr);
  8710. } else {
  8711. const retryConfig = config.loadPolicy.errorRetry;
  8712. const retryCount = stats.retry;
  8713. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  8714. const response = {
  8715. url: context.url,
  8716. data: undefined,
  8717. code: status
  8718. };
  8719. if (shouldRetry(retryConfig, retryCount, false, response)) {
  8720. this.retry(retryConfig);
  8721. } else {
  8722. logger.error(`${status} while loading ${context.url}`);
  8723. this.callbacks.onError({
  8724. code: status,
  8725. text: xhr.statusText
  8726. }, context, xhr, stats);
  8727. }
  8728. }
  8729. }
  8730. }
  8731. }
  8732. loadtimeout() {
  8733. if (!this.config) return;
  8734. const retryConfig = this.config.loadPolicy.timeoutRetry;
  8735. const retryCount = this.stats.retry;
  8736. if (shouldRetry(retryConfig, retryCount, true)) {
  8737. this.retry(retryConfig);
  8738. } else {
  8739. var _this$context;
  8740. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  8741. const callbacks = this.callbacks;
  8742. if (callbacks) {
  8743. this.abortInternal();
  8744. callbacks.onTimeout(this.stats, this.context, this.loader);
  8745. }
  8746. }
  8747. }
  8748. retry(retryConfig) {
  8749. const {
  8750. context,
  8751. stats
  8752. } = this;
  8753. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  8754. stats.retry++;
  8755. logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  8756. // abort and reset internal state
  8757. this.abortInternal();
  8758. this.loader = null;
  8759. // schedule retry
  8760. self.clearTimeout(this.retryTimeout);
  8761. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  8762. }
  8763. loadprogress(event) {
  8764. const stats = this.stats;
  8765. stats.loaded = event.loaded;
  8766. if (event.lengthComputable) {
  8767. stats.total = event.total;
  8768. }
  8769. }
  8770. getCacheAge() {
  8771. let result = null;
  8772. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  8773. const ageHeader = this.loader.getResponseHeader('age');
  8774. result = ageHeader ? parseFloat(ageHeader) : null;
  8775. }
  8776. return result;
  8777. }
  8778. getResponseHeader(name) {
  8779. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {
  8780. return this.loader.getResponseHeader(name);
  8781. }
  8782. return null;
  8783. }
  8784. }
  8785. class ChunkCache {
  8786. constructor() {
  8787. this.chunks = [];
  8788. this.dataLength = 0;
  8789. }
  8790. push(chunk) {
  8791. this.chunks.push(chunk);
  8792. this.dataLength += chunk.length;
  8793. }
  8794. flush() {
  8795. const {
  8796. chunks,
  8797. dataLength
  8798. } = this;
  8799. let result;
  8800. if (!chunks.length) {
  8801. return new Uint8Array(0);
  8802. } else if (chunks.length === 1) {
  8803. result = chunks[0];
  8804. } else {
  8805. result = concatUint8Arrays(chunks, dataLength);
  8806. }
  8807. this.reset();
  8808. return result;
  8809. }
  8810. reset() {
  8811. this.chunks.length = 0;
  8812. this.dataLength = 0;
  8813. }
  8814. }
  8815. function concatUint8Arrays(chunks, dataLength) {
  8816. const result = new Uint8Array(dataLength);
  8817. let offset = 0;
  8818. for (let i = 0; i < chunks.length; i++) {
  8819. const chunk = chunks[i];
  8820. result.set(chunk, offset);
  8821. offset += chunk.length;
  8822. }
  8823. return result;
  8824. }
  8825. function fetchSupported() {
  8826. if (
  8827. // @ts-ignore
  8828. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  8829. try {
  8830. new self.ReadableStream({}); // eslint-disable-line no-new
  8831. return true;
  8832. } catch (e) {
  8833. /* noop */
  8834. }
  8835. }
  8836. return false;
  8837. }
  8838. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  8839. class FetchLoader {
  8840. constructor(config /* HlsConfig */) {
  8841. this.fetchSetup = void 0;
  8842. this.requestTimeout = void 0;
  8843. this.request = null;
  8844. this.response = null;
  8845. this.controller = void 0;
  8846. this.context = null;
  8847. this.config = null;
  8848. this.callbacks = null;
  8849. this.stats = void 0;
  8850. this.loader = null;
  8851. this.fetchSetup = config.fetchSetup || getRequest;
  8852. this.controller = new self.AbortController();
  8853. this.stats = new LoadStats();
  8854. }
  8855. destroy() {
  8856. this.loader = this.callbacks = this.context = this.config = this.request = null;
  8857. this.abortInternal();
  8858. this.response = null;
  8859. // @ts-ignore
  8860. this.fetchSetup = this.controller = this.stats = null;
  8861. }
  8862. abortInternal() {
  8863. if (this.controller && !this.stats.loading.end) {
  8864. this.stats.aborted = true;
  8865. this.controller.abort();
  8866. }
  8867. }
  8868. abort() {
  8869. var _this$callbacks;
  8870. this.abortInternal();
  8871. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  8872. this.callbacks.onAbort(this.stats, this.context, this.response);
  8873. }
  8874. }
  8875. load(context, config, callbacks) {
  8876. const stats = this.stats;
  8877. if (stats.loading.start) {
  8878. throw new Error('Loader can only be used once.');
  8879. }
  8880. stats.loading.start = self.performance.now();
  8881. const initParams = getRequestParameters(context, this.controller.signal);
  8882. const onProgress = callbacks.onProgress;
  8883. const isArrayBuffer = context.responseType === 'arraybuffer';
  8884. const LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  8885. const {
  8886. maxTimeToFirstByteMs,
  8887. maxLoadTimeMs
  8888. } = config.loadPolicy;
  8889. this.context = context;
  8890. this.config = config;
  8891. this.callbacks = callbacks;
  8892. this.request = this.fetchSetup(context, initParams);
  8893. self.clearTimeout(this.requestTimeout);
  8894. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  8895. this.requestTimeout = self.setTimeout(() => {
  8896. this.abortInternal();
  8897. callbacks.onTimeout(stats, context, this.response);
  8898. }, config.timeout);
  8899. self.fetch(this.request).then(response => {
  8900. this.response = this.loader = response;
  8901. const first = Math.max(self.performance.now(), stats.loading.start);
  8902. self.clearTimeout(this.requestTimeout);
  8903. config.timeout = maxLoadTimeMs;
  8904. this.requestTimeout = self.setTimeout(() => {
  8905. this.abortInternal();
  8906. callbacks.onTimeout(stats, context, this.response);
  8907. }, maxLoadTimeMs - (first - stats.loading.start));
  8908. if (!response.ok) {
  8909. const {
  8910. status,
  8911. statusText
  8912. } = response;
  8913. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  8914. }
  8915. stats.loading.first = first;
  8916. stats.total = getContentLength(response.headers) || stats.total;
  8917. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  8918. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  8919. }
  8920. if (isArrayBuffer) {
  8921. return response.arrayBuffer();
  8922. }
  8923. if (context.responseType === 'json') {
  8924. return response.json();
  8925. }
  8926. return response.text();
  8927. }).then(responseData => {
  8928. const response = this.response;
  8929. if (!response) {
  8930. throw new Error('loader destroyed');
  8931. }
  8932. self.clearTimeout(this.requestTimeout);
  8933. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  8934. const total = responseData[LENGTH];
  8935. if (total) {
  8936. stats.loaded = stats.total = total;
  8937. }
  8938. const loaderResponse = {
  8939. url: response.url,
  8940. data: responseData,
  8941. code: response.status
  8942. };
  8943. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  8944. onProgress(stats, context, responseData, response);
  8945. }
  8946. callbacks.onSuccess(loaderResponse, stats, context, response);
  8947. }).catch(error => {
  8948. self.clearTimeout(this.requestTimeout);
  8949. if (stats.aborted) {
  8950. return;
  8951. }
  8952. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  8953. // when destroying, 'error' itself can be undefined
  8954. const code = !error ? 0 : error.code || 0;
  8955. const text = !error ? null : error.message;
  8956. callbacks.onError({
  8957. code,
  8958. text
  8959. }, context, error ? error.details : null, stats);
  8960. });
  8961. }
  8962. getCacheAge() {
  8963. let result = null;
  8964. if (this.response) {
  8965. const ageHeader = this.response.headers.get('age');
  8966. result = ageHeader ? parseFloat(ageHeader) : null;
  8967. }
  8968. return result;
  8969. }
  8970. getResponseHeader(name) {
  8971. return this.response ? this.response.headers.get(name) : null;
  8972. }
  8973. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  8974. const chunkCache = new ChunkCache();
  8975. const reader = response.body.getReader();
  8976. const pump = () => {
  8977. return reader.read().then(data => {
  8978. if (data.done) {
  8979. if (chunkCache.dataLength) {
  8980. onProgress(stats, context, chunkCache.flush(), response);
  8981. }
  8982. return Promise.resolve(new ArrayBuffer(0));
  8983. }
  8984. const chunk = data.value;
  8985. const len = chunk.length;
  8986. stats.loaded += len;
  8987. if (len < highWaterMark || chunkCache.dataLength) {
  8988. // The current chunk is too small to to be emitted or the cache already has data
  8989. // Push it to the cache
  8990. chunkCache.push(chunk);
  8991. if (chunkCache.dataLength >= highWaterMark) {
  8992. // flush in order to join the typed arrays
  8993. onProgress(stats, context, chunkCache.flush(), response);
  8994. }
  8995. } else {
  8996. // If there's nothing cached already, and the chache is large enough
  8997. // just emit the progress event
  8998. onProgress(stats, context, chunk, response);
  8999. }
  9000. return pump();
  9001. }).catch(() => {
  9002. /* aborted */
  9003. return Promise.reject();
  9004. });
  9005. };
  9006. return pump();
  9007. }
  9008. }
  9009. function getRequestParameters(context, signal) {
  9010. const initParams = {
  9011. method: 'GET',
  9012. mode: 'cors',
  9013. credentials: 'same-origin',
  9014. signal,
  9015. headers: new self.Headers(_extends({}, context.headers))
  9016. };
  9017. if (context.rangeEnd) {
  9018. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  9019. }
  9020. return initParams;
  9021. }
  9022. function getByteRangeLength(byteRangeHeader) {
  9023. const result = BYTERANGE.exec(byteRangeHeader);
  9024. if (result) {
  9025. return parseInt(result[2]) - parseInt(result[1]) + 1;
  9026. }
  9027. }
  9028. function getContentLength(headers) {
  9029. const contentRange = headers.get('Content-Range');
  9030. if (contentRange) {
  9031. const byteRangeLength = getByteRangeLength(contentRange);
  9032. if (isFiniteNumber(byteRangeLength)) {
  9033. return byteRangeLength;
  9034. }
  9035. }
  9036. const contentLength = headers.get('Content-Length');
  9037. if (contentLength) {
  9038. return parseInt(contentLength);
  9039. }
  9040. }
  9041. function getRequest(context, initParams) {
  9042. return new self.Request(context.url, initParams);
  9043. }
  9044. class FetchError extends Error {
  9045. constructor(message, code, details) {
  9046. super(message);
  9047. this.code = void 0;
  9048. this.details = void 0;
  9049. this.code = code;
  9050. this.details = details;
  9051. }
  9052. }
  9053. /**
  9054. * @deprecated use fragLoadPolicy.default
  9055. */
  9056. /**
  9057. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  9058. */
  9059. const defaultLoadPolicy = {
  9060. maxTimeToFirstByteMs: 8000,
  9061. maxLoadTimeMs: 20000,
  9062. timeoutRetry: null,
  9063. errorRetry: null
  9064. };
  9065. /**
  9066. * @ignore
  9067. * If possible, keep hlsDefaultConfig shallow
  9068. * It is cloned whenever a new Hls instance is created, by keeping the config
  9069. * shallow the properties are cloned, and we don't end up manipulating the default
  9070. */
  9071. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  9072. autoStartLoad: true,
  9073. // used by stream-controller
  9074. startPosition: -1,
  9075. // used by stream-controller
  9076. defaultAudioCodec: undefined,
  9077. // used by stream-controller
  9078. debug: false,
  9079. // used by logger
  9080. capLevelOnFPSDrop: false,
  9081. // used by fps-controller
  9082. capLevelToPlayerSize: false,
  9083. // used by cap-level-controller
  9084. ignoreDevicePixelRatio: false,
  9085. // used by cap-level-controller
  9086. preferManagedMediaSource: true,
  9087. initialLiveManifestSize: 1,
  9088. // used by stream-controller
  9089. maxBufferLength: 30,
  9090. // used by stream-controller
  9091. backBufferLength: Infinity,
  9092. // used by buffer-controller
  9093. frontBufferFlushThreshold: Infinity,
  9094. maxBufferSize: 60 * 1000 * 1000,
  9095. // used by stream-controller
  9096. maxBufferHole: 0.1,
  9097. // used by stream-controller
  9098. highBufferWatchdogPeriod: 2,
  9099. // used by stream-controller
  9100. nudgeOffset: 0.1,
  9101. // used by stream-controller
  9102. nudgeMaxRetry: 3,
  9103. // used by stream-controller
  9104. maxFragLookUpTolerance: 0.25,
  9105. // used by stream-controller
  9106. liveSyncDurationCount: 3,
  9107. // used by latency-controller
  9108. liveMaxLatencyDurationCount: Infinity,
  9109. // used by latency-controller
  9110. liveSyncDuration: undefined,
  9111. // used by latency-controller
  9112. liveMaxLatencyDuration: undefined,
  9113. // used by latency-controller
  9114. maxLiveSyncPlaybackRate: 1,
  9115. // used by latency-controller
  9116. liveDurationInfinity: false,
  9117. // used by buffer-controller
  9118. /**
  9119. * @deprecated use backBufferLength
  9120. */
  9121. liveBackBufferLength: null,
  9122. // used by buffer-controller
  9123. maxMaxBufferLength: 600,
  9124. // used by stream-controller
  9125. enableWorker: true,
  9126. // used by transmuxer
  9127. workerPath: null,
  9128. // used by transmuxer
  9129. enableSoftwareAES: true,
  9130. // used by decrypter
  9131. startLevel: undefined,
  9132. // used by level-controller
  9133. startFragPrefetch: false,
  9134. // used by stream-controller
  9135. fpsDroppedMonitoringPeriod: 5000,
  9136. // used by fps-controller
  9137. fpsDroppedMonitoringThreshold: 0.2,
  9138. // used by fps-controller
  9139. appendErrorMaxRetry: 3,
  9140. // used by buffer-controller
  9141. loader: XhrLoader,
  9142. // loader: FetchLoader,
  9143. fLoader: undefined,
  9144. // used by fragment-loader
  9145. pLoader: undefined,
  9146. // used by playlist-loader
  9147. xhrSetup: undefined,
  9148. // used by xhr-loader
  9149. licenseXhrSetup: undefined,
  9150. // used by eme-controller
  9151. licenseResponseCallback: undefined,
  9152. // used by eme-controller
  9153. abrController: AbrController,
  9154. bufferController: BufferController,
  9155. capLevelController: CapLevelController,
  9156. errorController: ErrorController,
  9157. fpsController: FPSController,
  9158. stretchShortVideoTrack: false,
  9159. // used by mp4-remuxer
  9160. maxAudioFramesDrift: 1,
  9161. // used by mp4-remuxer
  9162. forceKeyFrameOnDiscontinuity: true,
  9163. // used by ts-demuxer
  9164. abrEwmaFastLive: 3,
  9165. // used by abr-controller
  9166. abrEwmaSlowLive: 9,
  9167. // used by abr-controller
  9168. abrEwmaFastVoD: 3,
  9169. // used by abr-controller
  9170. abrEwmaSlowVoD: 9,
  9171. // used by abr-controller
  9172. abrEwmaDefaultEstimate: 5e5,
  9173. // 500 kbps // used by abr-controller
  9174. abrEwmaDefaultEstimateMax: 5e6,
  9175. // 5 mbps
  9176. abrBandWidthFactor: 0.95,
  9177. // used by abr-controller
  9178. abrBandWidthUpFactor: 0.7,
  9179. // used by abr-controller
  9180. abrMaxWithRealBitrate: false,
  9181. // used by abr-controller
  9182. maxStarvationDelay: 4,
  9183. // used by abr-controller
  9184. maxLoadingDelay: 4,
  9185. // used by abr-controller
  9186. minAutoBitrate: 0,
  9187. // used by hls
  9188. emeEnabled: false,
  9189. // used by eme-controller
  9190. widevineLicenseUrl: undefined,
  9191. // used by eme-controller
  9192. drmSystems: {},
  9193. // used by eme-controller
  9194. drmSystemOptions: {},
  9195. // used by eme-controller
  9196. requestMediaKeySystemAccessFunc: null,
  9197. // used by eme-controller
  9198. testBandwidth: true,
  9199. progressive: false,
  9200. lowLatencyMode: true,
  9201. cmcd: undefined,
  9202. enableDateRangeMetadataCues: true,
  9203. enableEmsgMetadataCues: true,
  9204. enableID3MetadataCues: true,
  9205. useMediaCapabilities: false,
  9206. certLoadPolicy: {
  9207. default: defaultLoadPolicy
  9208. },
  9209. keyLoadPolicy: {
  9210. default: {
  9211. maxTimeToFirstByteMs: 8000,
  9212. maxLoadTimeMs: 20000,
  9213. timeoutRetry: {
  9214. maxNumRetry: 1,
  9215. retryDelayMs: 1000,
  9216. maxRetryDelayMs: 20000,
  9217. backoff: 'linear'
  9218. },
  9219. errorRetry: {
  9220. maxNumRetry: 8,
  9221. retryDelayMs: 1000,
  9222. maxRetryDelayMs: 20000,
  9223. backoff: 'linear'
  9224. }
  9225. }
  9226. },
  9227. manifestLoadPolicy: {
  9228. default: {
  9229. maxTimeToFirstByteMs: Infinity,
  9230. maxLoadTimeMs: 20000,
  9231. timeoutRetry: {
  9232. maxNumRetry: 2,
  9233. retryDelayMs: 0,
  9234. maxRetryDelayMs: 0
  9235. },
  9236. errorRetry: {
  9237. maxNumRetry: 1,
  9238. retryDelayMs: 1000,
  9239. maxRetryDelayMs: 8000
  9240. }
  9241. }
  9242. },
  9243. playlistLoadPolicy: {
  9244. default: {
  9245. maxTimeToFirstByteMs: 10000,
  9246. maxLoadTimeMs: 20000,
  9247. timeoutRetry: {
  9248. maxNumRetry: 2,
  9249. retryDelayMs: 0,
  9250. maxRetryDelayMs: 0
  9251. },
  9252. errorRetry: {
  9253. maxNumRetry: 2,
  9254. retryDelayMs: 1000,
  9255. maxRetryDelayMs: 8000
  9256. }
  9257. }
  9258. },
  9259. fragLoadPolicy: {
  9260. default: {
  9261. maxTimeToFirstByteMs: 10000,
  9262. maxLoadTimeMs: 120000,
  9263. timeoutRetry: {
  9264. maxNumRetry: 4,
  9265. retryDelayMs: 0,
  9266. maxRetryDelayMs: 0
  9267. },
  9268. errorRetry: {
  9269. maxNumRetry: 6,
  9270. retryDelayMs: 1000,
  9271. maxRetryDelayMs: 8000
  9272. }
  9273. }
  9274. },
  9275. steeringManifestLoadPolicy: {
  9276. default: {
  9277. maxTimeToFirstByteMs: 10000,
  9278. maxLoadTimeMs: 20000,
  9279. timeoutRetry: {
  9280. maxNumRetry: 2,
  9281. retryDelayMs: 0,
  9282. maxRetryDelayMs: 0
  9283. },
  9284. errorRetry: {
  9285. maxNumRetry: 1,
  9286. retryDelayMs: 1000,
  9287. maxRetryDelayMs: 8000
  9288. }
  9289. }
  9290. },
  9291. // These default settings are deprecated in favor of the above policies
  9292. // and are maintained for backwards compatibility
  9293. manifestLoadingTimeOut: 10000,
  9294. manifestLoadingMaxRetry: 1,
  9295. manifestLoadingRetryDelay: 1000,
  9296. manifestLoadingMaxRetryTimeout: 64000,
  9297. levelLoadingTimeOut: 10000,
  9298. levelLoadingMaxRetry: 4,
  9299. levelLoadingRetryDelay: 1000,
  9300. levelLoadingMaxRetryTimeout: 64000,
  9301. fragLoadingTimeOut: 20000,
  9302. fragLoadingMaxRetry: 6,
  9303. fragLoadingRetryDelay: 1000,
  9304. fragLoadingMaxRetryTimeout: 64000
  9305. }, timelineConfig()), {}, {
  9306. subtitleStreamController: undefined,
  9307. subtitleTrackController: undefined,
  9308. timelineController: undefined,
  9309. audioStreamController: undefined,
  9310. audioTrackController: undefined,
  9311. emeController: undefined,
  9312. cmcdController: undefined,
  9313. contentSteeringController: ContentSteeringController
  9314. });
  9315. function timelineConfig() {
  9316. return {
  9317. cueHandler: Cues,
  9318. // used by timeline-controller
  9319. enableWebVTT: false,
  9320. // used by timeline-controller
  9321. enableIMSC1: false,
  9322. // used by timeline-controller
  9323. enableCEA708Captions: false,
  9324. // used by timeline-controller
  9325. captionsTextTrack1Label: 'English',
  9326. // used by timeline-controller
  9327. captionsTextTrack1LanguageCode: 'en',
  9328. // used by timeline-controller
  9329. captionsTextTrack2Label: 'Spanish',
  9330. // used by timeline-controller
  9331. captionsTextTrack2LanguageCode: 'es',
  9332. // used by timeline-controller
  9333. captionsTextTrack3Label: 'Unknown CC',
  9334. // used by timeline-controller
  9335. captionsTextTrack3LanguageCode: '',
  9336. // used by timeline-controller
  9337. captionsTextTrack4Label: 'Unknown CC',
  9338. // used by timeline-controller
  9339. captionsTextTrack4LanguageCode: '',
  9340. // used by timeline-controller
  9341. renderTextTracksNatively: true
  9342. };
  9343. }
  9344. /**
  9345. * @ignore
  9346. */
  9347. function mergeConfig(defaultConfig, userConfig) {
  9348. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  9349. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  9350. }
  9351. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  9352. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  9353. }
  9354. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  9355. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  9356. }
  9357. const defaultsCopy = deepCpy(defaultConfig);
  9358. // Backwards compatibility with deprecated config values
  9359. const deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  9360. const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  9361. deprecatedSettingTypes.forEach(type => {
  9362. const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;
  9363. const policyNotSet = userConfig[policyName] === undefined;
  9364. const report = [];
  9365. deprecatedSettings.forEach(setting => {
  9366. const deprecatedSetting = `${type}Loading${setting}`;
  9367. const value = userConfig[deprecatedSetting];
  9368. if (value !== undefined && policyNotSet) {
  9369. report.push(deprecatedSetting);
  9370. const settings = defaultsCopy[policyName].default;
  9371. userConfig[policyName] = {
  9372. default: settings
  9373. };
  9374. switch (setting) {
  9375. case 'TimeOut':
  9376. settings.maxLoadTimeMs = value;
  9377. settings.maxTimeToFirstByteMs = value;
  9378. break;
  9379. case 'MaxRetry':
  9380. settings.errorRetry.maxNumRetry = value;
  9381. settings.timeoutRetry.maxNumRetry = value;
  9382. break;
  9383. case 'RetryDelay':
  9384. settings.errorRetry.retryDelayMs = value;
  9385. settings.timeoutRetry.retryDelayMs = value;
  9386. break;
  9387. case 'MaxRetryTimeout':
  9388. settings.errorRetry.maxRetryDelayMs = value;
  9389. settings.timeoutRetry.maxRetryDelayMs = value;
  9390. break;
  9391. }
  9392. }
  9393. });
  9394. if (report.length) {
  9395. logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${JSON.stringify(userConfig[policyName])}`);
  9396. }
  9397. });
  9398. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  9399. }
  9400. function deepCpy(obj) {
  9401. if (obj && typeof obj === 'object') {
  9402. if (Array.isArray(obj)) {
  9403. return obj.map(deepCpy);
  9404. }
  9405. return Object.keys(obj).reduce((result, key) => {
  9406. result[key] = deepCpy(obj[key]);
  9407. return result;
  9408. }, {});
  9409. }
  9410. return obj;
  9411. }
  9412. /**
  9413. * @ignore
  9414. */
  9415. function enableStreamingMode(config) {
  9416. const currentLoader = config.loader;
  9417. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  9418. // If a developer has configured their own loader, respect that choice
  9419. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  9420. config.progressive = false;
  9421. } else {
  9422. const canStreamProgressively = fetchSupported();
  9423. if (canStreamProgressively) {
  9424. config.loader = FetchLoader;
  9425. config.progressive = true;
  9426. config.enableSoftwareAES = true;
  9427. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  9428. }
  9429. }
  9430. }
  9431. let chromeOrFirefox;
  9432. class LevelController extends BasePlaylistController {
  9433. constructor(hls, contentSteeringController) {
  9434. super(hls, '[level-controller]');
  9435. this._levels = [];
  9436. this._firstLevel = -1;
  9437. this._maxAutoLevel = -1;
  9438. this._startLevel = void 0;
  9439. this.currentLevel = null;
  9440. this.currentLevelIndex = -1;
  9441. this.manualLevelIndex = -1;
  9442. this.steering = void 0;
  9443. this.onParsedComplete = void 0;
  9444. this.steering = contentSteeringController;
  9445. this._registerListeners();
  9446. }
  9447. _registerListeners() {
  9448. const {
  9449. hls
  9450. } = this;
  9451. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9452. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9453. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9454. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9455. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9456. hls.on(Events.ERROR, this.onError, this);
  9457. }
  9458. _unregisterListeners() {
  9459. const {
  9460. hls
  9461. } = this;
  9462. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9463. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9464. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9465. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9466. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9467. hls.off(Events.ERROR, this.onError, this);
  9468. }
  9469. destroy() {
  9470. this._unregisterListeners();
  9471. this.steering = null;
  9472. this.resetLevels();
  9473. super.destroy();
  9474. }
  9475. stopLoad() {
  9476. const levels = this._levels;
  9477. // clean up live level details to force reload them, and reset load errors
  9478. levels.forEach(level => {
  9479. level.loadError = 0;
  9480. level.fragmentError = 0;
  9481. });
  9482. super.stopLoad();
  9483. }
  9484. resetLevels() {
  9485. this._startLevel = undefined;
  9486. this.manualLevelIndex = -1;
  9487. this.currentLevelIndex = -1;
  9488. this.currentLevel = null;
  9489. this._levels = [];
  9490. this._maxAutoLevel = -1;
  9491. }
  9492. onManifestLoading(event, data) {
  9493. this.resetLevels();
  9494. }
  9495. onManifestLoaded(event, data) {
  9496. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  9497. const levels = [];
  9498. const redundantSet = {};
  9499. const generatePathwaySet = {};
  9500. let resolutionFound = false;
  9501. let videoCodecFound = false;
  9502. let audioCodecFound = false;
  9503. data.levels.forEach(levelParsed => {
  9504. var _audioCodec, _videoCodec;
  9505. const attributes = levelParsed.attrs;
  9506. // erase audio codec info if browser does not support mp4a.40.34.
  9507. // demuxer will autodetect codec and fallback to mpeg/audio
  9508. let {
  9509. audioCodec,
  9510. videoCodec
  9511. } = levelParsed;
  9512. if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf('mp4a.40.34')) !== -1) {
  9513. chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent));
  9514. if (chromeOrFirefox) {
  9515. levelParsed.audioCodec = audioCodec = undefined;
  9516. }
  9517. }
  9518. if (audioCodec) {
  9519. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource);
  9520. }
  9521. if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {
  9522. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  9523. }
  9524. // only keep levels with supported audio/video codecs
  9525. const {
  9526. width,
  9527. height,
  9528. unknownCodecs
  9529. } = levelParsed;
  9530. resolutionFound || (resolutionFound = !!(width && height));
  9531. videoCodecFound || (videoCodecFound = !!videoCodec);
  9532. audioCodecFound || (audioCodecFound = !!audioCodec);
  9533. if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, 'audio', preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, 'video', preferManagedMediaSource)) {
  9534. return;
  9535. }
  9536. const {
  9537. CODECS,
  9538. 'FRAME-RATE': FRAMERATE,
  9539. 'HDCP-LEVEL': HDCP,
  9540. 'PATHWAY-ID': PATHWAY,
  9541. RESOLUTION,
  9542. 'VIDEO-RANGE': VIDEO_RANGE
  9543. } = attributes;
  9544. const contentSteeringPrefix = `${PATHWAY || '.'}-`;
  9545. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  9546. if (!redundantSet[levelKey]) {
  9547. const level = new Level(levelParsed);
  9548. redundantSet[levelKey] = level;
  9549. generatePathwaySet[levelKey] = 1;
  9550. levels.push(level);
  9551. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  9552. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  9553. // Content Steering controller to handles Pathway fallback on error
  9554. const pathwayCount = generatePathwaySet[levelKey] += 1;
  9555. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  9556. const level = new Level(levelParsed);
  9557. redundantSet[levelKey] = level;
  9558. levels.push(level);
  9559. } else {
  9560. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  9561. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  9562. }
  9563. });
  9564. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  9565. }
  9566. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  9567. let audioTracks = [];
  9568. let subtitleTracks = [];
  9569. let levels = filteredLevels;
  9570. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  9571. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  9572. levels = levels.filter(({
  9573. videoCodec,
  9574. videoRange,
  9575. width,
  9576. height
  9577. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  9578. }
  9579. if (levels.length === 0) {
  9580. // Dispatch error after MANIFEST_LOADED is done propagating
  9581. Promise.resolve().then(() => {
  9582. if (this.hls) {
  9583. if (data.levels.length) {
  9584. this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(data.levels[0].attrs)}`);
  9585. }
  9586. const error = new Error('no level with compatible codecs found in manifest');
  9587. this.hls.trigger(Events.ERROR, {
  9588. type: ErrorTypes.MEDIA_ERROR,
  9589. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  9590. fatal: true,
  9591. url: data.url,
  9592. error,
  9593. reason: error.message
  9594. });
  9595. }
  9596. });
  9597. return;
  9598. }
  9599. if (data.audioTracks) {
  9600. const {
  9601. preferManagedMediaSource
  9602. } = this.hls.config;
  9603. audioTracks = data.audioTracks.filter(track => !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, 'audio', preferManagedMediaSource));
  9604. // Assign ids after filtering as array indices by group-id
  9605. assignTrackIdsByGroup(audioTracks);
  9606. }
  9607. if (data.subtitles) {
  9608. subtitleTracks = data.subtitles;
  9609. assignTrackIdsByGroup(subtitleTracks);
  9610. }
  9611. // start bitrate is the first bitrate of the manifest
  9612. const unsortedLevels = levels.slice(0);
  9613. // sort levels from lowest to highest
  9614. levels.sort((a, b) => {
  9615. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  9616. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  9617. }
  9618. // sort on height before bitrate for cap-level-controller
  9619. if (resolutionFound && a.height !== b.height) {
  9620. return a.height - b.height;
  9621. }
  9622. if (a.frameRate !== b.frameRate) {
  9623. return a.frameRate - b.frameRate;
  9624. }
  9625. if (a.videoRange !== b.videoRange) {
  9626. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  9627. }
  9628. if (a.videoCodec !== b.videoCodec) {
  9629. const valueA = videoCodecPreferenceValue(a.videoCodec);
  9630. const valueB = videoCodecPreferenceValue(b.videoCodec);
  9631. if (valueA !== valueB) {
  9632. return valueB - valueA;
  9633. }
  9634. }
  9635. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  9636. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  9637. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  9638. if (valueA !== valueB) {
  9639. return valueB - valueA;
  9640. }
  9641. }
  9642. if (a.averageBitrate !== b.averageBitrate) {
  9643. return a.averageBitrate - b.averageBitrate;
  9644. }
  9645. return 0;
  9646. });
  9647. let firstLevelInPlaylist = unsortedLevels[0];
  9648. if (this.steering) {
  9649. levels = this.steering.filterParsedLevels(levels);
  9650. if (levels.length !== unsortedLevels.length) {
  9651. for (let i = 0; i < unsortedLevels.length; i++) {
  9652. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  9653. firstLevelInPlaylist = unsortedLevels[i];
  9654. break;
  9655. }
  9656. }
  9657. }
  9658. }
  9659. this._levels = levels;
  9660. // find index of first level in sorted levels
  9661. for (let i = 0; i < levels.length; i++) {
  9662. if (levels[i] === firstLevelInPlaylist) {
  9663. var _this$hls$userConfig;
  9664. this._firstLevel = i;
  9665. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  9666. const bandwidthEstimate = this.hls.bandwidthEstimate;
  9667. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  9668. // Update default bwe to first variant bitrate as long it has not been configured or set
  9669. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  9670. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  9671. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) {
  9672. this.hls.bandwidthEstimate = startingBwEstimate;
  9673. }
  9674. }
  9675. break;
  9676. }
  9677. }
  9678. // Audio is only alternate if manifest include a URI along with the audio group tag,
  9679. // and this is not an audio-only stream where levels contain audio-only
  9680. const audioOnly = audioCodecFound && !videoCodecFound;
  9681. const edata = {
  9682. levels,
  9683. audioTracks,
  9684. subtitleTracks,
  9685. sessionData: data.sessionData,
  9686. sessionKeys: data.sessionKeys,
  9687. firstLevel: this._firstLevel,
  9688. stats: data.stats,
  9689. audio: audioCodecFound,
  9690. video: videoCodecFound,
  9691. altAudio: !audioOnly && audioTracks.some(t => !!t.url)
  9692. };
  9693. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  9694. // Initiate loading after all controllers have received MANIFEST_PARSED
  9695. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  9696. this.hls.startLoad(this.hls.config.startPosition);
  9697. }
  9698. }
  9699. get levels() {
  9700. if (this._levels.length === 0) {
  9701. return null;
  9702. }
  9703. return this._levels;
  9704. }
  9705. get level() {
  9706. return this.currentLevelIndex;
  9707. }
  9708. set level(newLevel) {
  9709. const levels = this._levels;
  9710. if (levels.length === 0) {
  9711. return;
  9712. }
  9713. // check if level idx is valid
  9714. if (newLevel < 0 || newLevel >= levels.length) {
  9715. // invalid level id given, trigger error
  9716. const error = new Error('invalid level idx');
  9717. const fatal = newLevel < 0;
  9718. this.hls.trigger(Events.ERROR, {
  9719. type: ErrorTypes.OTHER_ERROR,
  9720. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  9721. level: newLevel,
  9722. fatal,
  9723. error,
  9724. reason: error.message
  9725. });
  9726. if (fatal) {
  9727. return;
  9728. }
  9729. newLevel = Math.min(newLevel, levels.length - 1);
  9730. }
  9731. const lastLevelIndex = this.currentLevelIndex;
  9732. const lastLevel = this.currentLevel;
  9733. const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  9734. const level = levels[newLevel];
  9735. const pathwayId = level.attrs['PATHWAY-ID'];
  9736. this.currentLevelIndex = newLevel;
  9737. this.currentLevel = level;
  9738. if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) {
  9739. return;
  9740. }
  9741. 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 : ''}`);
  9742. const levelSwitchingData = {
  9743. level: newLevel,
  9744. attrs: level.attrs,
  9745. details: level.details,
  9746. bitrate: level.bitrate,
  9747. averageBitrate: level.averageBitrate,
  9748. maxBitrate: level.maxBitrate,
  9749. realBitrate: level.realBitrate,
  9750. width: level.width,
  9751. height: level.height,
  9752. codecSet: level.codecSet,
  9753. audioCodec: level.audioCodec,
  9754. videoCodec: level.videoCodec,
  9755. audioGroups: level.audioGroups,
  9756. subtitleGroups: level.subtitleGroups,
  9757. loaded: level.loaded,
  9758. loadError: level.loadError,
  9759. fragmentError: level.fragmentError,
  9760. name: level.name,
  9761. id: level.id,
  9762. uri: level.uri,
  9763. url: level.url,
  9764. urlId: 0,
  9765. audioGroupIds: level.audioGroupIds,
  9766. textGroupIds: level.textGroupIds
  9767. };
  9768. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  9769. // check if we need to load playlist for this level
  9770. const levelDetails = level.details;
  9771. if (!levelDetails || levelDetails.live) {
  9772. // level not retrieved yet, or live playlist we need to (re)load it
  9773. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  9774. this.loadPlaylist(hlsUrlParameters);
  9775. }
  9776. }
  9777. get manualLevel() {
  9778. return this.manualLevelIndex;
  9779. }
  9780. set manualLevel(newLevel) {
  9781. this.manualLevelIndex = newLevel;
  9782. if (this._startLevel === undefined) {
  9783. this._startLevel = newLevel;
  9784. }
  9785. if (newLevel !== -1) {
  9786. this.level = newLevel;
  9787. }
  9788. }
  9789. get firstLevel() {
  9790. return this._firstLevel;
  9791. }
  9792. set firstLevel(newLevel) {
  9793. this._firstLevel = newLevel;
  9794. }
  9795. get startLevel() {
  9796. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  9797. if (this._startLevel === undefined) {
  9798. const configStartLevel = this.hls.config.startLevel;
  9799. if (configStartLevel !== undefined) {
  9800. return configStartLevel;
  9801. }
  9802. return this.hls.firstAutoLevel;
  9803. }
  9804. return this._startLevel;
  9805. }
  9806. set startLevel(newLevel) {
  9807. this._startLevel = newLevel;
  9808. }
  9809. onError(event, data) {
  9810. if (data.fatal || !data.context) {
  9811. return;
  9812. }
  9813. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  9814. this.checkRetry(data);
  9815. }
  9816. }
  9817. // reset errors on the successful load of a fragment
  9818. onFragBuffered(event, {
  9819. frag
  9820. }) {
  9821. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  9822. const el = frag.elementaryStreams;
  9823. if (!Object.keys(el).some(type => !!el[type])) {
  9824. return;
  9825. }
  9826. const level = this._levels[frag.level];
  9827. if (level != null && level.loadError) {
  9828. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  9829. level.loadError = 0;
  9830. }
  9831. }
  9832. }
  9833. onLevelLoaded(event, data) {
  9834. var _data$deliveryDirecti2;
  9835. const {
  9836. level,
  9837. details
  9838. } = data;
  9839. const curLevel = this._levels[level];
  9840. if (!curLevel) {
  9841. var _data$deliveryDirecti;
  9842. this.warn(`Invalid level index ${level}`);
  9843. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  9844. details.deltaUpdateFailed = true;
  9845. }
  9846. return;
  9847. }
  9848. // only process level loaded events matching with expected level
  9849. if (level === this.currentLevelIndex) {
  9850. // reset level load error counter on successful level loaded only if there is no issues with fragments
  9851. if (curLevel.fragmentError === 0) {
  9852. curLevel.loadError = 0;
  9853. }
  9854. this.playlistLoaded(level, data, curLevel.details);
  9855. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  9856. // received a delta playlist update that cannot be merged
  9857. details.deltaUpdateFailed = true;
  9858. }
  9859. }
  9860. loadPlaylist(hlsUrlParameters) {
  9861. super.loadPlaylist();
  9862. const currentLevelIndex = this.currentLevelIndex;
  9863. const currentLevel = this.currentLevel;
  9864. if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {
  9865. let url = currentLevel.uri;
  9866. if (hlsUrlParameters) {
  9867. try {
  9868. url = hlsUrlParameters.addDirectives(url);
  9869. } catch (error) {
  9870. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  9871. }
  9872. }
  9873. const pathwayId = currentLevel.attrs['PATHWAY-ID'];
  9874. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''} with${pathwayId ? ' Pathway ' + pathwayId : ''} ${url}`);
  9875. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  9876. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  9877. this.clearTimer();
  9878. this.hls.trigger(Events.LEVEL_LOADING, {
  9879. url,
  9880. level: currentLevelIndex,
  9881. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  9882. id: 0,
  9883. // Deprecated Level urlId
  9884. deliveryDirectives: hlsUrlParameters || null
  9885. });
  9886. }
  9887. }
  9888. get nextLoadLevel() {
  9889. if (this.manualLevelIndex !== -1) {
  9890. return this.manualLevelIndex;
  9891. } else {
  9892. return this.hls.nextAutoLevel;
  9893. }
  9894. }
  9895. set nextLoadLevel(nextLevel) {
  9896. this.level = nextLevel;
  9897. if (this.manualLevelIndex === -1) {
  9898. this.hls.nextAutoLevel = nextLevel;
  9899. }
  9900. }
  9901. removeLevel(levelIndex) {
  9902. var _this$currentLevel;
  9903. const levels = this._levels.filter((level, index) => {
  9904. if (index !== levelIndex) {
  9905. return true;
  9906. }
  9907. if (this.steering) {
  9908. this.steering.removeLevel(level);
  9909. }
  9910. if (level === this.currentLevel) {
  9911. this.currentLevel = null;
  9912. this.currentLevelIndex = -1;
  9913. if (level.details) {
  9914. level.details.fragments.forEach(f => f.level = -1);
  9915. }
  9916. }
  9917. return false;
  9918. });
  9919. reassignFragmentLevelIndexes(levels);
  9920. this._levels = levels;
  9921. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  9922. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  9923. }
  9924. this.hls.trigger(Events.LEVELS_UPDATED, {
  9925. levels
  9926. });
  9927. }
  9928. onLevelsUpdated(event, {
  9929. levels
  9930. }) {
  9931. this._levels = levels;
  9932. }
  9933. checkMaxAutoUpdated() {
  9934. const {
  9935. autoLevelCapping,
  9936. maxAutoLevel,
  9937. maxHdcpLevel
  9938. } = this.hls;
  9939. if (this._maxAutoLevel !== maxAutoLevel) {
  9940. this._maxAutoLevel = maxAutoLevel;
  9941. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  9942. autoLevelCapping,
  9943. levels: this.levels,
  9944. maxAutoLevel,
  9945. minAutoLevel: this.hls.minAutoLevel,
  9946. maxHdcpLevel
  9947. });
  9948. }
  9949. }
  9950. }
  9951. function assignTrackIdsByGroup(tracks) {
  9952. const groups = {};
  9953. tracks.forEach(track => {
  9954. const groupId = track.groupId || '';
  9955. track.id = groups[groupId] = groups[groupId] || 0;
  9956. groups[groupId]++;
  9957. });
  9958. }
  9959. var FragmentState = {
  9960. NOT_LOADED: "NOT_LOADED",
  9961. APPENDING: "APPENDING",
  9962. PARTIAL: "PARTIAL",
  9963. OK: "OK"
  9964. };
  9965. class FragmentTracker {
  9966. constructor(hls) {
  9967. this.activePartLists = Object.create(null);
  9968. this.endListFragments = Object.create(null);
  9969. this.fragments = Object.create(null);
  9970. this.timeRanges = Object.create(null);
  9971. this.bufferPadding = 0.2;
  9972. this.hls = void 0;
  9973. this.hasGaps = false;
  9974. this.hls = hls;
  9975. this._registerListeners();
  9976. }
  9977. _registerListeners() {
  9978. const {
  9979. hls
  9980. } = this;
  9981. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  9982. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9983. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  9984. }
  9985. _unregisterListeners() {
  9986. const {
  9987. hls
  9988. } = this;
  9989. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  9990. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9991. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  9992. }
  9993. destroy() {
  9994. this._unregisterListeners();
  9995. // @ts-ignore
  9996. this.fragments =
  9997. // @ts-ignore
  9998. this.activePartLists =
  9999. // @ts-ignore
  10000. this.endListFragments = this.timeRanges = null;
  10001. }
  10002. /**
  10003. * Return a Fragment or Part with an appended range that matches the position and levelType
  10004. * Otherwise, return null
  10005. */
  10006. getAppendedFrag(position, levelType) {
  10007. const activeParts = this.activePartLists[levelType];
  10008. if (activeParts) {
  10009. for (let i = activeParts.length; i--;) {
  10010. const activePart = activeParts[i];
  10011. if (!activePart) {
  10012. break;
  10013. }
  10014. const appendedPTS = activePart.end;
  10015. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  10016. return activePart;
  10017. }
  10018. }
  10019. }
  10020. return this.getBufferedFrag(position, levelType);
  10021. }
  10022. /**
  10023. * Return a buffered Fragment that matches the position and levelType.
  10024. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  10025. * If not found any Fragment, return null
  10026. */
  10027. getBufferedFrag(position, levelType) {
  10028. const {
  10029. fragments
  10030. } = this;
  10031. const keys = Object.keys(fragments);
  10032. for (let i = keys.length; i--;) {
  10033. const fragmentEntity = fragments[keys[i]];
  10034. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  10035. const frag = fragmentEntity.body;
  10036. if (frag.start <= position && position <= frag.end) {
  10037. return frag;
  10038. }
  10039. }
  10040. }
  10041. return null;
  10042. }
  10043. /**
  10044. * Partial fragments effected by coded frame eviction will be removed
  10045. * The browser will unload parts of the buffer to free up memory for new buffer data
  10046. * 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)
  10047. */
  10048. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) {
  10049. if (this.timeRanges) {
  10050. this.timeRanges[elementaryStream] = timeRange;
  10051. }
  10052. // Check if any flagged fragments have been unloaded
  10053. // excluding anything newer than appendedPartSn
  10054. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  10055. Object.keys(this.fragments).forEach(key => {
  10056. const fragmentEntity = this.fragments[key];
  10057. if (!fragmentEntity) {
  10058. return;
  10059. }
  10060. if (appendedPartSn >= fragmentEntity.body.sn) {
  10061. return;
  10062. }
  10063. if (!fragmentEntity.buffered && !fragmentEntity.loaded) {
  10064. if (fragmentEntity.body.type === playlistType) {
  10065. this.removeFragment(fragmentEntity.body);
  10066. }
  10067. return;
  10068. }
  10069. const esData = fragmentEntity.range[elementaryStream];
  10070. if (!esData) {
  10071. return;
  10072. }
  10073. esData.time.some(time => {
  10074. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  10075. if (isNotBuffered) {
  10076. // Unregister partial fragment as it needs to load again to be reused
  10077. this.removeFragment(fragmentEntity.body);
  10078. }
  10079. return isNotBuffered;
  10080. });
  10081. });
  10082. }
  10083. /**
  10084. * Checks if the fragment passed in is loaded in the buffer properly
  10085. * Partially loaded fragments will be registered as a partial fragment
  10086. */
  10087. detectPartialFragments(data) {
  10088. const timeRanges = this.timeRanges;
  10089. const {
  10090. frag,
  10091. part
  10092. } = data;
  10093. if (!timeRanges || frag.sn === 'initSegment') {
  10094. return;
  10095. }
  10096. const fragKey = getFragmentKey(frag);
  10097. const fragmentEntity = this.fragments[fragKey];
  10098. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  10099. return;
  10100. }
  10101. const isFragHint = !frag.relurl;
  10102. Object.keys(timeRanges).forEach(elementaryStream => {
  10103. const streamInfo = frag.elementaryStreams[elementaryStream];
  10104. if (!streamInfo) {
  10105. return;
  10106. }
  10107. const timeRange = timeRanges[elementaryStream];
  10108. const partial = isFragHint || streamInfo.partial === true;
  10109. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, part, partial, timeRange);
  10110. });
  10111. fragmentEntity.loaded = null;
  10112. if (Object.keys(fragmentEntity.range).length) {
  10113. fragmentEntity.buffered = true;
  10114. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  10115. if (endList) {
  10116. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  10117. }
  10118. if (!isPartial(fragmentEntity)) {
  10119. // Remove older fragment parts from lookup after frag is tracked as buffered
  10120. this.removeParts(frag.sn - 1, frag.type);
  10121. }
  10122. } else {
  10123. // remove fragment if nothing was appended
  10124. this.removeFragment(fragmentEntity.body);
  10125. }
  10126. }
  10127. removeParts(snToKeep, levelType) {
  10128. const activeParts = this.activePartLists[levelType];
  10129. if (!activeParts) {
  10130. return;
  10131. }
  10132. this.activePartLists[levelType] = activeParts.filter(part => part.fragment.sn >= snToKeep);
  10133. }
  10134. fragBuffered(frag, force) {
  10135. const fragKey = getFragmentKey(frag);
  10136. let fragmentEntity = this.fragments[fragKey];
  10137. if (!fragmentEntity && force) {
  10138. fragmentEntity = this.fragments[fragKey] = {
  10139. body: frag,
  10140. appendedPTS: null,
  10141. loaded: null,
  10142. buffered: false,
  10143. range: Object.create(null)
  10144. };
  10145. if (frag.gap) {
  10146. this.hasGaps = true;
  10147. }
  10148. }
  10149. if (fragmentEntity) {
  10150. fragmentEntity.loaded = null;
  10151. fragmentEntity.buffered = true;
  10152. }
  10153. }
  10154. getBufferedTimes(fragment, part, partial, timeRange) {
  10155. const buffered = {
  10156. time: [],
  10157. partial
  10158. };
  10159. const startPTS = fragment.start;
  10160. const endPTS = fragment.end;
  10161. const minEndPTS = fragment.minEndPTS || endPTS;
  10162. const maxStartPTS = fragment.maxStartPTS || startPTS;
  10163. for (let i = 0; i < timeRange.length; i++) {
  10164. const startTime = timeRange.start(i) - this.bufferPadding;
  10165. const endTime = timeRange.end(i) + this.bufferPadding;
  10166. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  10167. // Fragment is entirely contained in buffer
  10168. // No need to check the other timeRange times since it's completely playable
  10169. buffered.time.push({
  10170. startPTS: Math.max(startPTS, timeRange.start(i)),
  10171. endPTS: Math.min(endPTS, timeRange.end(i))
  10172. });
  10173. break;
  10174. } else if (startPTS < endTime && endPTS > startTime) {
  10175. const start = Math.max(startPTS, timeRange.start(i));
  10176. const end = Math.min(endPTS, timeRange.end(i));
  10177. if (end > start) {
  10178. buffered.partial = true;
  10179. // Check for intersection with buffer
  10180. // Get playable sections of the fragment
  10181. buffered.time.push({
  10182. startPTS: start,
  10183. endPTS: end
  10184. });
  10185. }
  10186. } else if (endPTS <= startTime) {
  10187. // No need to check the rest of the timeRange as it is in order
  10188. break;
  10189. }
  10190. }
  10191. return buffered;
  10192. }
  10193. /**
  10194. * Gets the partial fragment for a certain time
  10195. */
  10196. getPartialFragment(time) {
  10197. let bestFragment = null;
  10198. let timePadding;
  10199. let startTime;
  10200. let endTime;
  10201. let bestOverlap = 0;
  10202. const {
  10203. bufferPadding,
  10204. fragments
  10205. } = this;
  10206. Object.keys(fragments).forEach(key => {
  10207. const fragmentEntity = fragments[key];
  10208. if (!fragmentEntity) {
  10209. return;
  10210. }
  10211. if (isPartial(fragmentEntity)) {
  10212. startTime = fragmentEntity.body.start - bufferPadding;
  10213. endTime = fragmentEntity.body.end + bufferPadding;
  10214. if (time >= startTime && time <= endTime) {
  10215. // Use the fragment that has the most padding from start and end time
  10216. timePadding = Math.min(time - startTime, endTime - time);
  10217. if (bestOverlap <= timePadding) {
  10218. bestFragment = fragmentEntity.body;
  10219. bestOverlap = timePadding;
  10220. }
  10221. }
  10222. }
  10223. });
  10224. return bestFragment;
  10225. }
  10226. isEndListAppended(type) {
  10227. const lastFragmentEntity = this.endListFragments[type];
  10228. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  10229. }
  10230. getState(fragment) {
  10231. const fragKey = getFragmentKey(fragment);
  10232. const fragmentEntity = this.fragments[fragKey];
  10233. if (fragmentEntity) {
  10234. if (!fragmentEntity.buffered) {
  10235. return FragmentState.APPENDING;
  10236. } else if (isPartial(fragmentEntity)) {
  10237. return FragmentState.PARTIAL;
  10238. } else {
  10239. return FragmentState.OK;
  10240. }
  10241. }
  10242. return FragmentState.NOT_LOADED;
  10243. }
  10244. isTimeBuffered(startPTS, endPTS, timeRange) {
  10245. let startTime;
  10246. let endTime;
  10247. for (let i = 0; i < timeRange.length; i++) {
  10248. startTime = timeRange.start(i) - this.bufferPadding;
  10249. endTime = timeRange.end(i) + this.bufferPadding;
  10250. if (startPTS >= startTime && endPTS <= endTime) {
  10251. return true;
  10252. }
  10253. if (endPTS <= startTime) {
  10254. // No need to check the rest of the timeRange as it is in order
  10255. return false;
  10256. }
  10257. }
  10258. return false;
  10259. }
  10260. onFragLoaded(event, data) {
  10261. const {
  10262. frag,
  10263. part
  10264. } = data;
  10265. // don't track initsegment (for which sn is not a number)
  10266. // don't track frags used for bitrateTest, they're irrelevant.
  10267. if (frag.sn === 'initSegment' || frag.bitrateTest) {
  10268. return;
  10269. }
  10270. // Fragment entity `loaded` FragLoadedData is null when loading parts
  10271. const loaded = part ? null : data;
  10272. const fragKey = getFragmentKey(frag);
  10273. this.fragments[fragKey] = {
  10274. body: frag,
  10275. appendedPTS: null,
  10276. loaded,
  10277. buffered: false,
  10278. range: Object.create(null)
  10279. };
  10280. }
  10281. onBufferAppended(event, data) {
  10282. const {
  10283. frag,
  10284. part,
  10285. timeRanges
  10286. } = data;
  10287. if (frag.sn === 'initSegment') {
  10288. return;
  10289. }
  10290. const playlistType = frag.type;
  10291. if (part) {
  10292. let activeParts = this.activePartLists[playlistType];
  10293. if (!activeParts) {
  10294. this.activePartLists[playlistType] = activeParts = [];
  10295. }
  10296. activeParts.push(part);
  10297. }
  10298. // Store the latest timeRanges loaded in the buffer
  10299. this.timeRanges = timeRanges;
  10300. Object.keys(timeRanges).forEach(elementaryStream => {
  10301. const timeRange = timeRanges[elementaryStream];
  10302. this.detectEvictedFragments(elementaryStream, timeRange, playlistType, part);
  10303. });
  10304. }
  10305. onFragBuffered(event, data) {
  10306. this.detectPartialFragments(data);
  10307. }
  10308. hasFragment(fragment) {
  10309. const fragKey = getFragmentKey(fragment);
  10310. return !!this.fragments[fragKey];
  10311. }
  10312. hasParts(type) {
  10313. var _this$activePartLists;
  10314. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  10315. }
  10316. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  10317. if (withGapOnly && !this.hasGaps) {
  10318. return;
  10319. }
  10320. Object.keys(this.fragments).forEach(key => {
  10321. const fragmentEntity = this.fragments[key];
  10322. if (!fragmentEntity) {
  10323. return;
  10324. }
  10325. const frag = fragmentEntity.body;
  10326. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  10327. return;
  10328. }
  10329. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  10330. this.removeFragment(frag);
  10331. }
  10332. });
  10333. }
  10334. removeFragment(fragment) {
  10335. const fragKey = getFragmentKey(fragment);
  10336. fragment.stats.loaded = 0;
  10337. fragment.clearElementaryStreamInfo();
  10338. const activeParts = this.activePartLists[fragment.type];
  10339. if (activeParts) {
  10340. const snToRemove = fragment.sn;
  10341. this.activePartLists[fragment.type] = activeParts.filter(part => part.fragment.sn !== snToRemove);
  10342. }
  10343. delete this.fragments[fragKey];
  10344. if (fragment.endList) {
  10345. delete this.endListFragments[fragment.type];
  10346. }
  10347. }
  10348. removeAllFragments() {
  10349. this.fragments = Object.create(null);
  10350. this.endListFragments = Object.create(null);
  10351. this.activePartLists = Object.create(null);
  10352. this.hasGaps = false;
  10353. }
  10354. }
  10355. function isPartial(fragmentEntity) {
  10356. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  10357. 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));
  10358. }
  10359. function getFragmentKey(fragment) {
  10360. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  10361. }
  10362. const MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  10363. class FragmentLoader {
  10364. constructor(config) {
  10365. this.config = void 0;
  10366. this.loader = null;
  10367. this.partLoadTimeout = -1;
  10368. this.config = config;
  10369. }
  10370. destroy() {
  10371. if (this.loader) {
  10372. this.loader.destroy();
  10373. this.loader = null;
  10374. }
  10375. }
  10376. abort() {
  10377. if (this.loader) {
  10378. // Abort the loader for current fragment. Only one may load at any given time
  10379. this.loader.abort();
  10380. }
  10381. }
  10382. load(frag, onProgress) {
  10383. const url = frag.url;
  10384. if (!url) {
  10385. return Promise.reject(new LoadError({
  10386. type: ErrorTypes.NETWORK_ERROR,
  10387. details: ErrorDetails.FRAG_LOAD_ERROR,
  10388. fatal: false,
  10389. frag,
  10390. error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),
  10391. networkDetails: null
  10392. }));
  10393. }
  10394. this.abort();
  10395. const config = this.config;
  10396. const FragmentILoader = config.fLoader;
  10397. const DefaultILoader = config.loader;
  10398. return new Promise((resolve, reject) => {
  10399. if (this.loader) {
  10400. this.loader.destroy();
  10401. }
  10402. if (frag.gap) {
  10403. if (frag.tagList.some(tags => tags[0] === 'GAP')) {
  10404. reject(createGapLoadError(frag));
  10405. return;
  10406. } else {
  10407. // Reset temporary treatment as GAP tag
  10408. frag.gap = false;
  10409. }
  10410. }
  10411. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10412. const loaderContext = createLoaderContext(frag);
  10413. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10414. const loaderConfig = {
  10415. loadPolicy,
  10416. timeout: loadPolicy.maxLoadTimeMs,
  10417. maxRetry: 0,
  10418. retryDelay: 0,
  10419. maxRetryDelay: 0,
  10420. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  10421. };
  10422. // Assign frag stats to the loader's stats reference
  10423. frag.stats = loader.stats;
  10424. loader.load(loaderContext, loaderConfig, {
  10425. onSuccess: (response, stats, context, networkDetails) => {
  10426. this.resetLoader(frag, loader);
  10427. let payload = response.data;
  10428. if (context.resetIV && frag.decryptdata) {
  10429. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  10430. payload = payload.slice(16);
  10431. }
  10432. resolve({
  10433. frag,
  10434. part: null,
  10435. payload,
  10436. networkDetails
  10437. });
  10438. },
  10439. onError: (response, context, networkDetails, stats) => {
  10440. this.resetLoader(frag, loader);
  10441. reject(new LoadError({
  10442. type: ErrorTypes.NETWORK_ERROR,
  10443. details: ErrorDetails.FRAG_LOAD_ERROR,
  10444. fatal: false,
  10445. frag,
  10446. response: _objectSpread2({
  10447. url,
  10448. data: undefined
  10449. }, response),
  10450. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  10451. networkDetails,
  10452. stats
  10453. }));
  10454. },
  10455. onAbort: (stats, context, networkDetails) => {
  10456. this.resetLoader(frag, loader);
  10457. reject(new LoadError({
  10458. type: ErrorTypes.NETWORK_ERROR,
  10459. details: ErrorDetails.INTERNAL_ABORTED,
  10460. fatal: false,
  10461. frag,
  10462. error: new Error('Aborted'),
  10463. networkDetails,
  10464. stats
  10465. }));
  10466. },
  10467. onTimeout: (stats, context, networkDetails) => {
  10468. this.resetLoader(frag, loader);
  10469. reject(new LoadError({
  10470. type: ErrorTypes.NETWORK_ERROR,
  10471. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10472. fatal: false,
  10473. frag,
  10474. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  10475. networkDetails,
  10476. stats
  10477. }));
  10478. },
  10479. onProgress: (stats, context, data, networkDetails) => {
  10480. if (onProgress) {
  10481. onProgress({
  10482. frag,
  10483. part: null,
  10484. payload: data,
  10485. networkDetails
  10486. });
  10487. }
  10488. }
  10489. });
  10490. });
  10491. }
  10492. loadPart(frag, part, onProgress) {
  10493. this.abort();
  10494. const config = this.config;
  10495. const FragmentILoader = config.fLoader;
  10496. const DefaultILoader = config.loader;
  10497. return new Promise((resolve, reject) => {
  10498. if (this.loader) {
  10499. this.loader.destroy();
  10500. }
  10501. if (frag.gap || part.gap) {
  10502. reject(createGapLoadError(frag, part));
  10503. return;
  10504. }
  10505. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10506. const loaderContext = createLoaderContext(frag, part);
  10507. // Should we define another load policy for parts?
  10508. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10509. const loaderConfig = {
  10510. loadPolicy,
  10511. timeout: loadPolicy.maxLoadTimeMs,
  10512. maxRetry: 0,
  10513. retryDelay: 0,
  10514. maxRetryDelay: 0,
  10515. highWaterMark: MIN_CHUNK_SIZE
  10516. };
  10517. // Assign part stats to the loader's stats reference
  10518. part.stats = loader.stats;
  10519. loader.load(loaderContext, loaderConfig, {
  10520. onSuccess: (response, stats, context, networkDetails) => {
  10521. this.resetLoader(frag, loader);
  10522. this.updateStatsFromPart(frag, part);
  10523. const partLoadedData = {
  10524. frag,
  10525. part,
  10526. payload: response.data,
  10527. networkDetails
  10528. };
  10529. onProgress(partLoadedData);
  10530. resolve(partLoadedData);
  10531. },
  10532. onError: (response, context, networkDetails, stats) => {
  10533. this.resetLoader(frag, loader);
  10534. reject(new LoadError({
  10535. type: ErrorTypes.NETWORK_ERROR,
  10536. details: ErrorDetails.FRAG_LOAD_ERROR,
  10537. fatal: false,
  10538. frag,
  10539. part,
  10540. response: _objectSpread2({
  10541. url: loaderContext.url,
  10542. data: undefined
  10543. }, response),
  10544. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  10545. networkDetails,
  10546. stats
  10547. }));
  10548. },
  10549. onAbort: (stats, context, networkDetails) => {
  10550. frag.stats.aborted = part.stats.aborted;
  10551. this.resetLoader(frag, loader);
  10552. reject(new LoadError({
  10553. type: ErrorTypes.NETWORK_ERROR,
  10554. details: ErrorDetails.INTERNAL_ABORTED,
  10555. fatal: false,
  10556. frag,
  10557. part,
  10558. error: new Error('Aborted'),
  10559. networkDetails,
  10560. stats
  10561. }));
  10562. },
  10563. onTimeout: (stats, context, networkDetails) => {
  10564. this.resetLoader(frag, loader);
  10565. reject(new LoadError({
  10566. type: ErrorTypes.NETWORK_ERROR,
  10567. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10568. fatal: false,
  10569. frag,
  10570. part,
  10571. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  10572. networkDetails,
  10573. stats
  10574. }));
  10575. }
  10576. });
  10577. });
  10578. }
  10579. updateStatsFromPart(frag, part) {
  10580. const fragStats = frag.stats;
  10581. const partStats = part.stats;
  10582. const partTotal = partStats.total;
  10583. fragStats.loaded += partStats.loaded;
  10584. if (partTotal) {
  10585. const estTotalParts = Math.round(frag.duration / part.duration);
  10586. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  10587. const estRemainingParts = estTotalParts - estLoadedParts;
  10588. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  10589. fragStats.total = fragStats.loaded + estRemainingBytes;
  10590. } else {
  10591. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  10592. }
  10593. const fragLoading = fragStats.loading;
  10594. const partLoading = partStats.loading;
  10595. if (fragLoading.start) {
  10596. // add to fragment loader latency
  10597. fragLoading.first += partLoading.first - partLoading.start;
  10598. } else {
  10599. fragLoading.start = partLoading.start;
  10600. fragLoading.first = partLoading.first;
  10601. }
  10602. fragLoading.end = partLoading.end;
  10603. }
  10604. resetLoader(frag, loader) {
  10605. frag.loader = null;
  10606. if (this.loader === loader) {
  10607. self.clearTimeout(this.partLoadTimeout);
  10608. this.loader = null;
  10609. }
  10610. loader.destroy();
  10611. }
  10612. }
  10613. function createLoaderContext(frag, part = null) {
  10614. const segment = part || frag;
  10615. const loaderContext = {
  10616. frag,
  10617. part,
  10618. responseType: 'arraybuffer',
  10619. url: segment.url,
  10620. headers: {},
  10621. rangeStart: 0,
  10622. rangeEnd: 0
  10623. };
  10624. const start = segment.byteRangeStartOffset;
  10625. const end = segment.byteRangeEndOffset;
  10626. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  10627. var _frag$decryptdata;
  10628. let byteRangeStart = start;
  10629. let byteRangeEnd = end;
  10630. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  10631. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  10632. // has the unencrypted size specified in the range.
  10633. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  10634. const fragmentLen = end - start;
  10635. if (fragmentLen % 16) {
  10636. byteRangeEnd = end + (16 - fragmentLen % 16);
  10637. }
  10638. if (start !== 0) {
  10639. loaderContext.resetIV = true;
  10640. byteRangeStart = start - 16;
  10641. }
  10642. }
  10643. loaderContext.rangeStart = byteRangeStart;
  10644. loaderContext.rangeEnd = byteRangeEnd;
  10645. }
  10646. return loaderContext;
  10647. }
  10648. function createGapLoadError(frag, part) {
  10649. const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);
  10650. const errorData = {
  10651. type: ErrorTypes.MEDIA_ERROR,
  10652. details: ErrorDetails.FRAG_GAP,
  10653. fatal: false,
  10654. frag,
  10655. error,
  10656. networkDetails: null
  10657. };
  10658. if (part) {
  10659. errorData.part = part;
  10660. }
  10661. (part ? part : frag).stats.aborted = true;
  10662. return new LoadError(errorData);
  10663. }
  10664. class LoadError extends Error {
  10665. constructor(data) {
  10666. super(data.error.message);
  10667. this.data = void 0;
  10668. this.data = data;
  10669. }
  10670. }
  10671. class KeyLoader {
  10672. constructor(config) {
  10673. this.config = void 0;
  10674. this.keyUriToKeyInfo = {};
  10675. this.emeController = null;
  10676. this.config = config;
  10677. }
  10678. abort(type) {
  10679. for (const uri in this.keyUriToKeyInfo) {
  10680. const loader = this.keyUriToKeyInfo[uri].loader;
  10681. if (loader) {
  10682. var _loader$context;
  10683. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  10684. return;
  10685. }
  10686. loader.abort();
  10687. }
  10688. }
  10689. }
  10690. detach() {
  10691. for (const uri in this.keyUriToKeyInfo) {
  10692. const keyInfo = this.keyUriToKeyInfo[uri];
  10693. // Remove cached EME keys on detach
  10694. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  10695. delete this.keyUriToKeyInfo[uri];
  10696. }
  10697. }
  10698. }
  10699. destroy() {
  10700. this.detach();
  10701. for (const uri in this.keyUriToKeyInfo) {
  10702. const loader = this.keyUriToKeyInfo[uri].loader;
  10703. if (loader) {
  10704. loader.destroy();
  10705. }
  10706. }
  10707. this.keyUriToKeyInfo = {};
  10708. }
  10709. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  10710. return new LoadError({
  10711. type: ErrorTypes.NETWORK_ERROR,
  10712. details,
  10713. fatal: false,
  10714. frag,
  10715. response,
  10716. error,
  10717. networkDetails
  10718. });
  10719. }
  10720. loadClear(loadingFrag, encryptedFragments) {
  10721. if (this.emeController && this.config.emeEnabled) {
  10722. // access key-system with nearest key on start (loaidng frag is unencrypted)
  10723. const {
  10724. sn,
  10725. cc
  10726. } = loadingFrag;
  10727. for (let i = 0; i < encryptedFragments.length; i++) {
  10728. const frag = encryptedFragments[i];
  10729. if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {
  10730. this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  10731. frag.setKeyFormat(keySystemFormat);
  10732. });
  10733. break;
  10734. }
  10735. }
  10736. }
  10737. }
  10738. load(frag) {
  10739. if (!frag.decryptdata && frag.encrypted && this.emeController) {
  10740. // Multiple keys, but none selected, resolve in eme-controller
  10741. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  10742. return this.loadInternal(frag, keySystemFormat);
  10743. });
  10744. }
  10745. return this.loadInternal(frag);
  10746. }
  10747. loadInternal(frag, keySystemFormat) {
  10748. var _keyInfo, _keyInfo2;
  10749. if (keySystemFormat) {
  10750. frag.setKeyFormat(keySystemFormat);
  10751. }
  10752. const decryptdata = frag.decryptdata;
  10753. if (!decryptdata) {
  10754. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');
  10755. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  10756. }
  10757. const uri = decryptdata.uri;
  10758. if (!uri) {
  10759. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  10760. }
  10761. let keyInfo = this.keyUriToKeyInfo[uri];
  10762. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  10763. decryptdata.key = keyInfo.decryptdata.key;
  10764. return Promise.resolve({
  10765. frag,
  10766. keyInfo
  10767. });
  10768. }
  10769. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  10770. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  10771. var _keyInfo$mediaKeySess;
  10772. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  10773. case undefined:
  10774. case 'status-pending':
  10775. case 'usable':
  10776. case 'usable-in-future':
  10777. return keyInfo.keyLoadPromise.then(keyLoadedData => {
  10778. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  10779. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  10780. return {
  10781. frag,
  10782. keyInfo
  10783. };
  10784. });
  10785. }
  10786. // If we have a key session and status and it is not pending or usable, continue
  10787. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  10788. }
  10789. // Load the key or return the loading promise
  10790. keyInfo = this.keyUriToKeyInfo[uri] = {
  10791. decryptdata,
  10792. keyLoadPromise: null,
  10793. loader: null,
  10794. mediaKeySessionContext: null
  10795. };
  10796. switch (decryptdata.method) {
  10797. case 'ISO-23001-7':
  10798. case 'SAMPLE-AES':
  10799. case 'SAMPLE-AES-CENC':
  10800. case 'SAMPLE-AES-CTR':
  10801. if (decryptdata.keyFormat === 'identity') {
  10802. // loadKeyHTTP handles http(s) and data URLs
  10803. return this.loadKeyHTTP(keyInfo, frag);
  10804. }
  10805. return this.loadKeyEME(keyInfo, frag);
  10806. case 'AES-128':
  10807. return this.loadKeyHTTP(keyInfo, frag);
  10808. default:
  10809. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  10810. }
  10811. }
  10812. loadKeyEME(keyInfo, frag) {
  10813. const keyLoadedData = {
  10814. frag,
  10815. keyInfo
  10816. };
  10817. if (this.emeController && this.config.emeEnabled) {
  10818. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  10819. if (keySessionContextPromise) {
  10820. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {
  10821. keyInfo.mediaKeySessionContext = keySessionContext;
  10822. return keyLoadedData;
  10823. })).catch(error => {
  10824. // Remove promise for license renewal or retry
  10825. keyInfo.keyLoadPromise = null;
  10826. throw error;
  10827. });
  10828. }
  10829. }
  10830. return Promise.resolve(keyLoadedData);
  10831. }
  10832. loadKeyHTTP(keyInfo, frag) {
  10833. const config = this.config;
  10834. const Loader = config.loader;
  10835. const keyLoader = new Loader(config);
  10836. frag.keyLoader = keyInfo.loader = keyLoader;
  10837. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  10838. const loaderContext = {
  10839. keyInfo,
  10840. frag,
  10841. responseType: 'arraybuffer',
  10842. url: keyInfo.decryptdata.uri
  10843. };
  10844. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  10845. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  10846. // this will also align retry logic with fragment-loader
  10847. const loadPolicy = config.keyLoadPolicy.default;
  10848. const loaderConfig = {
  10849. loadPolicy,
  10850. timeout: loadPolicy.maxLoadTimeMs,
  10851. maxRetry: 0,
  10852. retryDelay: 0,
  10853. maxRetryDelay: 0
  10854. };
  10855. const loaderCallbacks = {
  10856. onSuccess: (response, stats, context, networkDetails) => {
  10857. const {
  10858. frag,
  10859. keyInfo,
  10860. url: uri
  10861. } = context;
  10862. if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {
  10863. return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  10864. }
  10865. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  10866. // detach fragment key loader on load success
  10867. frag.keyLoader = null;
  10868. keyInfo.loader = null;
  10869. resolve({
  10870. frag,
  10871. keyInfo
  10872. });
  10873. },
  10874. onError: (response, context, networkDetails, stats) => {
  10875. this.resetLoader(context);
  10876. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  10877. url: loaderContext.url,
  10878. data: undefined
  10879. }, response)));
  10880. },
  10881. onTimeout: (stats, context, networkDetails) => {
  10882. this.resetLoader(context);
  10883. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  10884. },
  10885. onAbort: (stats, context, networkDetails) => {
  10886. this.resetLoader(context);
  10887. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  10888. }
  10889. };
  10890. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  10891. });
  10892. }
  10893. resetLoader(context) {
  10894. const {
  10895. frag,
  10896. keyInfo,
  10897. url: uri
  10898. } = context;
  10899. const loader = keyInfo.loader;
  10900. if (frag.keyLoader === loader) {
  10901. frag.keyLoader = null;
  10902. keyInfo.loader = null;
  10903. }
  10904. delete this.keyUriToKeyInfo[uri];
  10905. if (loader) {
  10906. loader.destroy();
  10907. }
  10908. }
  10909. }
  10910. /**
  10911. * @ignore
  10912. * Sub-class specialization of EventHandler base class.
  10913. *
  10914. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  10915. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  10916. *
  10917. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  10918. * using the `tick` method.
  10919. *
  10920. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  10921. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  10922. *
  10923. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  10924. * and cancelled with `clearNextTick`.
  10925. *
  10926. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  10927. *
  10928. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  10929. *
  10930. * Further explanations:
  10931. *
  10932. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  10933. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  10934. *
  10935. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  10936. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  10937. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  10938. */
  10939. class TaskLoop {
  10940. constructor() {
  10941. this._boundTick = void 0;
  10942. this._tickTimer = null;
  10943. this._tickInterval = null;
  10944. this._tickCallCount = 0;
  10945. this._boundTick = this.tick.bind(this);
  10946. }
  10947. destroy() {
  10948. this.onHandlerDestroying();
  10949. this.onHandlerDestroyed();
  10950. }
  10951. onHandlerDestroying() {
  10952. // clear all timers before unregistering from event bus
  10953. this.clearNextTick();
  10954. this.clearInterval();
  10955. }
  10956. onHandlerDestroyed() {}
  10957. hasInterval() {
  10958. return !!this._tickInterval;
  10959. }
  10960. hasNextTick() {
  10961. return !!this._tickTimer;
  10962. }
  10963. /**
  10964. * @param millis - Interval time (ms)
  10965. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  10966. */
  10967. setInterval(millis) {
  10968. if (!this._tickInterval) {
  10969. this._tickCallCount = 0;
  10970. this._tickInterval = self.setInterval(this._boundTick, millis);
  10971. return true;
  10972. }
  10973. return false;
  10974. }
  10975. /**
  10976. * @returns True when interval was cleared, false when none was set (no effect)
  10977. */
  10978. clearInterval() {
  10979. if (this._tickInterval) {
  10980. self.clearInterval(this._tickInterval);
  10981. this._tickInterval = null;
  10982. return true;
  10983. }
  10984. return false;
  10985. }
  10986. /**
  10987. * @returns True when timeout was cleared, false when none was set (no effect)
  10988. */
  10989. clearNextTick() {
  10990. if (this._tickTimer) {
  10991. self.clearTimeout(this._tickTimer);
  10992. this._tickTimer = null;
  10993. return true;
  10994. }
  10995. return false;
  10996. }
  10997. /**
  10998. * Will call the subclass doTick implementation in this main loop tick
  10999. * or in the next one (via setTimeout(,0)) in case it has already been called
  11000. * in this tick (in case this is a re-entrant call).
  11001. */
  11002. tick() {
  11003. this._tickCallCount++;
  11004. if (this._tickCallCount === 1) {
  11005. this.doTick();
  11006. // re-entrant call to tick from previous doTick call stack
  11007. // -> schedule a call on the next main loop iteration to process this task processing request
  11008. if (this._tickCallCount > 1) {
  11009. // make sure only one timer exists at any time at max
  11010. this.tickImmediate();
  11011. }
  11012. this._tickCallCount = 0;
  11013. }
  11014. }
  11015. tickImmediate() {
  11016. this.clearNextTick();
  11017. this._tickTimer = self.setTimeout(this._boundTick, 0);
  11018. }
  11019. /**
  11020. * For subclass to implement task logic
  11021. * @abstract
  11022. */
  11023. doTick() {}
  11024. }
  11025. class ChunkMetadata {
  11026. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  11027. this.level = void 0;
  11028. this.sn = void 0;
  11029. this.part = void 0;
  11030. this.id = void 0;
  11031. this.size = void 0;
  11032. this.partial = void 0;
  11033. this.transmuxing = getNewPerformanceTiming();
  11034. this.buffering = {
  11035. audio: getNewPerformanceTiming(),
  11036. video: getNewPerformanceTiming(),
  11037. audiovideo: getNewPerformanceTiming()
  11038. };
  11039. this.level = level;
  11040. this.sn = sn;
  11041. this.id = id;
  11042. this.size = size;
  11043. this.part = part;
  11044. this.partial = partial;
  11045. }
  11046. }
  11047. function getNewPerformanceTiming() {
  11048. return {
  11049. start: 0,
  11050. executeStart: 0,
  11051. executeEnd: 0,
  11052. end: 0
  11053. };
  11054. }
  11055. function findFirstFragWithCC(fragments, cc) {
  11056. for (let i = 0, len = fragments.length; i < len; i++) {
  11057. var _fragments$i;
  11058. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  11059. return fragments[i];
  11060. }
  11061. }
  11062. return null;
  11063. }
  11064. function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) {
  11065. if (switchDetails) {
  11066. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  11067. return true;
  11068. }
  11069. }
  11070. return false;
  11071. }
  11072. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  11073. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  11074. const prevFrags = prevDetails.fragments;
  11075. const curFrags = curDetails.fragments;
  11076. if (!curFrags.length || !prevFrags.length) {
  11077. logger.log('No fragments to align');
  11078. return;
  11079. }
  11080. const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  11081. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  11082. logger.log('No frag in previous level to align on');
  11083. return;
  11084. }
  11085. return prevStartFrag;
  11086. }
  11087. function adjustFragmentStart(frag, sliding) {
  11088. if (frag) {
  11089. const start = frag.start + sliding;
  11090. frag.start = frag.startPTS = start;
  11091. frag.endPTS = start + frag.duration;
  11092. }
  11093. }
  11094. function adjustSlidingStart(sliding, details) {
  11095. // Update segments
  11096. const fragments = details.fragments;
  11097. for (let i = 0, len = fragments.length; i < len; i++) {
  11098. adjustFragmentStart(fragments[i], sliding);
  11099. }
  11100. // Update LL-HLS parts at the end of the playlist
  11101. if (details.fragmentHint) {
  11102. adjustFragmentStart(details.fragmentHint, sliding);
  11103. }
  11104. details.alignedSliding = true;
  11105. }
  11106. /**
  11107. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  11108. * contiguous stream with the last fragments.
  11109. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  11110. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  11111. * and an extra download.
  11112. * @param lastFrag
  11113. * @param lastLevel
  11114. * @param details
  11115. */
  11116. function alignStream(lastFrag, switchDetails, details) {
  11117. if (!switchDetails) {
  11118. return;
  11119. }
  11120. alignDiscontinuities(lastFrag, details, switchDetails);
  11121. if (!details.alignedSliding && switchDetails) {
  11122. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  11123. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  11124. // discontinuity sequence.
  11125. alignMediaPlaylistByPDT(details, switchDetails);
  11126. }
  11127. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  11128. // Try to align on sn so that we pick a better start fragment.
  11129. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  11130. // and adjustSliding only adjusts fragments after skippedSegments.
  11131. adjustSliding(switchDetails, details);
  11132. }
  11133. }
  11134. /**
  11135. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  11136. * discontinuity sequence.
  11137. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  11138. * @param lastLevel - The details of the last loaded level
  11139. * @param details - The details of the new level
  11140. */
  11141. function alignDiscontinuities(lastFrag, details, switchDetails) {
  11142. if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {
  11143. const referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details);
  11144. if (referenceFrag && isFiniteNumber(referenceFrag.start)) {
  11145. logger.log(`Adjusting PTS using last level due to CC increase within current level ${details.url}`);
  11146. adjustSlidingStart(referenceFrag.start, details);
  11147. }
  11148. }
  11149. }
  11150. /**
  11151. * Ensures appropriate time-alignment between renditions based on PDT.
  11152. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  11153. * for the last discontinuity sequence number shared by both playlists when present,
  11154. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  11155. * times/timelines of `details` accordingly.
  11156. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  11157. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  11158. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  11159. * be consistent across playlists, per the HLS spec.
  11160. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  11161. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  11162. */
  11163. function alignMediaPlaylistByPDT(details, refDetails) {
  11164. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  11165. return;
  11166. }
  11167. const fragments = details.fragments;
  11168. const refFragments = refDetails.fragments;
  11169. if (!fragments.length || !refFragments.length) {
  11170. return;
  11171. }
  11172. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  11173. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  11174. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  11175. let refFrag;
  11176. let frag;
  11177. const targetCC = Math.min(refDetails.endCC, details.endCC);
  11178. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  11179. refFrag = findFirstFragWithCC(refFragments, targetCC);
  11180. frag = findFirstFragWithCC(fragments, targetCC);
  11181. }
  11182. if (!refFrag || !frag) {
  11183. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  11184. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  11185. }
  11186. const refPDT = refFrag.programDateTime;
  11187. const targetPDT = frag.programDateTime;
  11188. if (!refPDT || !targetPDT) {
  11189. return;
  11190. }
  11191. const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  11192. adjustSlidingStart(delta, details);
  11193. }
  11194. class AESCrypto {
  11195. constructor(subtle, iv) {
  11196. this.subtle = void 0;
  11197. this.aesIV = void 0;
  11198. this.subtle = subtle;
  11199. this.aesIV = iv;
  11200. }
  11201. decrypt(data, key) {
  11202. return this.subtle.decrypt({
  11203. name: 'AES-CBC',
  11204. iv: this.aesIV
  11205. }, key, data);
  11206. }
  11207. }
  11208. class FastAESKey {
  11209. constructor(subtle, key) {
  11210. this.subtle = void 0;
  11211. this.key = void 0;
  11212. this.subtle = subtle;
  11213. this.key = key;
  11214. }
  11215. expandKey() {
  11216. return this.subtle.importKey('raw', this.key, {
  11217. name: 'AES-CBC'
  11218. }, false, ['encrypt', 'decrypt']);
  11219. }
  11220. }
  11221. // PKCS7
  11222. function removePadding(array) {
  11223. const outputBytes = array.byteLength;
  11224. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  11225. if (paddingBytes) {
  11226. return sliceUint8(array, 0, outputBytes - paddingBytes);
  11227. }
  11228. return array;
  11229. }
  11230. class AESDecryptor {
  11231. constructor() {
  11232. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  11233. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11234. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11235. this.sBox = new Uint32Array(256);
  11236. this.invSBox = new Uint32Array(256);
  11237. this.key = new Uint32Array(0);
  11238. this.ksRows = 0;
  11239. this.keySize = 0;
  11240. this.keySchedule = void 0;
  11241. this.invKeySchedule = void 0;
  11242. this.initTable();
  11243. }
  11244. // Using view.getUint32() also swaps the byte order.
  11245. uint8ArrayToUint32Array_(arrayBuffer) {
  11246. const view = new DataView(arrayBuffer);
  11247. const newArray = new Uint32Array(4);
  11248. for (let i = 0; i < 4; i++) {
  11249. newArray[i] = view.getUint32(i * 4);
  11250. }
  11251. return newArray;
  11252. }
  11253. initTable() {
  11254. const sBox = this.sBox;
  11255. const invSBox = this.invSBox;
  11256. const subMix = this.subMix;
  11257. const subMix0 = subMix[0];
  11258. const subMix1 = subMix[1];
  11259. const subMix2 = subMix[2];
  11260. const subMix3 = subMix[3];
  11261. const invSubMix = this.invSubMix;
  11262. const invSubMix0 = invSubMix[0];
  11263. const invSubMix1 = invSubMix[1];
  11264. const invSubMix2 = invSubMix[2];
  11265. const invSubMix3 = invSubMix[3];
  11266. const d = new Uint32Array(256);
  11267. let x = 0;
  11268. let xi = 0;
  11269. let i = 0;
  11270. for (i = 0; i < 256; i++) {
  11271. if (i < 128) {
  11272. d[i] = i << 1;
  11273. } else {
  11274. d[i] = i << 1 ^ 0x11b;
  11275. }
  11276. }
  11277. for (i = 0; i < 256; i++) {
  11278. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  11279. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  11280. sBox[x] = sx;
  11281. invSBox[sx] = x;
  11282. // Compute multiplication
  11283. const x2 = d[x];
  11284. const x4 = d[x2];
  11285. const x8 = d[x4];
  11286. // Compute sub/invSub bytes, mix columns tables
  11287. let t = d[sx] * 0x101 ^ sx * 0x1010100;
  11288. subMix0[x] = t << 24 | t >>> 8;
  11289. subMix1[x] = t << 16 | t >>> 16;
  11290. subMix2[x] = t << 8 | t >>> 24;
  11291. subMix3[x] = t;
  11292. // Compute inv sub bytes, inv mix columns tables
  11293. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  11294. invSubMix0[sx] = t << 24 | t >>> 8;
  11295. invSubMix1[sx] = t << 16 | t >>> 16;
  11296. invSubMix2[sx] = t << 8 | t >>> 24;
  11297. invSubMix3[sx] = t;
  11298. // Compute next counter
  11299. if (!x) {
  11300. x = xi = 1;
  11301. } else {
  11302. x = x2 ^ d[d[d[x8 ^ x2]]];
  11303. xi ^= d[d[xi]];
  11304. }
  11305. }
  11306. }
  11307. expandKey(keyBuffer) {
  11308. // convert keyBuffer to Uint32Array
  11309. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  11310. let sameKey = true;
  11311. let offset = 0;
  11312. while (offset < key.length && sameKey) {
  11313. sameKey = key[offset] === this.key[offset];
  11314. offset++;
  11315. }
  11316. if (sameKey) {
  11317. return;
  11318. }
  11319. this.key = key;
  11320. const keySize = this.keySize = key.length;
  11321. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  11322. throw new Error('Invalid aes key size=' + keySize);
  11323. }
  11324. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  11325. let ksRow;
  11326. let invKsRow;
  11327. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  11328. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  11329. const sbox = this.sBox;
  11330. const rcon = this.rcon;
  11331. const invSubMix = this.invSubMix;
  11332. const invSubMix0 = invSubMix[0];
  11333. const invSubMix1 = invSubMix[1];
  11334. const invSubMix2 = invSubMix[2];
  11335. const invSubMix3 = invSubMix[3];
  11336. let prev;
  11337. let t;
  11338. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  11339. if (ksRow < keySize) {
  11340. prev = keySchedule[ksRow] = key[ksRow];
  11341. continue;
  11342. }
  11343. t = prev;
  11344. if (ksRow % keySize === 0) {
  11345. // Rot word
  11346. t = t << 8 | t >>> 24;
  11347. // Sub word
  11348. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11349. // Mix Rcon
  11350. t ^= rcon[ksRow / keySize | 0] << 24;
  11351. } else if (keySize > 6 && ksRow % keySize === 4) {
  11352. // Sub word
  11353. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11354. }
  11355. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  11356. }
  11357. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  11358. ksRow = ksRows - invKsRow;
  11359. if (invKsRow & 3) {
  11360. t = keySchedule[ksRow];
  11361. } else {
  11362. t = keySchedule[ksRow - 4];
  11363. }
  11364. if (invKsRow < 4 || ksRow <= 4) {
  11365. invKeySchedule[invKsRow] = t;
  11366. } else {
  11367. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  11368. }
  11369. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  11370. }
  11371. }
  11372. // Adding this as a method greatly improves performance.
  11373. networkToHostOrderSwap(word) {
  11374. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  11375. }
  11376. decrypt(inputArrayBuffer, offset, aesIV) {
  11377. const nRounds = this.keySize + 6;
  11378. const invKeySchedule = this.invKeySchedule;
  11379. const invSBOX = this.invSBox;
  11380. const invSubMix = this.invSubMix;
  11381. const invSubMix0 = invSubMix[0];
  11382. const invSubMix1 = invSubMix[1];
  11383. const invSubMix2 = invSubMix[2];
  11384. const invSubMix3 = invSubMix[3];
  11385. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  11386. let initVector0 = initVector[0];
  11387. let initVector1 = initVector[1];
  11388. let initVector2 = initVector[2];
  11389. let initVector3 = initVector[3];
  11390. const inputInt32 = new Int32Array(inputArrayBuffer);
  11391. const outputInt32 = new Int32Array(inputInt32.length);
  11392. let t0, t1, t2, t3;
  11393. let s0, s1, s2, s3;
  11394. let inputWords0, inputWords1, inputWords2, inputWords3;
  11395. let ksRow, i;
  11396. const swapWord = this.networkToHostOrderSwap;
  11397. while (offset < inputInt32.length) {
  11398. inputWords0 = swapWord(inputInt32[offset]);
  11399. inputWords1 = swapWord(inputInt32[offset + 1]);
  11400. inputWords2 = swapWord(inputInt32[offset + 2]);
  11401. inputWords3 = swapWord(inputInt32[offset + 3]);
  11402. s0 = inputWords0 ^ invKeySchedule[0];
  11403. s1 = inputWords3 ^ invKeySchedule[1];
  11404. s2 = inputWords2 ^ invKeySchedule[2];
  11405. s3 = inputWords1 ^ invKeySchedule[3];
  11406. ksRow = 4;
  11407. // Iterate through the rounds of decryption
  11408. for (i = 1; i < nRounds; i++) {
  11409. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  11410. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11411. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11412. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11413. // Update state
  11414. s0 = t0;
  11415. s1 = t1;
  11416. s2 = t2;
  11417. s3 = t3;
  11418. ksRow = ksRow + 4;
  11419. }
  11420. // Shift rows, sub bytes, add round key
  11421. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  11422. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11423. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11424. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11425. // Write
  11426. outputInt32[offset] = swapWord(t0 ^ initVector0);
  11427. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  11428. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  11429. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  11430. // reset initVector to last 4 unsigned int
  11431. initVector0 = inputWords0;
  11432. initVector1 = inputWords1;
  11433. initVector2 = inputWords2;
  11434. initVector3 = inputWords3;
  11435. offset = offset + 4;
  11436. }
  11437. return outputInt32.buffer;
  11438. }
  11439. }
  11440. const CHUNK_SIZE = 16; // 16 bytes, 128 bits
  11441. class Decrypter {
  11442. constructor(config, {
  11443. removePKCS7Padding = true
  11444. } = {}) {
  11445. this.logEnabled = true;
  11446. this.removePKCS7Padding = void 0;
  11447. this.subtle = null;
  11448. this.softwareDecrypter = null;
  11449. this.key = null;
  11450. this.fastAesKey = null;
  11451. this.remainderData = null;
  11452. this.currentIV = null;
  11453. this.currentResult = null;
  11454. this.useSoftware = void 0;
  11455. this.useSoftware = config.enableSoftwareAES;
  11456. this.removePKCS7Padding = removePKCS7Padding;
  11457. // built in decryptor expects PKCS7 padding
  11458. if (removePKCS7Padding) {
  11459. try {
  11460. const browserCrypto = self.crypto;
  11461. if (browserCrypto) {
  11462. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  11463. }
  11464. } catch (e) {
  11465. /* no-op */
  11466. }
  11467. }
  11468. this.useSoftware = !this.subtle;
  11469. }
  11470. destroy() {
  11471. this.subtle = null;
  11472. this.softwareDecrypter = null;
  11473. this.key = null;
  11474. this.fastAesKey = null;
  11475. this.remainderData = null;
  11476. this.currentIV = null;
  11477. this.currentResult = null;
  11478. }
  11479. isSync() {
  11480. return this.useSoftware;
  11481. }
  11482. flush() {
  11483. const {
  11484. currentResult,
  11485. remainderData
  11486. } = this;
  11487. if (!currentResult || remainderData) {
  11488. this.reset();
  11489. return null;
  11490. }
  11491. const data = new Uint8Array(currentResult);
  11492. this.reset();
  11493. if (this.removePKCS7Padding) {
  11494. return removePadding(data);
  11495. }
  11496. return data;
  11497. }
  11498. reset() {
  11499. this.currentResult = null;
  11500. this.currentIV = null;
  11501. this.remainderData = null;
  11502. if (this.softwareDecrypter) {
  11503. this.softwareDecrypter = null;
  11504. }
  11505. }
  11506. decrypt(data, key, iv) {
  11507. if (this.useSoftware) {
  11508. return new Promise((resolve, reject) => {
  11509. this.softwareDecrypt(new Uint8Array(data), key, iv);
  11510. const decryptResult = this.flush();
  11511. if (decryptResult) {
  11512. resolve(decryptResult.buffer);
  11513. } else {
  11514. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  11515. }
  11516. });
  11517. }
  11518. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  11519. }
  11520. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  11521. // data is handled in the flush() call
  11522. softwareDecrypt(data, key, iv) {
  11523. const {
  11524. currentIV,
  11525. currentResult,
  11526. remainderData
  11527. } = this;
  11528. this.logOnce('JS AES decrypt');
  11529. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  11530. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  11531. // the end on flush(), but by that time we have already received all bytes for the segment.
  11532. // Progressive decryption does not work with WebCrypto
  11533. if (remainderData) {
  11534. data = appendUint8Array(remainderData, data);
  11535. this.remainderData = null;
  11536. }
  11537. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  11538. const currentChunk = this.getValidChunk(data);
  11539. if (!currentChunk.length) {
  11540. return null;
  11541. }
  11542. if (currentIV) {
  11543. iv = currentIV;
  11544. }
  11545. let softwareDecrypter = this.softwareDecrypter;
  11546. if (!softwareDecrypter) {
  11547. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  11548. }
  11549. softwareDecrypter.expandKey(key);
  11550. const result = currentResult;
  11551. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  11552. this.currentIV = sliceUint8(currentChunk, -16).buffer;
  11553. if (!result) {
  11554. return null;
  11555. }
  11556. return result;
  11557. }
  11558. webCryptoDecrypt(data, key, iv) {
  11559. if (this.key !== key || !this.fastAesKey) {
  11560. if (!this.subtle) {
  11561. return Promise.resolve(this.onWebCryptoError(data, key, iv));
  11562. }
  11563. this.key = key;
  11564. this.fastAesKey = new FastAESKey(this.subtle, key);
  11565. }
  11566. return this.fastAesKey.expandKey().then(aesKey => {
  11567. // decrypt using web crypto
  11568. if (!this.subtle) {
  11569. return Promise.reject(new Error('web crypto not initialized'));
  11570. }
  11571. this.logOnce('WebCrypto AES decrypt');
  11572. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv));
  11573. return crypto.decrypt(data.buffer, aesKey);
  11574. }).catch(err => {
  11575. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  11576. return this.onWebCryptoError(data, key, iv);
  11577. });
  11578. }
  11579. onWebCryptoError(data, key, iv) {
  11580. this.useSoftware = true;
  11581. this.logEnabled = true;
  11582. this.softwareDecrypt(data, key, iv);
  11583. const decryptResult = this.flush();
  11584. if (decryptResult) {
  11585. return decryptResult.buffer;
  11586. }
  11587. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  11588. }
  11589. getValidChunk(data) {
  11590. let currentChunk = data;
  11591. const splitPoint = data.length - data.length % CHUNK_SIZE;
  11592. if (splitPoint !== data.length) {
  11593. currentChunk = sliceUint8(data, 0, splitPoint);
  11594. this.remainderData = sliceUint8(data, splitPoint);
  11595. }
  11596. return currentChunk;
  11597. }
  11598. logOnce(msg) {
  11599. if (!this.logEnabled) {
  11600. return;
  11601. }
  11602. logger.log(`[decrypter]: ${msg}`);
  11603. this.logEnabled = false;
  11604. }
  11605. }
  11606. /**
  11607. * TimeRanges to string helper
  11608. */
  11609. const TimeRanges = {
  11610. toString: function (r) {
  11611. let log = '';
  11612. const len = r.length;
  11613. for (let i = 0; i < len; i++) {
  11614. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  11615. }
  11616. return log;
  11617. }
  11618. };
  11619. const State = {
  11620. STOPPED: 'STOPPED',
  11621. IDLE: 'IDLE',
  11622. KEY_LOADING: 'KEY_LOADING',
  11623. FRAG_LOADING: 'FRAG_LOADING',
  11624. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  11625. WAITING_TRACK: 'WAITING_TRACK',
  11626. PARSING: 'PARSING',
  11627. PARSED: 'PARSED',
  11628. ENDED: 'ENDED',
  11629. ERROR: 'ERROR',
  11630. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  11631. WAITING_LEVEL: 'WAITING_LEVEL'
  11632. };
  11633. class BaseStreamController extends TaskLoop {
  11634. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  11635. super();
  11636. this.hls = void 0;
  11637. this.fragPrevious = null;
  11638. this.fragCurrent = null;
  11639. this.fragmentTracker = void 0;
  11640. this.transmuxer = null;
  11641. this._state = State.STOPPED;
  11642. this.playlistType = void 0;
  11643. this.media = null;
  11644. this.mediaBuffer = null;
  11645. this.config = void 0;
  11646. this.bitrateTest = false;
  11647. this.lastCurrentTime = 0;
  11648. this.nextLoadPosition = 0;
  11649. this.startPosition = 0;
  11650. this.startTimeOffset = null;
  11651. this.loadedmetadata = false;
  11652. this.retryDate = 0;
  11653. this.levels = null;
  11654. this.fragmentLoader = void 0;
  11655. this.keyLoader = void 0;
  11656. this.levelLastLoaded = null;
  11657. this.startFragRequested = false;
  11658. this.decrypter = void 0;
  11659. this.initPTS = [];
  11660. this.onvseeking = null;
  11661. this.onvended = null;
  11662. this.logPrefix = '';
  11663. this.log = void 0;
  11664. this.warn = void 0;
  11665. this.playlistType = playlistType;
  11666. this.logPrefix = logPrefix;
  11667. this.log = logger.log.bind(logger, `${logPrefix}:`);
  11668. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  11669. this.hls = hls;
  11670. this.fragmentLoader = new FragmentLoader(hls.config);
  11671. this.keyLoader = keyLoader;
  11672. this.fragmentTracker = fragmentTracker;
  11673. this.config = hls.config;
  11674. this.decrypter = new Decrypter(hls.config);
  11675. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  11676. }
  11677. doTick() {
  11678. this.onTickEnd();
  11679. }
  11680. onTickEnd() {}
  11681. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  11682. startLoad(startPosition) {}
  11683. stopLoad() {
  11684. this.fragmentLoader.abort();
  11685. this.keyLoader.abort(this.playlistType);
  11686. const frag = this.fragCurrent;
  11687. if (frag != null && frag.loader) {
  11688. frag.abortRequests();
  11689. this.fragmentTracker.removeFragment(frag);
  11690. }
  11691. this.resetTransmuxer();
  11692. this.fragCurrent = null;
  11693. this.fragPrevious = null;
  11694. this.clearInterval();
  11695. this.clearNextTick();
  11696. this.state = State.STOPPED;
  11697. }
  11698. _streamEnded(bufferInfo, levelDetails) {
  11699. // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,
  11700. // of nothing loading/loaded return false
  11701. if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) {
  11702. return false;
  11703. }
  11704. const partList = levelDetails.partList;
  11705. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  11706. // check instead if the last part is buffered.
  11707. if (partList != null && partList.length) {
  11708. const lastPart = partList[partList.length - 1];
  11709. // Checking the midpoint of the part for potential margin of error and related issues.
  11710. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  11711. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  11712. // part mismatches for independent audio and video playlists/segments.
  11713. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  11714. return lastPartBuffered;
  11715. }
  11716. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  11717. return this.fragmentTracker.isEndListAppended(playlistType);
  11718. }
  11719. getLevelDetails() {
  11720. if (this.levels && this.levelLastLoaded !== null) {
  11721. var _this$levelLastLoaded;
  11722. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  11723. }
  11724. }
  11725. onMediaAttached(event, data) {
  11726. const media = this.media = this.mediaBuffer = data.media;
  11727. this.onvseeking = this.onMediaSeeking.bind(this);
  11728. this.onvended = this.onMediaEnded.bind(this);
  11729. media.addEventListener('seeking', this.onvseeking);
  11730. media.addEventListener('ended', this.onvended);
  11731. const config = this.config;
  11732. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  11733. this.startLoad(config.startPosition);
  11734. }
  11735. }
  11736. onMediaDetaching() {
  11737. const media = this.media;
  11738. if (media != null && media.ended) {
  11739. this.log('MSE detaching and video ended, reset startPosition');
  11740. this.startPosition = this.lastCurrentTime = 0;
  11741. }
  11742. // remove video listeners
  11743. if (media && this.onvseeking && this.onvended) {
  11744. media.removeEventListener('seeking', this.onvseeking);
  11745. media.removeEventListener('ended', this.onvended);
  11746. this.onvseeking = this.onvended = null;
  11747. }
  11748. if (this.keyLoader) {
  11749. this.keyLoader.detach();
  11750. }
  11751. this.media = this.mediaBuffer = null;
  11752. this.loadedmetadata = false;
  11753. this.fragmentTracker.removeAllFragments();
  11754. this.stopLoad();
  11755. }
  11756. onMediaSeeking() {
  11757. const {
  11758. config,
  11759. fragCurrent,
  11760. media,
  11761. mediaBuffer,
  11762. state
  11763. } = this;
  11764. const currentTime = media ? media.currentTime : 0;
  11765. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  11766. this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`);
  11767. if (this.state === State.ENDED) {
  11768. this.resetLoadingState();
  11769. } else if (fragCurrent) {
  11770. // Seeking while frag load is in progress
  11771. const tolerance = config.maxFragLookUpTolerance;
  11772. const fragStartOffset = fragCurrent.start - tolerance;
  11773. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  11774. // if seeking out of buffered range or into new one
  11775. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  11776. const pastFragment = currentTime > fragEndOffset;
  11777. // if the seek position is outside the current fragment range
  11778. if (currentTime < fragStartOffset || pastFragment) {
  11779. if (pastFragment && fragCurrent.loader) {
  11780. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  11781. fragCurrent.abortRequests();
  11782. this.resetLoadingState();
  11783. }
  11784. this.fragPrevious = null;
  11785. }
  11786. }
  11787. }
  11788. if (media) {
  11789. // Remove gap fragments
  11790. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  11791. this.lastCurrentTime = currentTime;
  11792. }
  11793. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  11794. if (!this.loadedmetadata && !bufferInfo.len) {
  11795. this.nextLoadPosition = this.startPosition = currentTime;
  11796. }
  11797. // Async tick to speed up processing
  11798. this.tickImmediate();
  11799. }
  11800. onMediaEnded() {
  11801. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  11802. this.startPosition = this.lastCurrentTime = 0;
  11803. }
  11804. onManifestLoaded(event, data) {
  11805. this.startTimeOffset = data.startTimeOffset;
  11806. this.initPTS = [];
  11807. }
  11808. onHandlerDestroying() {
  11809. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  11810. this.stopLoad();
  11811. super.onHandlerDestroying();
  11812. // @ts-ignore
  11813. this.hls = null;
  11814. }
  11815. onHandlerDestroyed() {
  11816. this.state = State.STOPPED;
  11817. if (this.fragmentLoader) {
  11818. this.fragmentLoader.destroy();
  11819. }
  11820. if (this.keyLoader) {
  11821. this.keyLoader.destroy();
  11822. }
  11823. if (this.decrypter) {
  11824. this.decrypter.destroy();
  11825. }
  11826. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  11827. super.onHandlerDestroyed();
  11828. }
  11829. loadFragment(frag, level, targetBufferTime) {
  11830. this._loadFragForPlayback(frag, level, targetBufferTime);
  11831. }
  11832. _loadFragForPlayback(frag, level, targetBufferTime) {
  11833. const progressCallback = data => {
  11834. if (this.fragContextChanged(frag)) {
  11835. this.warn(`Fragment ${frag.sn}${data.part ? ' p: ' + data.part.index : ''} of level ${frag.level} was dropped during download.`);
  11836. this.fragmentTracker.removeFragment(frag);
  11837. return;
  11838. }
  11839. frag.stats.chunkCount++;
  11840. this._handleFragmentLoadProgress(data);
  11841. };
  11842. this._doFragLoad(frag, level, targetBufferTime, progressCallback).then(data => {
  11843. if (!data) {
  11844. // if we're here we probably needed to backtrack or are waiting for more parts
  11845. return;
  11846. }
  11847. const state = this.state;
  11848. if (this.fragContextChanged(frag)) {
  11849. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  11850. this.fragmentTracker.removeFragment(frag);
  11851. this.state = State.IDLE;
  11852. }
  11853. return;
  11854. }
  11855. if ('payload' in data) {
  11856. this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);
  11857. this.hls.trigger(Events.FRAG_LOADED, data);
  11858. }
  11859. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  11860. this._handleFragmentLoadComplete(data);
  11861. }).catch(reason => {
  11862. if (this.state === State.STOPPED || this.state === State.ERROR) {
  11863. return;
  11864. }
  11865. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  11866. this.resetFragmentLoading(frag);
  11867. });
  11868. }
  11869. clearTrackerIfNeeded(frag) {
  11870. var _this$mediaBuffer;
  11871. const {
  11872. fragmentTracker
  11873. } = this;
  11874. const fragState = fragmentTracker.getState(frag);
  11875. if (fragState === FragmentState.APPENDING) {
  11876. // Lower the max buffer length and try again
  11877. const playlistType = frag.type;
  11878. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  11879. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  11880. // If backtracking, always remove from the tracker without reducing max buffer length
  11881. const backtrackFragment = this.backtrackFragment;
  11882. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  11883. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  11884. fragmentTracker.removeFragment(frag);
  11885. }
  11886. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  11887. // Stop gap for bad tracker / buffer flush behavior
  11888. fragmentTracker.removeAllFragments();
  11889. } else if (fragmentTracker.hasParts(frag.type)) {
  11890. // In low latency mode, remove fragments for which only some parts were buffered
  11891. fragmentTracker.detectPartialFragments({
  11892. frag,
  11893. part: null,
  11894. stats: frag.stats,
  11895. id: frag.type
  11896. });
  11897. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  11898. fragmentTracker.removeFragment(frag);
  11899. }
  11900. }
  11901. }
  11902. checkLiveUpdate(details) {
  11903. if (details.updated && !details.live) {
  11904. // Live stream ended, update fragment tracker
  11905. const lastFragment = details.fragments[details.fragments.length - 1];
  11906. this.fragmentTracker.detectPartialFragments({
  11907. frag: lastFragment,
  11908. part: null,
  11909. stats: lastFragment.stats,
  11910. id: lastFragment.type
  11911. });
  11912. }
  11913. if (!details.fragments[0]) {
  11914. details.deltaUpdateFailed = true;
  11915. }
  11916. }
  11917. flushMainBuffer(startOffset, endOffset, type = null) {
  11918. if (!(startOffset - endOffset)) {
  11919. return;
  11920. }
  11921. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  11922. // passing a null type flushes both buffers
  11923. const flushScope = {
  11924. startOffset,
  11925. endOffset,
  11926. type
  11927. };
  11928. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  11929. }
  11930. _loadInitSegment(frag, level) {
  11931. this._doFragLoad(frag, level).then(data => {
  11932. if (!data || this.fragContextChanged(frag) || !this.levels) {
  11933. throw new Error('init load aborted');
  11934. }
  11935. return data;
  11936. }).then(data => {
  11937. const {
  11938. hls
  11939. } = this;
  11940. const {
  11941. payload
  11942. } = data;
  11943. const decryptData = frag.decryptdata;
  11944. // check to see if the payload needs to be decrypted
  11945. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  11946. const startTime = self.performance.now();
  11947. // decrypt init segment data
  11948. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(err => {
  11949. hls.trigger(Events.ERROR, {
  11950. type: ErrorTypes.MEDIA_ERROR,
  11951. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  11952. fatal: false,
  11953. error: err,
  11954. reason: err.message,
  11955. frag
  11956. });
  11957. throw err;
  11958. }).then(decryptedData => {
  11959. const endTime = self.performance.now();
  11960. hls.trigger(Events.FRAG_DECRYPTED, {
  11961. frag,
  11962. payload: decryptedData,
  11963. stats: {
  11964. tstart: startTime,
  11965. tdecrypt: endTime
  11966. }
  11967. });
  11968. data.payload = decryptedData;
  11969. return this.completeInitSegmentLoad(data);
  11970. });
  11971. }
  11972. return this.completeInitSegmentLoad(data);
  11973. }).catch(reason => {
  11974. if (this.state === State.STOPPED || this.state === State.ERROR) {
  11975. return;
  11976. }
  11977. this.warn(reason);
  11978. this.resetFragmentLoading(frag);
  11979. });
  11980. }
  11981. completeInitSegmentLoad(data) {
  11982. const {
  11983. levels
  11984. } = this;
  11985. if (!levels) {
  11986. throw new Error('init load aborted, missing levels');
  11987. }
  11988. const stats = data.frag.stats;
  11989. this.state = State.IDLE;
  11990. data.frag.data = new Uint8Array(data.payload);
  11991. stats.parsing.start = stats.buffering.start = self.performance.now();
  11992. stats.parsing.end = stats.buffering.end = self.performance.now();
  11993. this.tick();
  11994. }
  11995. fragContextChanged(frag) {
  11996. const {
  11997. fragCurrent
  11998. } = this;
  11999. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  12000. }
  12001. fragBufferedComplete(frag, part) {
  12002. var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious;
  12003. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12004. this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track'} ${frag.level} (frag:[${((_frag$startPTS = frag.startPTS) != null ? _frag$startPTS : NaN).toFixed(3)}-${((_frag$endPTS = frag.endPTS) != null ? _frag$endPTS : NaN).toFixed(3)}] > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)'})`);
  12005. if (frag.sn !== 'initSegment') {
  12006. var _this$levels;
  12007. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  12008. const el = frag.elementaryStreams;
  12009. if (!Object.keys(el).some(type => !!el[type])) {
  12010. // empty segment
  12011. this.state = State.IDLE;
  12012. return;
  12013. }
  12014. }
  12015. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  12016. if (level != null && level.fragmentError) {
  12017. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  12018. level.fragmentError = 0;
  12019. }
  12020. }
  12021. this.state = State.IDLE;
  12022. if (!media) {
  12023. return;
  12024. }
  12025. if (!this.loadedmetadata && frag.type == PlaylistLevelType.MAIN && media.buffered.length && ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.sn) === ((_this$fragPrevious = this.fragPrevious) == null ? void 0 : _this$fragPrevious.sn)) {
  12026. this.loadedmetadata = true;
  12027. this.seekToStartPos();
  12028. }
  12029. this.tick();
  12030. }
  12031. seekToStartPos() {}
  12032. _handleFragmentLoadComplete(fragLoadedEndData) {
  12033. const {
  12034. transmuxer
  12035. } = this;
  12036. if (!transmuxer) {
  12037. return;
  12038. }
  12039. const {
  12040. frag,
  12041. part,
  12042. partsLoaded
  12043. } = fragLoadedEndData;
  12044. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  12045. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);
  12046. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  12047. transmuxer.flush(chunkMeta);
  12048. }
  12049. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  12050. _handleFragmentLoadProgress(frag) {}
  12051. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  12052. var _frag$decryptdata;
  12053. const details = level == null ? void 0 : level.details;
  12054. if (!this.levels || !details) {
  12055. throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);
  12056. }
  12057. let keyLoadingPromise = null;
  12058. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  12059. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${frag.level}`);
  12060. this.state = State.KEY_LOADING;
  12061. this.fragCurrent = frag;
  12062. keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {
  12063. if (!this.fragContextChanged(keyLoadedData.frag)) {
  12064. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  12065. if (this.state === State.KEY_LOADING) {
  12066. this.state = State.IDLE;
  12067. }
  12068. return keyLoadedData;
  12069. }
  12070. });
  12071. this.hls.trigger(Events.KEY_LOADING, {
  12072. frag
  12073. });
  12074. if (this.fragCurrent === null) {
  12075. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  12076. }
  12077. } else if (!frag.encrypted && details.encryptedFragments.length) {
  12078. this.keyLoader.loadClear(frag, details.encryptedFragments);
  12079. }
  12080. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  12081. if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {
  12082. const partList = details.partList;
  12083. if (partList && progressCallback) {
  12084. if (targetBufferTime > frag.end && details.fragmentHint) {
  12085. frag = details.fragmentHint;
  12086. }
  12087. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  12088. if (partIndex > -1) {
  12089. const part = partList[partIndex];
  12090. this.log(`Loading part sn: ${frag.sn} p: ${part.index} cc: ${frag.cc} of playlist [${details.startSN}-${details.endSN}] parts [0-${partIndex}-${partList.length - 1}] ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  12091. this.nextLoadPosition = part.start + part.duration;
  12092. this.state = State.FRAG_LOADING;
  12093. let _result;
  12094. if (keyLoadingPromise) {
  12095. _result = keyLoadingPromise.then(keyLoadedData => {
  12096. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  12097. return null;
  12098. }
  12099. return this.doFragPartsLoad(frag, part, level, progressCallback);
  12100. }).catch(error => this.handleFragLoadError(error));
  12101. } else {
  12102. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));
  12103. }
  12104. this.hls.trigger(Events.FRAG_LOADING, {
  12105. frag,
  12106. part,
  12107. targetBufferTime
  12108. });
  12109. if (this.fragCurrent === null) {
  12110. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  12111. }
  12112. return _result;
  12113. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  12114. // Fragment hint has no parts
  12115. return Promise.resolve(null);
  12116. }
  12117. }
  12118. }
  12119. this.log(`Loading fragment ${frag.sn} cc: ${frag.cc} ${details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''}${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  12120. // Don't update nextLoadPosition for fragments which are not buffered
  12121. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  12122. this.nextLoadPosition = frag.start + frag.duration;
  12123. }
  12124. this.state = State.FRAG_LOADING;
  12125. // Load key before streaming fragment data
  12126. const dataOnProgress = this.config.progressive;
  12127. let result;
  12128. if (dataOnProgress && keyLoadingPromise) {
  12129. result = keyLoadingPromise.then(keyLoadedData => {
  12130. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  12131. return null;
  12132. }
  12133. return this.fragmentLoader.load(frag, progressCallback);
  12134. }).catch(error => this.handleFragLoadError(error));
  12135. } else {
  12136. // load unencrypted fragment data with progress event,
  12137. // or handle fragment result after key and fragment are finished loading
  12138. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {
  12139. if (!dataOnProgress && fragLoadedData && progressCallback) {
  12140. progressCallback(fragLoadedData);
  12141. }
  12142. return fragLoadedData;
  12143. }).catch(error => this.handleFragLoadError(error));
  12144. }
  12145. this.hls.trigger(Events.FRAG_LOADING, {
  12146. frag,
  12147. targetBufferTime
  12148. });
  12149. if (this.fragCurrent === null) {
  12150. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  12151. }
  12152. return result;
  12153. }
  12154. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  12155. return new Promise((resolve, reject) => {
  12156. var _level$details;
  12157. const partsLoaded = [];
  12158. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  12159. const loadPart = part => {
  12160. this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {
  12161. partsLoaded[part.index] = partLoadedData;
  12162. const loadedPart = partLoadedData.part;
  12163. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  12164. const nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  12165. if (nextPart) {
  12166. loadPart(nextPart);
  12167. } else {
  12168. return resolve({
  12169. frag,
  12170. part: loadedPart,
  12171. partsLoaded
  12172. });
  12173. }
  12174. }).catch(reject);
  12175. };
  12176. loadPart(fromPart);
  12177. });
  12178. }
  12179. handleFragLoadError(error) {
  12180. if ('data' in error) {
  12181. const data = error.data;
  12182. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  12183. this.handleFragLoadAborted(data.frag, data.part);
  12184. } else {
  12185. this.hls.trigger(Events.ERROR, data);
  12186. }
  12187. } else {
  12188. this.hls.trigger(Events.ERROR, {
  12189. type: ErrorTypes.OTHER_ERROR,
  12190. details: ErrorDetails.INTERNAL_EXCEPTION,
  12191. err: error,
  12192. error,
  12193. fatal: true
  12194. });
  12195. }
  12196. return null;
  12197. }
  12198. _handleTransmuxerFlush(chunkMeta) {
  12199. const context = this.getCurrentContext(chunkMeta);
  12200. if (!context || this.state !== State.PARSING) {
  12201. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  12202. this.state = State.IDLE;
  12203. }
  12204. return;
  12205. }
  12206. const {
  12207. frag,
  12208. part,
  12209. level
  12210. } = context;
  12211. const now = self.performance.now();
  12212. frag.stats.parsing.end = now;
  12213. if (part) {
  12214. part.stats.parsing.end = now;
  12215. }
  12216. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  12217. }
  12218. getCurrentContext(chunkMeta) {
  12219. const {
  12220. levels,
  12221. fragCurrent
  12222. } = this;
  12223. const {
  12224. level: levelIndex,
  12225. sn,
  12226. part: partIndex
  12227. } = chunkMeta;
  12228. if (!(levels != null && levels[levelIndex])) {
  12229. this.warn(`Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`);
  12230. return null;
  12231. }
  12232. const level = levels[levelIndex];
  12233. const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  12234. const frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent);
  12235. if (!frag) {
  12236. return null;
  12237. }
  12238. if (fragCurrent && fragCurrent !== frag) {
  12239. frag.stats = fragCurrent.stats;
  12240. }
  12241. return {
  12242. frag,
  12243. part,
  12244. level
  12245. };
  12246. }
  12247. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  12248. var _buffer;
  12249. if (!data || this.state !== State.PARSING) {
  12250. return;
  12251. }
  12252. const {
  12253. data1,
  12254. data2
  12255. } = data;
  12256. let buffer = data1;
  12257. if (data1 && data2) {
  12258. // Combine the moof + mdat so that we buffer with a single append
  12259. buffer = appendUint8Array(data1, data2);
  12260. }
  12261. if (!((_buffer = buffer) != null && _buffer.length)) {
  12262. return;
  12263. }
  12264. const segment = {
  12265. type: data.type,
  12266. frag,
  12267. part,
  12268. chunkMeta,
  12269. parent: frag.type,
  12270. data: buffer
  12271. };
  12272. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  12273. if (data.dropped && data.independent && !part) {
  12274. if (noBacktracking) {
  12275. return;
  12276. }
  12277. // Clear buffer so that we reload previous segments sequentially if required
  12278. this.flushBufferGap(frag);
  12279. }
  12280. }
  12281. flushBufferGap(frag) {
  12282. const media = this.media;
  12283. if (!media) {
  12284. return;
  12285. }
  12286. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  12287. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  12288. this.flushMainBuffer(0, frag.start);
  12289. return;
  12290. }
  12291. // Remove back-buffer without interrupting playback to allow back tracking
  12292. const currentTime = media.currentTime;
  12293. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  12294. const fragDuration = frag.duration;
  12295. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  12296. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  12297. if (frag.start - start > segmentFraction) {
  12298. this.flushMainBuffer(start, frag.start);
  12299. }
  12300. }
  12301. getFwdBufferInfo(bufferable, type) {
  12302. const pos = this.getLoadPosition();
  12303. if (!isFiniteNumber(pos)) {
  12304. return null;
  12305. }
  12306. return this.getFwdBufferInfoAtPos(bufferable, pos, type);
  12307. }
  12308. getFwdBufferInfoAtPos(bufferable, pos, type) {
  12309. const {
  12310. config: {
  12311. maxBufferHole
  12312. }
  12313. } = this;
  12314. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  12315. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  12316. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  12317. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  12318. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  12319. return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole));
  12320. }
  12321. }
  12322. return bufferInfo;
  12323. }
  12324. getMaxBufferLength(levelBitrate) {
  12325. const {
  12326. config
  12327. } = this;
  12328. let maxBufLen;
  12329. if (levelBitrate) {
  12330. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  12331. } else {
  12332. maxBufLen = config.maxBufferLength;
  12333. }
  12334. return Math.min(maxBufLen, config.maxMaxBufferLength);
  12335. }
  12336. reduceMaxBufferLength(threshold, fragDuration) {
  12337. const config = this.config;
  12338. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  12339. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  12340. if (reducedLength >= minLength) {
  12341. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  12342. config.maxMaxBufferLength = reducedLength;
  12343. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  12344. return true;
  12345. }
  12346. return false;
  12347. }
  12348. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  12349. const fragOrPart = this.fragmentTracker.getAppendedFrag(position, PlaylistLevelType.MAIN);
  12350. if (fragOrPart && 'fragment' in fragOrPart) {
  12351. return fragOrPart.fragment;
  12352. }
  12353. return fragOrPart;
  12354. }
  12355. getNextFragment(pos, levelDetails) {
  12356. const fragments = levelDetails.fragments;
  12357. const fragLen = fragments.length;
  12358. if (!fragLen) {
  12359. return null;
  12360. }
  12361. // find fragment index, contiguous with end of buffer position
  12362. const {
  12363. config
  12364. } = this;
  12365. const start = fragments[0].start;
  12366. let frag;
  12367. if (levelDetails.live) {
  12368. const initialLiveManifestSize = config.initialLiveManifestSize;
  12369. if (fragLen < initialLiveManifestSize) {
  12370. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  12371. return null;
  12372. }
  12373. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  12374. // In order to discover the range, we load the best matching fragment for that level and demux it.
  12375. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  12376. // we get the fragment matching that start time
  12377. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  12378. frag = this.getInitialLiveFragment(levelDetails, fragments);
  12379. this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  12380. }
  12381. } else if (pos <= start) {
  12382. // VoD playlist: if loadPosition before start of playlist, load first fragment
  12383. frag = fragments[0];
  12384. }
  12385. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  12386. if (!frag) {
  12387. const end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  12388. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  12389. }
  12390. return this.mapToInitFragWhenRequired(frag);
  12391. }
  12392. isLoopLoading(frag, targetBufferTime) {
  12393. const trackerState = this.fragmentTracker.getState(frag);
  12394. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  12395. }
  12396. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  12397. const gapStart = frag.gap;
  12398. const nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  12399. if (nextFragment === null) {
  12400. return nextFragment;
  12401. }
  12402. frag = nextFragment;
  12403. if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {
  12404. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  12405. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType);
  12406. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  12407. // Returning here might result in not finding an audio and video candiate to skip to
  12408. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${frag.sn}`);
  12409. return null;
  12410. }
  12411. }
  12412. return frag;
  12413. }
  12414. mapToInitFragWhenRequired(frag) {
  12415. // If an initSegment is present, it must be buffered first
  12416. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  12417. return frag.initSegment;
  12418. }
  12419. return frag;
  12420. }
  12421. getNextPart(partList, frag, targetBufferTime) {
  12422. let nextPart = -1;
  12423. let contiguous = false;
  12424. let independentAttrOmitted = true;
  12425. for (let i = 0, len = partList.length; i < len; i++) {
  12426. const part = partList[i];
  12427. independentAttrOmitted = independentAttrOmitted && !part.independent;
  12428. if (nextPart > -1 && targetBufferTime < part.start) {
  12429. break;
  12430. }
  12431. const loaded = part.loaded;
  12432. if (loaded) {
  12433. nextPart = -1;
  12434. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  12435. nextPart = i;
  12436. }
  12437. contiguous = loaded;
  12438. }
  12439. return nextPart;
  12440. }
  12441. loadedEndOfParts(partList, targetBufferTime) {
  12442. const lastPart = partList[partList.length - 1];
  12443. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  12444. }
  12445. /*
  12446. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  12447. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  12448. start and end times for each fragment in the playlist (after which this method will not need to be called).
  12449. */
  12450. getInitialLiveFragment(levelDetails, fragments) {
  12451. const fragPrevious = this.fragPrevious;
  12452. let frag = null;
  12453. if (fragPrevious) {
  12454. if (levelDetails.hasProgramDateTime) {
  12455. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  12456. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  12457. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  12458. }
  12459. if (!frag) {
  12460. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  12461. const targetSN = fragPrevious.sn + 1;
  12462. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  12463. const fragNext = fragments[targetSN - levelDetails.startSN];
  12464. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  12465. if (fragPrevious.cc === fragNext.cc) {
  12466. frag = fragNext;
  12467. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  12468. }
  12469. }
  12470. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  12471. // will have the wrong start times
  12472. if (!frag) {
  12473. frag = findFragWithCC(fragments, fragPrevious.cc);
  12474. if (frag) {
  12475. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  12476. }
  12477. }
  12478. }
  12479. } else {
  12480. // Find a new start fragment when fragPrevious is null
  12481. const liveStart = this.hls.liveSyncPosition;
  12482. if (liveStart !== null) {
  12483. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  12484. }
  12485. }
  12486. return frag;
  12487. }
  12488. /*
  12489. This method finds the best matching fragment given the provided position.
  12490. */
  12491. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  12492. const {
  12493. config
  12494. } = this;
  12495. let {
  12496. fragPrevious
  12497. } = this;
  12498. let {
  12499. fragments,
  12500. endSN
  12501. } = levelDetails;
  12502. const {
  12503. fragmentHint
  12504. } = levelDetails;
  12505. const {
  12506. maxFragLookUpTolerance
  12507. } = config;
  12508. const partList = levelDetails.partList;
  12509. const loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint);
  12510. if (loadingParts && fragmentHint && !this.bitrateTest) {
  12511. // Include incomplete fragment with parts at end
  12512. fragments = fragments.concat(fragmentHint);
  12513. endSN = fragmentHint.sn;
  12514. }
  12515. let frag;
  12516. if (bufferEnd < end) {
  12517. const lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;
  12518. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  12519. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  12520. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  12521. } else {
  12522. // reach end of playlist
  12523. frag = fragments[fragments.length - 1];
  12524. }
  12525. if (frag) {
  12526. const curSNIdx = frag.sn - levelDetails.startSN;
  12527. // Move fragPrevious forward to support forcing the next fragment to load
  12528. // when the buffer catches up to a previously buffered range.
  12529. const fragState = this.fragmentTracker.getState(frag);
  12530. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  12531. fragPrevious = frag;
  12532. }
  12533. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) {
  12534. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  12535. // non-uniform fragment durations
  12536. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  12537. if (sameLevel) {
  12538. const nextFrag = fragments[curSNIdx + 1];
  12539. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  12540. frag = nextFrag;
  12541. } else {
  12542. frag = null;
  12543. }
  12544. }
  12545. }
  12546. }
  12547. return frag;
  12548. }
  12549. synchronizeToLiveEdge(levelDetails) {
  12550. const {
  12551. config,
  12552. media
  12553. } = this;
  12554. if (!media) {
  12555. return;
  12556. }
  12557. const liveSyncPosition = this.hls.liveSyncPosition;
  12558. const currentTime = media.currentTime;
  12559. const start = levelDetails.fragments[0].start;
  12560. const end = levelDetails.edge;
  12561. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  12562. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  12563. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  12564. // Continue if buffer is starving or if current time is behind max latency
  12565. const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  12566. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  12567. if (!this.loadedmetadata) {
  12568. this.nextLoadPosition = liveSyncPosition;
  12569. }
  12570. // Only seek if ready and there is not a significant forward buffer available for playback
  12571. if (media.readyState) {
  12572. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  12573. media.currentTime = liveSyncPosition;
  12574. }
  12575. }
  12576. }
  12577. }
  12578. alignPlaylists(details, previousDetails, switchDetails) {
  12579. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  12580. // this could all go in level-helper mergeDetails()
  12581. const length = details.fragments.length;
  12582. if (!length) {
  12583. this.warn(`No fragments in live playlist`);
  12584. return 0;
  12585. }
  12586. const slidingStart = details.fragments[0].start;
  12587. const firstLevelLoad = !previousDetails;
  12588. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  12589. if (firstLevelLoad || !aligned && !slidingStart) {
  12590. const {
  12591. fragPrevious
  12592. } = this;
  12593. alignStream(fragPrevious, switchDetails, details);
  12594. const alignedSlidingStart = details.fragments[0].start;
  12595. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} prev-sn: ${fragPrevious ? fragPrevious.sn : 'na'} fragments: ${length}`);
  12596. return alignedSlidingStart;
  12597. }
  12598. return slidingStart;
  12599. }
  12600. waitForCdnTuneIn(details) {
  12601. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  12602. const advancePartLimit = 3;
  12603. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  12604. }
  12605. setStartPosition(details, sliding) {
  12606. // compute start position if set to -1. use it straight away if value is defined
  12607. let startPosition = this.startPosition;
  12608. if (startPosition < sliding) {
  12609. startPosition = -1;
  12610. }
  12611. if (startPosition === -1 || this.lastCurrentTime === -1) {
  12612. // Use Playlist EXT-X-START:TIME-OFFSET when set
  12613. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  12614. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  12615. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  12616. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  12617. startPosition = sliding + startTimeOffset;
  12618. if (startTimeOffset < 0) {
  12619. startPosition += details.totalduration;
  12620. }
  12621. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  12622. this.log(`Start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist, adjust startPosition to ${startPosition}`);
  12623. this.startPosition = startPosition;
  12624. } else if (details.live) {
  12625. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  12626. // not been specified via the config or an as an argument to startLoad (#3736).
  12627. startPosition = this.hls.liveSyncPosition || sliding;
  12628. } else {
  12629. this.startPosition = startPosition = 0;
  12630. }
  12631. this.lastCurrentTime = startPosition;
  12632. }
  12633. this.nextLoadPosition = startPosition;
  12634. }
  12635. getLoadPosition() {
  12636. const {
  12637. media
  12638. } = this;
  12639. // if we have not yet loaded any fragment, start loading from start position
  12640. let pos = 0;
  12641. if (this.loadedmetadata && media) {
  12642. pos = media.currentTime;
  12643. } else if (this.nextLoadPosition) {
  12644. pos = this.nextLoadPosition;
  12645. }
  12646. return pos;
  12647. }
  12648. handleFragLoadAborted(frag, part) {
  12649. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  12650. this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} was aborted`);
  12651. this.resetFragmentLoading(frag);
  12652. }
  12653. }
  12654. resetFragmentLoading(frag) {
  12655. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  12656. this.state = State.IDLE;
  12657. }
  12658. }
  12659. onFragmentOrKeyLoadError(filterType, data) {
  12660. if (data.chunkMeta && !data.frag) {
  12661. const context = this.getCurrentContext(data.chunkMeta);
  12662. if (context) {
  12663. data.frag = context.frag;
  12664. }
  12665. }
  12666. const frag = data.frag;
  12667. // Handle frag error related to caller's filterType
  12668. if (!frag || frag.type !== filterType || !this.levels) {
  12669. return;
  12670. }
  12671. if (this.fragContextChanged(frag)) {
  12672. var _this$fragCurrent2;
  12673. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url}`);
  12674. return;
  12675. }
  12676. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  12677. if (gapTagEncountered) {
  12678. this.fragmentTracker.fragBuffered(frag, true);
  12679. }
  12680. // keep retrying until the limit will be reached
  12681. const errorAction = data.errorAction;
  12682. const {
  12683. action,
  12684. retryCount = 0,
  12685. retryConfig
  12686. } = errorAction || {};
  12687. if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) {
  12688. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  12689. const delay = getRetryDelay(retryConfig, retryCount);
  12690. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  12691. errorAction.resolved = true;
  12692. this.retryDate = self.performance.now() + delay;
  12693. this.state = State.FRAG_LOADING_WAITING_RETRY;
  12694. } else if (retryConfig && errorAction) {
  12695. this.resetFragmentErrors(filterType);
  12696. if (retryCount < retryConfig.maxNumRetry) {
  12697. // Network retry is skipped when level switch is preferred
  12698. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  12699. errorAction.resolved = true;
  12700. }
  12701. } else {
  12702. logger.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  12703. return;
  12704. }
  12705. } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) {
  12706. this.state = State.WAITING_LEVEL;
  12707. } else {
  12708. this.state = State.ERROR;
  12709. }
  12710. // Perform next async tick sooner to speed up error action resolution
  12711. this.tickImmediate();
  12712. }
  12713. reduceLengthAndFlushBuffer(data) {
  12714. // if in appending state
  12715. if (this.state === State.PARSING || this.state === State.PARSED) {
  12716. const frag = data.frag;
  12717. const playlistType = data.parent;
  12718. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  12719. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  12720. // reduce max buf len if current position is buffered
  12721. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  12722. if (buffered) {
  12723. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  12724. }
  12725. const flushBuffer = !buffered;
  12726. if (flushBuffer) {
  12727. // current position is not buffered, but browser is still complaining about buffer full error
  12728. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  12729. // in that case flush the whole audio buffer to recover
  12730. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  12731. }
  12732. if (frag) {
  12733. this.fragmentTracker.removeFragment(frag);
  12734. this.nextLoadPosition = frag.start;
  12735. }
  12736. this.resetLoadingState();
  12737. return flushBuffer;
  12738. }
  12739. return false;
  12740. }
  12741. resetFragmentErrors(filterType) {
  12742. if (filterType === PlaylistLevelType.AUDIO) {
  12743. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  12744. this.fragCurrent = null;
  12745. }
  12746. // Fragment errors that result in a level switch or redundant fail-over
  12747. // should reset the stream controller state to idle
  12748. if (!this.loadedmetadata) {
  12749. this.startFragRequested = false;
  12750. }
  12751. if (this.state !== State.STOPPED) {
  12752. this.state = State.IDLE;
  12753. }
  12754. }
  12755. afterBufferFlushed(media, bufferType, playlistType) {
  12756. if (!media) {
  12757. return;
  12758. }
  12759. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  12760. // (so that we will check against video.buffered ranges in case of alt audio track)
  12761. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  12762. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  12763. if (this.state === State.ENDED) {
  12764. this.resetLoadingState();
  12765. }
  12766. }
  12767. resetLoadingState() {
  12768. this.log('Reset loading state');
  12769. this.fragCurrent = null;
  12770. this.fragPrevious = null;
  12771. this.state = State.IDLE;
  12772. }
  12773. resetStartWhenNotLoaded(level) {
  12774. // if loadedmetadata is not set, it means that first frag request failed
  12775. // in that case, reset startFragRequested flag
  12776. if (!this.loadedmetadata) {
  12777. this.startFragRequested = false;
  12778. const details = level ? level.details : null;
  12779. if (details != null && details.live) {
  12780. // Update the start position and return to IDLE to recover live start
  12781. this.startPosition = -1;
  12782. this.setStartPosition(details, 0);
  12783. this.resetLoadingState();
  12784. } else {
  12785. this.nextLoadPosition = this.startPosition;
  12786. }
  12787. }
  12788. }
  12789. resetWhenMissingContext(chunkMeta) {
  12790. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`);
  12791. this.removeUnbufferedFrags();
  12792. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  12793. this.resetLoadingState();
  12794. }
  12795. removeUnbufferedFrags(start = 0) {
  12796. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  12797. }
  12798. updateLevelTiming(frag, part, level, partial) {
  12799. var _this$transmuxer;
  12800. const details = level.details;
  12801. if (!details) {
  12802. this.warn('level.details undefined');
  12803. return;
  12804. }
  12805. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  12806. const info = frag.elementaryStreams[type];
  12807. if (info) {
  12808. const parsedDuration = info.endPTS - info.startPTS;
  12809. if (parsedDuration <= 0) {
  12810. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  12811. // The new transmuxer will be configured with a time offset matching the next fragment start,
  12812. // preventing the timeline from shifting.
  12813. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  12814. return result || false;
  12815. }
  12816. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  12817. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  12818. details,
  12819. level,
  12820. drift,
  12821. type,
  12822. frag,
  12823. start: info.startPTS,
  12824. end: info.endPTS
  12825. });
  12826. return true;
  12827. }
  12828. return result;
  12829. }, false);
  12830. if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  12831. const error = new Error(`Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`);
  12832. if (level.fragmentError === 0) {
  12833. // Mark and track the odd empty segment as a gap to avoid reloading
  12834. level.fragmentError++;
  12835. frag.gap = true;
  12836. this.fragmentTracker.removeFragment(frag);
  12837. this.fragmentTracker.fragBuffered(frag, true);
  12838. }
  12839. this.warn(error.message);
  12840. this.hls.trigger(Events.ERROR, {
  12841. type: ErrorTypes.MEDIA_ERROR,
  12842. details: ErrorDetails.FRAG_PARSING_ERROR,
  12843. fatal: false,
  12844. error,
  12845. frag,
  12846. reason: `Found no media in msn ${frag.sn} of level "${level.url}"`
  12847. });
  12848. if (!this.hls) {
  12849. return;
  12850. }
  12851. this.resetTransmuxer();
  12852. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  12853. }
  12854. this.state = State.PARSED;
  12855. this.hls.trigger(Events.FRAG_PARSED, {
  12856. frag,
  12857. part
  12858. });
  12859. }
  12860. resetTransmuxer() {
  12861. if (this.transmuxer) {
  12862. this.transmuxer.destroy();
  12863. this.transmuxer = null;
  12864. }
  12865. }
  12866. recoverWorkerError(data) {
  12867. if (data.event === 'demuxerWorker') {
  12868. this.fragmentTracker.removeAllFragments();
  12869. this.resetTransmuxer();
  12870. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  12871. this.resetLoadingState();
  12872. }
  12873. }
  12874. set state(nextState) {
  12875. const previousState = this._state;
  12876. if (previousState !== nextState) {
  12877. this._state = nextState;
  12878. this.log(`${previousState}->${nextState}`);
  12879. }
  12880. }
  12881. get state() {
  12882. return this._state;
  12883. }
  12884. }
  12885. function getSourceBuffer() {
  12886. return self.SourceBuffer || self.WebKitSourceBuffer;
  12887. }
  12888. function isMSESupported() {
  12889. const mediaSource = getMediaSource();
  12890. if (!mediaSource) {
  12891. return false;
  12892. }
  12893. // if SourceBuffer is exposed ensure its API is valid
  12894. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  12895. const sourceBuffer = getSourceBuffer();
  12896. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  12897. }
  12898. function isSupported() {
  12899. if (!isMSESupported()) {
  12900. return false;
  12901. }
  12902. const mediaSource = getMediaSource();
  12903. 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'))));
  12904. }
  12905. function changeTypeSupported() {
  12906. var _sourceBuffer$prototy;
  12907. const sourceBuffer = getSourceBuffer();
  12908. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  12909. }
  12910. // ensure the worker ends up in the bundle
  12911. // If the worker should not be included this gets aliased to empty.js
  12912. function hasUMDWorker() {
  12913. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  12914. }
  12915. function injectWorker() {
  12916. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  12917. type: 'text/javascript'
  12918. });
  12919. const objectURL = self.URL.createObjectURL(blob);
  12920. const worker = new self.Worker(objectURL);
  12921. return {
  12922. worker,
  12923. objectURL
  12924. };
  12925. }
  12926. function loadWorker(path) {
  12927. const scriptURL = new self.URL(path, self.location.href).href;
  12928. const worker = new self.Worker(scriptURL);
  12929. return {
  12930. worker,
  12931. scriptURL
  12932. };
  12933. }
  12934. function dummyTrack(type = '', inputTimeScale = 90000) {
  12935. return {
  12936. type,
  12937. id: -1,
  12938. pid: -1,
  12939. inputTimeScale,
  12940. sequenceNumber: -1,
  12941. samples: [],
  12942. dropped: 0
  12943. };
  12944. }
  12945. class BaseAudioDemuxer {
  12946. constructor() {
  12947. this._audioTrack = void 0;
  12948. this._id3Track = void 0;
  12949. this.frameIndex = 0;
  12950. this.cachedData = null;
  12951. this.basePTS = null;
  12952. this.initPTS = null;
  12953. this.lastPTS = null;
  12954. }
  12955. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12956. this._id3Track = {
  12957. type: 'id3',
  12958. id: 3,
  12959. pid: -1,
  12960. inputTimeScale: 90000,
  12961. sequenceNumber: 0,
  12962. samples: [],
  12963. dropped: 0
  12964. };
  12965. }
  12966. resetTimeStamp(deaultTimestamp) {
  12967. this.initPTS = deaultTimestamp;
  12968. this.resetContiguity();
  12969. }
  12970. resetContiguity() {
  12971. this.basePTS = null;
  12972. this.lastPTS = null;
  12973. this.frameIndex = 0;
  12974. }
  12975. canParse(data, offset) {
  12976. return false;
  12977. }
  12978. appendFrame(track, data, offset) {}
  12979. // feed incoming data to the front of the parsing pipeline
  12980. demux(data, timeOffset) {
  12981. if (this.cachedData) {
  12982. data = appendUint8Array(this.cachedData, data);
  12983. this.cachedData = null;
  12984. }
  12985. let id3Data = getID3Data(data, 0);
  12986. let offset = id3Data ? id3Data.length : 0;
  12987. let lastDataIndex;
  12988. const track = this._audioTrack;
  12989. const id3Track = this._id3Track;
  12990. const timestamp = id3Data ? getTimeStamp(id3Data) : undefined;
  12991. const length = data.length;
  12992. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  12993. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  12994. this.lastPTS = this.basePTS;
  12995. }
  12996. if (this.lastPTS === null) {
  12997. this.lastPTS = this.basePTS;
  12998. }
  12999. // more expressive than alternative: id3Data?.length
  13000. if (id3Data && id3Data.length > 0) {
  13001. id3Track.samples.push({
  13002. pts: this.lastPTS,
  13003. dts: this.lastPTS,
  13004. data: id3Data,
  13005. type: MetadataSchema.audioId3,
  13006. duration: Number.POSITIVE_INFINITY
  13007. });
  13008. }
  13009. while (offset < length) {
  13010. if (this.canParse(data, offset)) {
  13011. const frame = this.appendFrame(track, data, offset);
  13012. if (frame) {
  13013. this.frameIndex++;
  13014. this.lastPTS = frame.sample.pts;
  13015. offset += frame.length;
  13016. lastDataIndex = offset;
  13017. } else {
  13018. offset = length;
  13019. }
  13020. } else if (canParse$2(data, offset)) {
  13021. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  13022. id3Data = getID3Data(data, offset);
  13023. id3Track.samples.push({
  13024. pts: this.lastPTS,
  13025. dts: this.lastPTS,
  13026. data: id3Data,
  13027. type: MetadataSchema.audioId3,
  13028. duration: Number.POSITIVE_INFINITY
  13029. });
  13030. offset += id3Data.length;
  13031. lastDataIndex = offset;
  13032. } else {
  13033. offset++;
  13034. }
  13035. if (offset === length && lastDataIndex !== length) {
  13036. const partialData = sliceUint8(data, lastDataIndex);
  13037. if (this.cachedData) {
  13038. this.cachedData = appendUint8Array(this.cachedData, partialData);
  13039. } else {
  13040. this.cachedData = partialData;
  13041. }
  13042. }
  13043. }
  13044. return {
  13045. audioTrack: track,
  13046. videoTrack: dummyTrack(),
  13047. id3Track,
  13048. textTrack: dummyTrack()
  13049. };
  13050. }
  13051. demuxSampleAes(data, keyData, timeOffset) {
  13052. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  13053. }
  13054. flush(timeOffset) {
  13055. // Parse cache in case of remaining frames.
  13056. const cachedData = this.cachedData;
  13057. if (cachedData) {
  13058. this.cachedData = null;
  13059. this.demux(cachedData, 0);
  13060. }
  13061. return {
  13062. audioTrack: this._audioTrack,
  13063. videoTrack: dummyTrack(),
  13064. id3Track: this._id3Track,
  13065. textTrack: dummyTrack()
  13066. };
  13067. }
  13068. destroy() {}
  13069. }
  13070. /**
  13071. * Initialize PTS
  13072. * <p>
  13073. * use timestamp unless it is undefined, NaN or Infinity
  13074. * </p>
  13075. */
  13076. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  13077. if (isFiniteNumber(timestamp)) {
  13078. return timestamp * 90;
  13079. }
  13080. const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  13081. return timeOffset * 90000 + init90kHz;
  13082. };
  13083. /**
  13084. * ADTS parser helper
  13085. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  13086. */
  13087. function getAudioConfig(observer, data, offset, audioCodec) {
  13088. let adtsObjectType;
  13089. let adtsExtensionSamplingIndex;
  13090. let adtsChannelConfig;
  13091. let config;
  13092. const userAgent = navigator.userAgent.toLowerCase();
  13093. const manifestCodec = audioCodec;
  13094. const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  13095. // byte 2
  13096. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  13097. const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  13098. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  13099. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  13100. observer.emit(Events.ERROR, Events.ERROR, {
  13101. type: ErrorTypes.MEDIA_ERROR,
  13102. details: ErrorDetails.FRAG_PARSING_ERROR,
  13103. fatal: true,
  13104. error,
  13105. reason: error.message
  13106. });
  13107. return;
  13108. }
  13109. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  13110. // byte 3
  13111. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  13112. logger.log(`manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`);
  13113. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  13114. if (/firefox/i.test(userAgent)) {
  13115. if (adtsSamplingIndex >= 6) {
  13116. adtsObjectType = 5;
  13117. config = new Array(4);
  13118. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13119. // there is a factor 2 between frame sample rate and output sample rate
  13120. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13121. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13122. } else {
  13123. adtsObjectType = 2;
  13124. config = new Array(2);
  13125. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13126. }
  13127. // Android : always use AAC
  13128. } else if (userAgent.indexOf('android') !== -1) {
  13129. adtsObjectType = 2;
  13130. config = new Array(2);
  13131. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13132. } else {
  13133. /* for other browsers (Chrome/Vivaldi/Opera ...)
  13134. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  13135. */
  13136. adtsObjectType = 5;
  13137. config = new Array(4);
  13138. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  13139. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  13140. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13141. // there is a factor 2 between frame sample rate and output sample rate
  13142. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13143. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13144. } else {
  13145. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  13146. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  13147. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  13148. adtsObjectType = 2;
  13149. config = new Array(2);
  13150. }
  13151. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13152. }
  13153. }
  13154. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  13155. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  13156. Audio Profile / Audio Object Type
  13157. 0: Null
  13158. 1: AAC Main
  13159. 2: AAC LC (Low Complexity)
  13160. 3: AAC SSR (Scalable Sample Rate)
  13161. 4: AAC LTP (Long Term Prediction)
  13162. 5: SBR (Spectral Band Replication)
  13163. 6: AAC Scalable
  13164. sampling freq
  13165. 0: 96000 Hz
  13166. 1: 88200 Hz
  13167. 2: 64000 Hz
  13168. 3: 48000 Hz
  13169. 4: 44100 Hz
  13170. 5: 32000 Hz
  13171. 6: 24000 Hz
  13172. 7: 22050 Hz
  13173. 8: 16000 Hz
  13174. 9: 12000 Hz
  13175. 10: 11025 Hz
  13176. 11: 8000 Hz
  13177. 12: 7350 Hz
  13178. 13: Reserved
  13179. 14: Reserved
  13180. 15: frequency is written explictly
  13181. Channel Configurations
  13182. These are the channel configurations:
  13183. 0: Defined in AOT Specifc Config
  13184. 1: 1 channel: front-center
  13185. 2: 2 channels: front-left, front-right
  13186. */
  13187. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  13188. config[0] = adtsObjectType << 3;
  13189. // samplingFrequencyIndex
  13190. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  13191. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  13192. // channelConfiguration
  13193. config[1] |= adtsChannelConfig << 3;
  13194. if (adtsObjectType === 5) {
  13195. // adtsExtensionSamplingIndex
  13196. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  13197. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  13198. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  13199. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  13200. config[2] |= 2 << 2;
  13201. config[3] = 0;
  13202. }
  13203. return {
  13204. config,
  13205. samplerate: adtsSamplingRates[adtsSamplingIndex],
  13206. channelCount: adtsChannelConfig,
  13207. codec: 'mp4a.40.' + adtsObjectType,
  13208. manifestCodec
  13209. };
  13210. }
  13211. function isHeaderPattern$1(data, offset) {
  13212. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  13213. }
  13214. function getHeaderLength(data, offset) {
  13215. return data[offset + 1] & 0x01 ? 7 : 9;
  13216. }
  13217. function getFullFrameLength(data, offset) {
  13218. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  13219. }
  13220. function canGetFrameLength(data, offset) {
  13221. return offset + 5 < data.length;
  13222. }
  13223. function isHeader$1(data, offset) {
  13224. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13225. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13226. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13227. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  13228. }
  13229. function canParse$1(data, offset) {
  13230. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  13231. }
  13232. function probe$1(data, offset) {
  13233. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  13234. // or end of data is reached
  13235. if (isHeader$1(data, offset)) {
  13236. // ADTS header Length
  13237. const headerLength = getHeaderLength(data, offset);
  13238. if (offset + headerLength >= data.length) {
  13239. return false;
  13240. }
  13241. // ADTS frame Length
  13242. const frameLength = getFullFrameLength(data, offset);
  13243. if (frameLength <= headerLength) {
  13244. return false;
  13245. }
  13246. const newOffset = offset + frameLength;
  13247. return newOffset === data.length || isHeader$1(data, newOffset);
  13248. }
  13249. return false;
  13250. }
  13251. function initTrackConfig(track, observer, data, offset, audioCodec) {
  13252. if (!track.samplerate) {
  13253. const config = getAudioConfig(observer, data, offset, audioCodec);
  13254. if (!config) {
  13255. return;
  13256. }
  13257. track.config = config.config;
  13258. track.samplerate = config.samplerate;
  13259. track.channelCount = config.channelCount;
  13260. track.codec = config.codec;
  13261. track.manifestCodec = config.manifestCodec;
  13262. logger.log(`parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`);
  13263. }
  13264. }
  13265. function getFrameDuration(samplerate) {
  13266. return 1024 * 90000 / samplerate;
  13267. }
  13268. function parseFrameHeader(data, offset) {
  13269. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  13270. const headerLength = getHeaderLength(data, offset);
  13271. if (offset + headerLength <= data.length) {
  13272. // retrieve frame size
  13273. const frameLength = getFullFrameLength(data, offset) - headerLength;
  13274. if (frameLength > 0) {
  13275. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  13276. return {
  13277. headerLength,
  13278. frameLength
  13279. };
  13280. }
  13281. }
  13282. }
  13283. function appendFrame$1(track, data, offset, pts, frameIndex) {
  13284. const frameDuration = getFrameDuration(track.samplerate);
  13285. const stamp = pts + frameIndex * frameDuration;
  13286. const header = parseFrameHeader(data, offset);
  13287. let unit;
  13288. if (header) {
  13289. const {
  13290. frameLength,
  13291. headerLength
  13292. } = header;
  13293. const _length = headerLength + frameLength;
  13294. const missing = Math.max(0, offset + _length - data.length);
  13295. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  13296. if (missing) {
  13297. unit = new Uint8Array(_length - headerLength);
  13298. unit.set(data.subarray(offset + headerLength, data.length), 0);
  13299. } else {
  13300. unit = data.subarray(offset + headerLength, offset + _length);
  13301. }
  13302. const _sample = {
  13303. unit,
  13304. pts: stamp
  13305. };
  13306. if (!missing) {
  13307. track.samples.push(_sample);
  13308. }
  13309. return {
  13310. sample: _sample,
  13311. length: _length,
  13312. missing
  13313. };
  13314. }
  13315. // overflow incomplete header
  13316. const length = data.length - offset;
  13317. unit = new Uint8Array(length);
  13318. unit.set(data.subarray(offset, data.length), 0);
  13319. const sample = {
  13320. unit,
  13321. pts: stamp
  13322. };
  13323. return {
  13324. sample,
  13325. length,
  13326. missing: -1
  13327. };
  13328. }
  13329. /**
  13330. * MPEG parser helper
  13331. */
  13332. let chromeVersion$1 = null;
  13333. 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];
  13334. const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  13335. const SamplesCoefficients = [
  13336. // MPEG 2.5
  13337. [0,
  13338. // Reserved
  13339. 72,
  13340. // Layer3
  13341. 144,
  13342. // Layer2
  13343. 12 // Layer1
  13344. ],
  13345. // Reserved
  13346. [0,
  13347. // Reserved
  13348. 0,
  13349. // Layer3
  13350. 0,
  13351. // Layer2
  13352. 0 // Layer1
  13353. ],
  13354. // MPEG 2
  13355. [0,
  13356. // Reserved
  13357. 72,
  13358. // Layer3
  13359. 144,
  13360. // Layer2
  13361. 12 // Layer1
  13362. ],
  13363. // MPEG 1
  13364. [0,
  13365. // Reserved
  13366. 144,
  13367. // Layer3
  13368. 144,
  13369. // Layer2
  13370. 12 // Layer1
  13371. ]];
  13372. const BytesInSlot = [0,
  13373. // Reserved
  13374. 1,
  13375. // Layer3
  13376. 1,
  13377. // Layer2
  13378. 4 // Layer1
  13379. ];
  13380. function appendFrame(track, data, offset, pts, frameIndex) {
  13381. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  13382. if (offset + 24 > data.length) {
  13383. return;
  13384. }
  13385. const header = parseHeader(data, offset);
  13386. if (header && offset + header.frameLength <= data.length) {
  13387. const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  13388. const stamp = pts + frameIndex * frameDuration;
  13389. const sample = {
  13390. unit: data.subarray(offset, offset + header.frameLength),
  13391. pts: stamp,
  13392. dts: stamp
  13393. };
  13394. track.config = [];
  13395. track.channelCount = header.channelCount;
  13396. track.samplerate = header.sampleRate;
  13397. track.samples.push(sample);
  13398. return {
  13399. sample,
  13400. length: header.frameLength,
  13401. missing: 0
  13402. };
  13403. }
  13404. }
  13405. function parseHeader(data, offset) {
  13406. const mpegVersion = data[offset + 1] >> 3 & 3;
  13407. const mpegLayer = data[offset + 1] >> 1 & 3;
  13408. const bitRateIndex = data[offset + 2] >> 4 & 15;
  13409. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  13410. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  13411. const paddingBit = data[offset + 2] >> 1 & 1;
  13412. const channelMode = data[offset + 3] >> 6;
  13413. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  13414. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  13415. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  13416. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  13417. const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  13418. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  13419. const bytesInSlot = BytesInSlot[mpegLayer];
  13420. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  13421. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  13422. if (chromeVersion$1 === null) {
  13423. const userAgent = navigator.userAgent || '';
  13424. const result = userAgent.match(/Chrome\/(\d+)/i);
  13425. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  13426. }
  13427. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  13428. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  13429. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  13430. data[offset + 3] = data[offset + 3] | 0x80;
  13431. }
  13432. return {
  13433. sampleRate,
  13434. channelCount,
  13435. frameLength,
  13436. samplesPerFrame
  13437. };
  13438. }
  13439. }
  13440. function isHeaderPattern(data, offset) {
  13441. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  13442. }
  13443. function isHeader(data, offset) {
  13444. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  13445. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  13446. // More info http://www.mp3-tech.org/programmer/frame_header.html
  13447. return offset + 1 < data.length && isHeaderPattern(data, offset);
  13448. }
  13449. function canParse(data, offset) {
  13450. const headerSize = 4;
  13451. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  13452. }
  13453. function probe(data, offset) {
  13454. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  13455. // or end of data is reached
  13456. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  13457. // MPEG header Length
  13458. const headerLength = 4;
  13459. // MPEG frame Length
  13460. const header = parseHeader(data, offset);
  13461. let frameLength = headerLength;
  13462. if (header != null && header.frameLength) {
  13463. frameLength = header.frameLength;
  13464. }
  13465. const newOffset = offset + frameLength;
  13466. return newOffset === data.length || isHeader(data, newOffset);
  13467. }
  13468. return false;
  13469. }
  13470. /**
  13471. * AAC demuxer
  13472. */
  13473. class AACDemuxer extends BaseAudioDemuxer {
  13474. constructor(observer, config) {
  13475. super();
  13476. this.observer = void 0;
  13477. this.config = void 0;
  13478. this.observer = observer;
  13479. this.config = config;
  13480. }
  13481. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13482. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  13483. this._audioTrack = {
  13484. container: 'audio/adts',
  13485. type: 'audio',
  13486. id: 2,
  13487. pid: -1,
  13488. sequenceNumber: 0,
  13489. segmentCodec: 'aac',
  13490. samples: [],
  13491. manifestCodec: audioCodec,
  13492. duration: trackDuration,
  13493. inputTimeScale: 90000,
  13494. dropped: 0
  13495. };
  13496. }
  13497. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  13498. static probe(data) {
  13499. if (!data) {
  13500. return false;
  13501. }
  13502. // Check for the ADTS sync word
  13503. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13504. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13505. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13506. const id3Data = getID3Data(data, 0);
  13507. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  13508. if (probe(data, offset)) {
  13509. return false;
  13510. }
  13511. for (let length = data.length; offset < length; offset++) {
  13512. if (probe$1(data, offset)) {
  13513. logger.log('ADTS sync word found !');
  13514. return true;
  13515. }
  13516. }
  13517. return false;
  13518. }
  13519. canParse(data, offset) {
  13520. return canParse$1(data, offset);
  13521. }
  13522. appendFrame(track, data, offset) {
  13523. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  13524. const frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  13525. if (frame && frame.missing === 0) {
  13526. return frame;
  13527. }
  13528. }
  13529. }
  13530. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  13531. class MP4Demuxer {
  13532. constructor(observer, config) {
  13533. this.remainderData = null;
  13534. this.timeOffset = 0;
  13535. this.config = void 0;
  13536. this.videoTrack = void 0;
  13537. this.audioTrack = void 0;
  13538. this.id3Track = void 0;
  13539. this.txtTrack = void 0;
  13540. this.config = config;
  13541. }
  13542. resetTimeStamp() {}
  13543. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13544. const videoTrack = this.videoTrack = dummyTrack('video', 1);
  13545. const audioTrack = this.audioTrack = dummyTrack('audio', 1);
  13546. const captionTrack = this.txtTrack = dummyTrack('text', 1);
  13547. this.id3Track = dummyTrack('id3', 1);
  13548. this.timeOffset = 0;
  13549. if (!(initSegment != null && initSegment.byteLength)) {
  13550. return;
  13551. }
  13552. const initData = parseInitSegment(initSegment);
  13553. if (initData.video) {
  13554. const {
  13555. id,
  13556. timescale,
  13557. codec
  13558. } = initData.video;
  13559. videoTrack.id = id;
  13560. videoTrack.timescale = captionTrack.timescale = timescale;
  13561. videoTrack.codec = codec;
  13562. }
  13563. if (initData.audio) {
  13564. const {
  13565. id,
  13566. timescale,
  13567. codec
  13568. } = initData.audio;
  13569. audioTrack.id = id;
  13570. audioTrack.timescale = timescale;
  13571. audioTrack.codec = codec;
  13572. }
  13573. captionTrack.id = RemuxerTrackIdConfig.text;
  13574. videoTrack.sampleDuration = 0;
  13575. videoTrack.duration = audioTrack.duration = trackDuration;
  13576. }
  13577. resetContiguity() {
  13578. this.remainderData = null;
  13579. }
  13580. static probe(data) {
  13581. return hasMoofData(data);
  13582. }
  13583. demux(data, timeOffset) {
  13584. this.timeOffset = timeOffset;
  13585. // 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
  13586. let videoSamples = data;
  13587. const videoTrack = this.videoTrack;
  13588. const textTrack = this.txtTrack;
  13589. if (this.config.progressive) {
  13590. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  13591. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  13592. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  13593. if (this.remainderData) {
  13594. videoSamples = appendUint8Array(this.remainderData, data);
  13595. }
  13596. const segmentedData = segmentValidRange(videoSamples);
  13597. this.remainderData = segmentedData.remainder;
  13598. videoTrack.samples = segmentedData.valid || new Uint8Array();
  13599. } else {
  13600. videoTrack.samples = videoSamples;
  13601. }
  13602. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  13603. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13604. return {
  13605. videoTrack,
  13606. audioTrack: this.audioTrack,
  13607. id3Track,
  13608. textTrack: this.txtTrack
  13609. };
  13610. }
  13611. flush() {
  13612. const timeOffset = this.timeOffset;
  13613. const videoTrack = this.videoTrack;
  13614. const textTrack = this.txtTrack;
  13615. videoTrack.samples = this.remainderData || new Uint8Array();
  13616. this.remainderData = null;
  13617. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  13618. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13619. return {
  13620. videoTrack,
  13621. audioTrack: dummyTrack(),
  13622. id3Track,
  13623. textTrack: dummyTrack()
  13624. };
  13625. }
  13626. extractID3Track(videoTrack, timeOffset) {
  13627. const id3Track = this.id3Track;
  13628. if (videoTrack.samples.length) {
  13629. const emsgs = findBox(videoTrack.samples, ['emsg']);
  13630. if (emsgs) {
  13631. emsgs.forEach(data => {
  13632. const emsgInfo = parseEmsg(data);
  13633. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  13634. const pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  13635. let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  13636. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  13637. if (duration <= 0.001) {
  13638. duration = Number.POSITIVE_INFINITY;
  13639. }
  13640. const payload = emsgInfo.payload;
  13641. id3Track.samples.push({
  13642. data: payload,
  13643. len: payload.byteLength,
  13644. dts: pts,
  13645. pts: pts,
  13646. type: MetadataSchema.emsg,
  13647. duration: duration
  13648. });
  13649. }
  13650. });
  13651. }
  13652. }
  13653. return id3Track;
  13654. }
  13655. demuxSampleAes(data, keyData, timeOffset) {
  13656. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  13657. }
  13658. destroy() {}
  13659. }
  13660. const getAudioBSID = (data, offset) => {
  13661. // check the bsid to confirm ac-3 | ec-3
  13662. let bsid = 0;
  13663. let numBits = 5;
  13664. offset += numBits;
  13665. const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  13666. const mask = new Uint32Array(1); // unsigned 32 bit mask value
  13667. const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  13668. while (numBits > 0) {
  13669. byte[0] = data[offset];
  13670. // read remaining bits, upto 8 bits at a time
  13671. const bits = Math.min(numBits, 8);
  13672. const shift = 8 - bits;
  13673. mask[0] = 0xff000000 >>> 24 + shift << shift;
  13674. temp[0] = (byte[0] & mask[0]) >> shift;
  13675. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  13676. offset += 1;
  13677. numBits -= bits;
  13678. }
  13679. return bsid;
  13680. };
  13681. class BaseVideoParser {
  13682. constructor() {
  13683. this.VideoSample = null;
  13684. }
  13685. createVideoSample(key, pts, dts, debug) {
  13686. return {
  13687. key,
  13688. frame: false,
  13689. pts,
  13690. dts,
  13691. units: [],
  13692. debug,
  13693. length: 0
  13694. };
  13695. }
  13696. getLastNalUnit(samples) {
  13697. var _VideoSample;
  13698. let VideoSample = this.VideoSample;
  13699. let lastUnit;
  13700. // try to fallback to previous sample if current one is empty
  13701. if (!VideoSample || VideoSample.units.length === 0) {
  13702. VideoSample = samples[samples.length - 1];
  13703. }
  13704. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  13705. const units = VideoSample.units;
  13706. lastUnit = units[units.length - 1];
  13707. }
  13708. return lastUnit;
  13709. }
  13710. pushAccessUnit(VideoSample, videoTrack) {
  13711. if (VideoSample.units.length && VideoSample.frame) {
  13712. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  13713. if (VideoSample.pts === undefined) {
  13714. const samples = videoTrack.samples;
  13715. const nbSamples = samples.length;
  13716. if (nbSamples) {
  13717. const lastSample = samples[nbSamples - 1];
  13718. VideoSample.pts = lastSample.pts;
  13719. VideoSample.dts = lastSample.dts;
  13720. } else {
  13721. // dropping samples, no timestamp found
  13722. videoTrack.dropped++;
  13723. return;
  13724. }
  13725. }
  13726. videoTrack.samples.push(VideoSample);
  13727. }
  13728. if (VideoSample.debug.length) {
  13729. logger.log(VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug);
  13730. }
  13731. }
  13732. }
  13733. /**
  13734. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  13735. */
  13736. class ExpGolomb {
  13737. constructor(data) {
  13738. this.data = void 0;
  13739. this.bytesAvailable = void 0;
  13740. this.word = void 0;
  13741. this.bitsAvailable = void 0;
  13742. this.data = data;
  13743. // the number of bytes left to examine in this.data
  13744. this.bytesAvailable = data.byteLength;
  13745. // the current word being examined
  13746. this.word = 0; // :uint
  13747. // the number of bits left to examine in the current word
  13748. this.bitsAvailable = 0; // :uint
  13749. }
  13750. // ():void
  13751. loadWord() {
  13752. const data = this.data;
  13753. const bytesAvailable = this.bytesAvailable;
  13754. const position = data.byteLength - bytesAvailable;
  13755. const workingBytes = new Uint8Array(4);
  13756. const availableBytes = Math.min(4, bytesAvailable);
  13757. if (availableBytes === 0) {
  13758. throw new Error('no bytes available');
  13759. }
  13760. workingBytes.set(data.subarray(position, position + availableBytes));
  13761. this.word = new DataView(workingBytes.buffer).getUint32(0);
  13762. // track the amount of this.data that has been processed
  13763. this.bitsAvailable = availableBytes * 8;
  13764. this.bytesAvailable -= availableBytes;
  13765. }
  13766. // (count:int):void
  13767. skipBits(count) {
  13768. let skipBytes; // :int
  13769. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  13770. if (this.bitsAvailable > count) {
  13771. this.word <<= count;
  13772. this.bitsAvailable -= count;
  13773. } else {
  13774. count -= this.bitsAvailable;
  13775. skipBytes = count >> 3;
  13776. count -= skipBytes << 3;
  13777. this.bytesAvailable -= skipBytes;
  13778. this.loadWord();
  13779. this.word <<= count;
  13780. this.bitsAvailable -= count;
  13781. }
  13782. }
  13783. // (size:int):uint
  13784. readBits(size) {
  13785. let bits = Math.min(this.bitsAvailable, size); // :uint
  13786. const valu = this.word >>> 32 - bits; // :uint
  13787. if (size > 32) {
  13788. logger.error('Cannot read more than 32 bits at a time');
  13789. }
  13790. this.bitsAvailable -= bits;
  13791. if (this.bitsAvailable > 0) {
  13792. this.word <<= bits;
  13793. } else if (this.bytesAvailable > 0) {
  13794. this.loadWord();
  13795. } else {
  13796. throw new Error('no bits available');
  13797. }
  13798. bits = size - bits;
  13799. if (bits > 0 && this.bitsAvailable) {
  13800. return valu << bits | this.readBits(bits);
  13801. } else {
  13802. return valu;
  13803. }
  13804. }
  13805. // ():uint
  13806. skipLZ() {
  13807. let leadingZeroCount; // :uint
  13808. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  13809. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  13810. // the first bit of working word is 1
  13811. this.word <<= leadingZeroCount;
  13812. this.bitsAvailable -= leadingZeroCount;
  13813. return leadingZeroCount;
  13814. }
  13815. }
  13816. // we exhausted word and still have not found a 1
  13817. this.loadWord();
  13818. return leadingZeroCount + this.skipLZ();
  13819. }
  13820. // ():void
  13821. skipUEG() {
  13822. this.skipBits(1 + this.skipLZ());
  13823. }
  13824. // ():void
  13825. skipEG() {
  13826. this.skipBits(1 + this.skipLZ());
  13827. }
  13828. // ():uint
  13829. readUEG() {
  13830. const clz = this.skipLZ(); // :uint
  13831. return this.readBits(clz + 1) - 1;
  13832. }
  13833. // ():int
  13834. readEG() {
  13835. const valu = this.readUEG(); // :int
  13836. if (0x01 & valu) {
  13837. // the number is odd if the low order bit is set
  13838. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  13839. } else {
  13840. return -1 * (valu >>> 1); // divide by two then make it negative
  13841. }
  13842. }
  13843. // Some convenience functions
  13844. // :Boolean
  13845. readBoolean() {
  13846. return this.readBits(1) === 1;
  13847. }
  13848. // ():int
  13849. readUByte() {
  13850. return this.readBits(8);
  13851. }
  13852. // ():int
  13853. readUShort() {
  13854. return this.readBits(16);
  13855. }
  13856. // ():int
  13857. readUInt() {
  13858. return this.readBits(32);
  13859. }
  13860. /**
  13861. * Advance the ExpGolomb decoder past a scaling list. The scaling
  13862. * list is optionally transmitted as part of a sequence parameter
  13863. * set and is not relevant to transmuxing.
  13864. * @param count the number of entries in this scaling list
  13865. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  13866. */
  13867. skipScalingList(count) {
  13868. let lastScale = 8;
  13869. let nextScale = 8;
  13870. let deltaScale;
  13871. for (let j = 0; j < count; j++) {
  13872. if (nextScale !== 0) {
  13873. deltaScale = this.readEG();
  13874. nextScale = (lastScale + deltaScale + 256) % 256;
  13875. }
  13876. lastScale = nextScale === 0 ? lastScale : nextScale;
  13877. }
  13878. }
  13879. /**
  13880. * Read a sequence parameter set and return some interesting video
  13881. * properties. A sequence parameter set is the H264 metadata that
  13882. * describes the properties of upcoming video frames.
  13883. * @returns an object with configuration parsed from the
  13884. * sequence parameter set, including the dimensions of the
  13885. * associated video frames.
  13886. */
  13887. readSPS() {
  13888. let frameCropLeftOffset = 0;
  13889. let frameCropRightOffset = 0;
  13890. let frameCropTopOffset = 0;
  13891. let frameCropBottomOffset = 0;
  13892. let numRefFramesInPicOrderCntCycle;
  13893. let scalingListCount;
  13894. let i;
  13895. const readUByte = this.readUByte.bind(this);
  13896. const readBits = this.readBits.bind(this);
  13897. const readUEG = this.readUEG.bind(this);
  13898. const readBoolean = this.readBoolean.bind(this);
  13899. const skipBits = this.skipBits.bind(this);
  13900. const skipEG = this.skipEG.bind(this);
  13901. const skipUEG = this.skipUEG.bind(this);
  13902. const skipScalingList = this.skipScalingList.bind(this);
  13903. readUByte();
  13904. const profileIdc = readUByte(); // profile_idc
  13905. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  13906. skipBits(3); // reserved_zero_3bits u(3),
  13907. readUByte(); // level_idc u(8)
  13908. skipUEG(); // seq_parameter_set_id
  13909. // some profiles have more optional data we don't need
  13910. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  13911. const chromaFormatIdc = readUEG();
  13912. if (chromaFormatIdc === 3) {
  13913. skipBits(1);
  13914. } // separate_colour_plane_flag
  13915. skipUEG(); // bit_depth_luma_minus8
  13916. skipUEG(); // bit_depth_chroma_minus8
  13917. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  13918. if (readBoolean()) {
  13919. // seq_scaling_matrix_present_flag
  13920. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  13921. for (i = 0; i < scalingListCount; i++) {
  13922. if (readBoolean()) {
  13923. // seq_scaling_list_present_flag[ i ]
  13924. if (i < 6) {
  13925. skipScalingList(16);
  13926. } else {
  13927. skipScalingList(64);
  13928. }
  13929. }
  13930. }
  13931. }
  13932. }
  13933. skipUEG(); // log2_max_frame_num_minus4
  13934. const picOrderCntType = readUEG();
  13935. if (picOrderCntType === 0) {
  13936. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  13937. } else if (picOrderCntType === 1) {
  13938. skipBits(1); // delta_pic_order_always_zero_flag
  13939. skipEG(); // offset_for_non_ref_pic
  13940. skipEG(); // offset_for_top_to_bottom_field
  13941. numRefFramesInPicOrderCntCycle = readUEG();
  13942. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  13943. skipEG();
  13944. } // offset_for_ref_frame[ i ]
  13945. }
  13946. skipUEG(); // max_num_ref_frames
  13947. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  13948. const picWidthInMbsMinus1 = readUEG();
  13949. const picHeightInMapUnitsMinus1 = readUEG();
  13950. const frameMbsOnlyFlag = readBits(1);
  13951. if (frameMbsOnlyFlag === 0) {
  13952. skipBits(1);
  13953. } // mb_adaptive_frame_field_flag
  13954. skipBits(1); // direct_8x8_inference_flag
  13955. if (readBoolean()) {
  13956. // frame_cropping_flag
  13957. frameCropLeftOffset = readUEG();
  13958. frameCropRightOffset = readUEG();
  13959. frameCropTopOffset = readUEG();
  13960. frameCropBottomOffset = readUEG();
  13961. }
  13962. let pixelRatio = [1, 1];
  13963. if (readBoolean()) {
  13964. // vui_parameters_present_flag
  13965. if (readBoolean()) {
  13966. // aspect_ratio_info_present_flag
  13967. const aspectRatioIdc = readUByte();
  13968. switch (aspectRatioIdc) {
  13969. case 1:
  13970. pixelRatio = [1, 1];
  13971. break;
  13972. case 2:
  13973. pixelRatio = [12, 11];
  13974. break;
  13975. case 3:
  13976. pixelRatio = [10, 11];
  13977. break;
  13978. case 4:
  13979. pixelRatio = [16, 11];
  13980. break;
  13981. case 5:
  13982. pixelRatio = [40, 33];
  13983. break;
  13984. case 6:
  13985. pixelRatio = [24, 11];
  13986. break;
  13987. case 7:
  13988. pixelRatio = [20, 11];
  13989. break;
  13990. case 8:
  13991. pixelRatio = [32, 11];
  13992. break;
  13993. case 9:
  13994. pixelRatio = [80, 33];
  13995. break;
  13996. case 10:
  13997. pixelRatio = [18, 11];
  13998. break;
  13999. case 11:
  14000. pixelRatio = [15, 11];
  14001. break;
  14002. case 12:
  14003. pixelRatio = [64, 33];
  14004. break;
  14005. case 13:
  14006. pixelRatio = [160, 99];
  14007. break;
  14008. case 14:
  14009. pixelRatio = [4, 3];
  14010. break;
  14011. case 15:
  14012. pixelRatio = [3, 2];
  14013. break;
  14014. case 16:
  14015. pixelRatio = [2, 1];
  14016. break;
  14017. case 255:
  14018. {
  14019. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  14020. break;
  14021. }
  14022. }
  14023. }
  14024. }
  14025. return {
  14026. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  14027. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  14028. pixelRatio: pixelRatio
  14029. };
  14030. }
  14031. readSliceType() {
  14032. // skip NALu type
  14033. this.readUByte();
  14034. // discard first_mb_in_slice
  14035. this.readUEG();
  14036. // return slice_type
  14037. return this.readUEG();
  14038. }
  14039. }
  14040. class AvcVideoParser extends BaseVideoParser {
  14041. parseAVCPES(track, textTrack, pes, last, duration) {
  14042. const units = this.parseAVCNALu(track, pes.data);
  14043. let VideoSample = this.VideoSample;
  14044. let push;
  14045. let spsfound = false;
  14046. // free pes.data to save up some memory
  14047. pes.data = null;
  14048. // if new NAL units found and last sample still there, let's push ...
  14049. // this helps parsing streams with missing AUD (only do this if AUD never found)
  14050. if (VideoSample && units.length && !track.audFound) {
  14051. this.pushAccessUnit(VideoSample, track);
  14052. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  14053. }
  14054. units.forEach(unit => {
  14055. var _VideoSample2;
  14056. switch (unit.type) {
  14057. // NDR
  14058. case 1:
  14059. {
  14060. let iskey = false;
  14061. push = true;
  14062. const data = unit.data;
  14063. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  14064. if (spsfound && data.length > 4) {
  14065. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  14066. const sliceType = new ExpGolomb(data).readSliceType();
  14067. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  14068. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  14069. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  14070. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  14071. // if (sliceType === 2 || sliceType === 7) {
  14072. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  14073. iskey = true;
  14074. }
  14075. }
  14076. if (iskey) {
  14077. var _VideoSample;
  14078. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  14079. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  14080. this.pushAccessUnit(VideoSample, track);
  14081. VideoSample = this.VideoSample = null;
  14082. }
  14083. }
  14084. if (!VideoSample) {
  14085. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  14086. }
  14087. VideoSample.frame = true;
  14088. VideoSample.key = iskey;
  14089. break;
  14090. // IDR
  14091. }
  14092. case 5:
  14093. push = true;
  14094. // handle PES not starting with AUD
  14095. // if we have frame data already, that cannot belong to the same frame, so force a push
  14096. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  14097. this.pushAccessUnit(VideoSample, track);
  14098. VideoSample = this.VideoSample = null;
  14099. }
  14100. if (!VideoSample) {
  14101. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  14102. }
  14103. VideoSample.key = true;
  14104. VideoSample.frame = true;
  14105. break;
  14106. // SEI
  14107. case 6:
  14108. {
  14109. push = true;
  14110. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  14111. break;
  14112. // SPS
  14113. }
  14114. case 7:
  14115. {
  14116. var _track$pixelRatio, _track$pixelRatio2;
  14117. push = true;
  14118. spsfound = true;
  14119. const sps = unit.data;
  14120. const expGolombDecoder = new ExpGolomb(sps);
  14121. const config = expGolombDecoder.readSPS();
  14122. 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]) {
  14123. track.width = config.width;
  14124. track.height = config.height;
  14125. track.pixelRatio = config.pixelRatio;
  14126. track.sps = [sps];
  14127. track.duration = duration;
  14128. const codecarray = sps.subarray(1, 4);
  14129. let codecstring = 'avc1.';
  14130. for (let i = 0; i < 3; i++) {
  14131. let h = codecarray[i].toString(16);
  14132. if (h.length < 2) {
  14133. h = '0' + h;
  14134. }
  14135. codecstring += h;
  14136. }
  14137. track.codec = codecstring;
  14138. }
  14139. break;
  14140. }
  14141. // PPS
  14142. case 8:
  14143. push = true;
  14144. track.pps = [unit.data];
  14145. break;
  14146. // AUD
  14147. case 9:
  14148. push = true;
  14149. track.audFound = true;
  14150. if (VideoSample) {
  14151. this.pushAccessUnit(VideoSample, track);
  14152. }
  14153. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  14154. break;
  14155. // Filler Data
  14156. case 12:
  14157. push = true;
  14158. break;
  14159. default:
  14160. push = false;
  14161. if (VideoSample) {
  14162. VideoSample.debug += 'unknown NAL ' + unit.type + ' ';
  14163. }
  14164. break;
  14165. }
  14166. if (VideoSample && push) {
  14167. const units = VideoSample.units;
  14168. units.push(unit);
  14169. }
  14170. });
  14171. // if last PES packet, push samples
  14172. if (last && VideoSample) {
  14173. this.pushAccessUnit(VideoSample, track);
  14174. this.VideoSample = null;
  14175. }
  14176. }
  14177. parseAVCNALu(track, array) {
  14178. const len = array.byteLength;
  14179. let state = track.naluState || 0;
  14180. const lastState = state;
  14181. const units = [];
  14182. let i = 0;
  14183. let value;
  14184. let overflow;
  14185. let unitType;
  14186. let lastUnitStart = -1;
  14187. let lastUnitType = 0;
  14188. // logger.log('PES:' + Hex.hexDump(array));
  14189. if (state === -1) {
  14190. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  14191. lastUnitStart = 0;
  14192. // NALu type is value read from offset 0
  14193. lastUnitType = array[0] & 0x1f;
  14194. state = 0;
  14195. i = 1;
  14196. }
  14197. while (i < len) {
  14198. value = array[i++];
  14199. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  14200. if (!state) {
  14201. state = value ? 0 : 1;
  14202. continue;
  14203. }
  14204. if (state === 1) {
  14205. state = value ? 0 : 2;
  14206. continue;
  14207. }
  14208. // here we have state either equal to 2 or 3
  14209. if (!value) {
  14210. state = 3;
  14211. } else if (value === 1) {
  14212. overflow = i - state - 1;
  14213. if (lastUnitStart >= 0) {
  14214. const unit = {
  14215. data: array.subarray(lastUnitStart, overflow),
  14216. type: lastUnitType
  14217. };
  14218. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  14219. units.push(unit);
  14220. } else {
  14221. // lastUnitStart is undefined => this is the first start code found in this PES packet
  14222. // first check if start code delimiter is overlapping between 2 PES packets,
  14223. // ie it started in last packet (lastState not zero)
  14224. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  14225. const lastUnit = this.getLastNalUnit(track.samples);
  14226. if (lastUnit) {
  14227. if (lastState && i <= 4 - lastState) {
  14228. // start delimiter overlapping between PES packets
  14229. // strip start delimiter bytes from the end of last NAL unit
  14230. // check if lastUnit had a state different from zero
  14231. if (lastUnit.state) {
  14232. // strip last bytes
  14233. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  14234. }
  14235. }
  14236. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  14237. if (overflow > 0) {
  14238. // logger.log('first NALU found with overflow:' + overflow);
  14239. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  14240. lastUnit.state = 0;
  14241. }
  14242. }
  14243. }
  14244. // check if we can read unit type
  14245. if (i < len) {
  14246. unitType = array[i] & 0x1f;
  14247. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  14248. lastUnitStart = i;
  14249. lastUnitType = unitType;
  14250. state = 0;
  14251. } else {
  14252. // not enough byte to read unit type. let's read it on next PES parsing
  14253. state = -1;
  14254. }
  14255. } else {
  14256. state = 0;
  14257. }
  14258. }
  14259. if (lastUnitStart >= 0 && state >= 0) {
  14260. const unit = {
  14261. data: array.subarray(lastUnitStart, len),
  14262. type: lastUnitType,
  14263. state: state
  14264. };
  14265. units.push(unit);
  14266. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  14267. }
  14268. // no NALu found
  14269. if (units.length === 0) {
  14270. // append pes.data to previous NAL unit
  14271. const lastUnit = this.getLastNalUnit(track.samples);
  14272. if (lastUnit) {
  14273. lastUnit.data = appendUint8Array(lastUnit.data, array);
  14274. }
  14275. }
  14276. track.naluState = state;
  14277. return units;
  14278. }
  14279. }
  14280. /**
  14281. * SAMPLE-AES decrypter
  14282. */
  14283. class SampleAesDecrypter {
  14284. constructor(observer, config, keyData) {
  14285. this.keyData = void 0;
  14286. this.decrypter = void 0;
  14287. this.keyData = keyData;
  14288. this.decrypter = new Decrypter(config, {
  14289. removePKCS7Padding: false
  14290. });
  14291. }
  14292. decryptBuffer(encryptedData) {
  14293. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  14294. }
  14295. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  14296. decryptAacSample(samples, sampleIndex, callback) {
  14297. const curUnit = samples[sampleIndex].unit;
  14298. if (curUnit.length <= 16) {
  14299. // No encrypted portion in this sample (first 16 bytes is not
  14300. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  14301. return;
  14302. }
  14303. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  14304. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  14305. this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {
  14306. const decryptedData = new Uint8Array(decryptedBuffer);
  14307. curUnit.set(decryptedData, 16);
  14308. if (!this.decrypter.isSync()) {
  14309. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  14310. }
  14311. });
  14312. }
  14313. decryptAacSamples(samples, sampleIndex, callback) {
  14314. for (;; sampleIndex++) {
  14315. if (sampleIndex >= samples.length) {
  14316. callback();
  14317. return;
  14318. }
  14319. if (samples[sampleIndex].unit.length < 32) {
  14320. continue;
  14321. }
  14322. this.decryptAacSample(samples, sampleIndex, callback);
  14323. if (!this.decrypter.isSync()) {
  14324. return;
  14325. }
  14326. }
  14327. }
  14328. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  14329. getAvcEncryptedData(decodedData) {
  14330. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  14331. const encryptedData = new Int8Array(encryptedDataLen);
  14332. let outputPos = 0;
  14333. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  14334. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  14335. }
  14336. return encryptedData;
  14337. }
  14338. getAvcDecryptedUnit(decodedData, decryptedData) {
  14339. const uint8DecryptedData = new Uint8Array(decryptedData);
  14340. let inputPos = 0;
  14341. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  14342. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  14343. }
  14344. return decodedData;
  14345. }
  14346. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  14347. const decodedData = discardEPB(curUnit.data);
  14348. const encryptedData = this.getAvcEncryptedData(decodedData);
  14349. this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {
  14350. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  14351. if (!this.decrypter.isSync()) {
  14352. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  14353. }
  14354. });
  14355. }
  14356. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  14357. if (samples instanceof Uint8Array) {
  14358. throw new Error('Cannot decrypt samples of type Uint8Array');
  14359. }
  14360. for (;; sampleIndex++, unitIndex = 0) {
  14361. if (sampleIndex >= samples.length) {
  14362. callback();
  14363. return;
  14364. }
  14365. const curUnits = samples[sampleIndex].units;
  14366. for (;; unitIndex++) {
  14367. if (unitIndex >= curUnits.length) {
  14368. break;
  14369. }
  14370. const curUnit = curUnits[unitIndex];
  14371. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  14372. continue;
  14373. }
  14374. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  14375. if (!this.decrypter.isSync()) {
  14376. return;
  14377. }
  14378. }
  14379. }
  14380. }
  14381. }
  14382. const PACKET_LENGTH = 188;
  14383. class TSDemuxer {
  14384. constructor(observer, config, typeSupported) {
  14385. this.observer = void 0;
  14386. this.config = void 0;
  14387. this.typeSupported = void 0;
  14388. this.sampleAes = null;
  14389. this.pmtParsed = false;
  14390. this.audioCodec = void 0;
  14391. this.videoCodec = void 0;
  14392. this._duration = 0;
  14393. this._pmtId = -1;
  14394. this._videoTrack = void 0;
  14395. this._audioTrack = void 0;
  14396. this._id3Track = void 0;
  14397. this._txtTrack = void 0;
  14398. this.aacOverFlow = null;
  14399. this.remainderData = null;
  14400. this.videoParser = void 0;
  14401. this.observer = observer;
  14402. this.config = config;
  14403. this.typeSupported = typeSupported;
  14404. this.videoParser = new AvcVideoParser();
  14405. }
  14406. static probe(data) {
  14407. const syncOffset = TSDemuxer.syncOffset(data);
  14408. if (syncOffset > 0) {
  14409. logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  14410. }
  14411. return syncOffset !== -1;
  14412. }
  14413. static syncOffset(data) {
  14414. const length = data.length;
  14415. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  14416. let i = 0;
  14417. while (i < scanwindow) {
  14418. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  14419. let foundPat = false;
  14420. let packetStart = -1;
  14421. let tsPackets = 0;
  14422. for (let j = i; j < length; j += PACKET_LENGTH) {
  14423. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  14424. tsPackets++;
  14425. if (packetStart === -1) {
  14426. packetStart = j;
  14427. // First sync word found at offset, increase scan length (#5251)
  14428. if (packetStart !== 0) {
  14429. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  14430. }
  14431. }
  14432. if (!foundPat) {
  14433. foundPat = parsePID(data, j) === 0;
  14434. }
  14435. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  14436. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  14437. return packetStart;
  14438. }
  14439. } else if (tsPackets) {
  14440. // Exit if sync word found, but does not contain contiguous packets
  14441. return -1;
  14442. } else {
  14443. break;
  14444. }
  14445. }
  14446. i++;
  14447. }
  14448. return -1;
  14449. }
  14450. /**
  14451. * Creates a track model internal to demuxer used to drive remuxing input
  14452. */
  14453. static createTrack(type, duration) {
  14454. return {
  14455. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  14456. type,
  14457. id: RemuxerTrackIdConfig[type],
  14458. pid: -1,
  14459. inputTimeScale: 90000,
  14460. sequenceNumber: 0,
  14461. samples: [],
  14462. dropped: 0,
  14463. duration: type === 'audio' ? duration : undefined
  14464. };
  14465. }
  14466. /**
  14467. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  14468. * Resets all internal track instances of the demuxer.
  14469. */
  14470. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14471. this.pmtParsed = false;
  14472. this._pmtId = -1;
  14473. this._videoTrack = TSDemuxer.createTrack('video');
  14474. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  14475. this._id3Track = TSDemuxer.createTrack('id3');
  14476. this._txtTrack = TSDemuxer.createTrack('text');
  14477. this._audioTrack.segmentCodec = 'aac';
  14478. // flush any partial content
  14479. this.aacOverFlow = null;
  14480. this.remainderData = null;
  14481. this.audioCodec = audioCodec;
  14482. this.videoCodec = videoCodec;
  14483. this._duration = trackDuration;
  14484. }
  14485. resetTimeStamp() {}
  14486. resetContiguity() {
  14487. const {
  14488. _audioTrack,
  14489. _videoTrack,
  14490. _id3Track
  14491. } = this;
  14492. if (_audioTrack) {
  14493. _audioTrack.pesData = null;
  14494. }
  14495. if (_videoTrack) {
  14496. _videoTrack.pesData = null;
  14497. }
  14498. if (_id3Track) {
  14499. _id3Track.pesData = null;
  14500. }
  14501. this.aacOverFlow = null;
  14502. this.remainderData = null;
  14503. }
  14504. demux(data, timeOffset, isSampleAes = false, flush = false) {
  14505. if (!isSampleAes) {
  14506. this.sampleAes = null;
  14507. }
  14508. let pes;
  14509. const videoTrack = this._videoTrack;
  14510. const audioTrack = this._audioTrack;
  14511. const id3Track = this._id3Track;
  14512. const textTrack = this._txtTrack;
  14513. let videoPid = videoTrack.pid;
  14514. let videoData = videoTrack.pesData;
  14515. let audioPid = audioTrack.pid;
  14516. let id3Pid = id3Track.pid;
  14517. let audioData = audioTrack.pesData;
  14518. let id3Data = id3Track.pesData;
  14519. let unknownPID = null;
  14520. let pmtParsed = this.pmtParsed;
  14521. let pmtId = this._pmtId;
  14522. let len = data.length;
  14523. if (this.remainderData) {
  14524. data = appendUint8Array(this.remainderData, data);
  14525. len = data.length;
  14526. this.remainderData = null;
  14527. }
  14528. if (len < PACKET_LENGTH && !flush) {
  14529. this.remainderData = data;
  14530. return {
  14531. audioTrack,
  14532. videoTrack,
  14533. id3Track,
  14534. textTrack
  14535. };
  14536. }
  14537. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  14538. len -= (len - syncOffset) % PACKET_LENGTH;
  14539. if (len < data.byteLength && !flush) {
  14540. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  14541. }
  14542. // loop through TS packets
  14543. let tsPacketErrors = 0;
  14544. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  14545. if (data[start] === 0x47) {
  14546. const stt = !!(data[start + 1] & 0x40);
  14547. const pid = parsePID(data, start);
  14548. const atf = (data[start + 3] & 0x30) >> 4;
  14549. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  14550. let offset;
  14551. if (atf > 1) {
  14552. offset = start + 5 + data[start + 4];
  14553. // continue if there is only adaptation field
  14554. if (offset === start + PACKET_LENGTH) {
  14555. continue;
  14556. }
  14557. } else {
  14558. offset = start + 4;
  14559. }
  14560. switch (pid) {
  14561. case videoPid:
  14562. if (stt) {
  14563. if (videoData && (pes = parsePES(videoData))) {
  14564. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration);
  14565. }
  14566. videoData = {
  14567. data: [],
  14568. size: 0
  14569. };
  14570. }
  14571. if (videoData) {
  14572. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14573. videoData.size += start + PACKET_LENGTH - offset;
  14574. }
  14575. break;
  14576. case audioPid:
  14577. if (stt) {
  14578. if (audioData && (pes = parsePES(audioData))) {
  14579. switch (audioTrack.segmentCodec) {
  14580. case 'aac':
  14581. this.parseAACPES(audioTrack, pes);
  14582. break;
  14583. case 'mp3':
  14584. this.parseMPEGPES(audioTrack, pes);
  14585. break;
  14586. }
  14587. }
  14588. audioData = {
  14589. data: [],
  14590. size: 0
  14591. };
  14592. }
  14593. if (audioData) {
  14594. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14595. audioData.size += start + PACKET_LENGTH - offset;
  14596. }
  14597. break;
  14598. case id3Pid:
  14599. if (stt) {
  14600. if (id3Data && (pes = parsePES(id3Data))) {
  14601. this.parseID3PES(id3Track, pes);
  14602. }
  14603. id3Data = {
  14604. data: [],
  14605. size: 0
  14606. };
  14607. }
  14608. if (id3Data) {
  14609. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14610. id3Data.size += start + PACKET_LENGTH - offset;
  14611. }
  14612. break;
  14613. case 0:
  14614. if (stt) {
  14615. offset += data[offset] + 1;
  14616. }
  14617. pmtId = this._pmtId = parsePAT(data, offset);
  14618. // logger.log('PMT PID:' + this._pmtId);
  14619. break;
  14620. case pmtId:
  14621. {
  14622. if (stt) {
  14623. offset += data[offset] + 1;
  14624. }
  14625. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer);
  14626. // only update track id if track PID found while parsing PMT
  14627. // this is to avoid resetting the PID to -1 in case
  14628. // track PID transiently disappears from the stream
  14629. // this could happen in case of transient missing audio samples for example
  14630. // NOTE this is only the PID of the track as found in TS,
  14631. // but we are not using this for MP4 track IDs.
  14632. videoPid = parsedPIDs.videoPid;
  14633. if (videoPid > 0) {
  14634. videoTrack.pid = videoPid;
  14635. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  14636. }
  14637. audioPid = parsedPIDs.audioPid;
  14638. if (audioPid > 0) {
  14639. audioTrack.pid = audioPid;
  14640. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  14641. }
  14642. id3Pid = parsedPIDs.id3Pid;
  14643. if (id3Pid > 0) {
  14644. id3Track.pid = id3Pid;
  14645. }
  14646. if (unknownPID !== null && !pmtParsed) {
  14647. logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  14648. unknownPID = null;
  14649. // we set it to -188, the += 188 in the for loop will reset start to 0
  14650. start = syncOffset - 188;
  14651. }
  14652. pmtParsed = this.pmtParsed = true;
  14653. break;
  14654. }
  14655. case 0x11:
  14656. case 0x1fff:
  14657. break;
  14658. default:
  14659. unknownPID = pid;
  14660. break;
  14661. }
  14662. } else {
  14663. tsPacketErrors++;
  14664. }
  14665. }
  14666. if (tsPacketErrors > 0) {
  14667. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`));
  14668. }
  14669. videoTrack.pesData = videoData;
  14670. audioTrack.pesData = audioData;
  14671. id3Track.pesData = id3Data;
  14672. const demuxResult = {
  14673. audioTrack,
  14674. videoTrack,
  14675. id3Track,
  14676. textTrack
  14677. };
  14678. if (flush) {
  14679. this.extractRemainingSamples(demuxResult);
  14680. }
  14681. return demuxResult;
  14682. }
  14683. flush() {
  14684. const {
  14685. remainderData
  14686. } = this;
  14687. this.remainderData = null;
  14688. let result;
  14689. if (remainderData) {
  14690. result = this.demux(remainderData, -1, false, true);
  14691. } else {
  14692. result = {
  14693. videoTrack: this._videoTrack,
  14694. audioTrack: this._audioTrack,
  14695. id3Track: this._id3Track,
  14696. textTrack: this._txtTrack
  14697. };
  14698. }
  14699. this.extractRemainingSamples(result);
  14700. if (this.sampleAes) {
  14701. return this.decrypt(result, this.sampleAes);
  14702. }
  14703. return result;
  14704. }
  14705. extractRemainingSamples(demuxResult) {
  14706. const {
  14707. audioTrack,
  14708. videoTrack,
  14709. id3Track,
  14710. textTrack
  14711. } = demuxResult;
  14712. const videoData = videoTrack.pesData;
  14713. const audioData = audioTrack.pesData;
  14714. const id3Data = id3Track.pesData;
  14715. // try to parse last PES packets
  14716. let pes;
  14717. if (videoData && (pes = parsePES(videoData))) {
  14718. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration);
  14719. videoTrack.pesData = null;
  14720. } else {
  14721. // either avcData null or PES truncated, keep it for next frag parsing
  14722. videoTrack.pesData = videoData;
  14723. }
  14724. if (audioData && (pes = parsePES(audioData))) {
  14725. switch (audioTrack.segmentCodec) {
  14726. case 'aac':
  14727. this.parseAACPES(audioTrack, pes);
  14728. break;
  14729. case 'mp3':
  14730. this.parseMPEGPES(audioTrack, pes);
  14731. break;
  14732. }
  14733. audioTrack.pesData = null;
  14734. } else {
  14735. if (audioData != null && audioData.size) {
  14736. logger.log('last AAC PES packet truncated,might overlap between fragments');
  14737. }
  14738. // either audioData null or PES truncated, keep it for next frag parsing
  14739. audioTrack.pesData = audioData;
  14740. }
  14741. if (id3Data && (pes = parsePES(id3Data))) {
  14742. this.parseID3PES(id3Track, pes);
  14743. id3Track.pesData = null;
  14744. } else {
  14745. // either id3Data null or PES truncated, keep it for next frag parsing
  14746. id3Track.pesData = id3Data;
  14747. }
  14748. }
  14749. demuxSampleAes(data, keyData, timeOffset) {
  14750. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  14751. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  14752. return this.decrypt(demuxResult, sampleAes);
  14753. }
  14754. decrypt(demuxResult, sampleAes) {
  14755. return new Promise(resolve => {
  14756. const {
  14757. audioTrack,
  14758. videoTrack
  14759. } = demuxResult;
  14760. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  14761. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  14762. if (videoTrack.samples) {
  14763. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  14764. resolve(demuxResult);
  14765. });
  14766. } else {
  14767. resolve(demuxResult);
  14768. }
  14769. });
  14770. } else if (videoTrack.samples) {
  14771. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  14772. resolve(demuxResult);
  14773. });
  14774. }
  14775. });
  14776. }
  14777. destroy() {
  14778. this._duration = 0;
  14779. }
  14780. parseAACPES(track, pes) {
  14781. let startOffset = 0;
  14782. const aacOverFlow = this.aacOverFlow;
  14783. let data = pes.data;
  14784. if (aacOverFlow) {
  14785. this.aacOverFlow = null;
  14786. const frameMissingBytes = aacOverFlow.missing;
  14787. const sampleLength = aacOverFlow.sample.unit.byteLength;
  14788. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  14789. if (frameMissingBytes === -1) {
  14790. data = appendUint8Array(aacOverFlow.sample.unit, data);
  14791. } else {
  14792. const frameOverflowBytes = sampleLength - frameMissingBytes;
  14793. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  14794. track.samples.push(aacOverFlow.sample);
  14795. startOffset = aacOverFlow.missing;
  14796. }
  14797. }
  14798. // look for ADTS header (0xFFFx)
  14799. let offset;
  14800. let len;
  14801. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  14802. if (isHeader$1(data, offset)) {
  14803. break;
  14804. }
  14805. }
  14806. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  14807. if (offset !== startOffset) {
  14808. let reason;
  14809. const recoverable = offset < len - 1;
  14810. if (recoverable) {
  14811. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  14812. } else {
  14813. reason = 'No ADTS header found in AAC PES';
  14814. }
  14815. emitParsingError(this.observer, new Error(reason), recoverable);
  14816. if (!recoverable) {
  14817. return;
  14818. }
  14819. }
  14820. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  14821. let pts;
  14822. if (pes.pts !== undefined) {
  14823. pts = pes.pts;
  14824. } else if (aacOverFlow) {
  14825. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  14826. // first sample PTS should be equal to last sample PTS + frameDuration
  14827. const frameDuration = getFrameDuration(track.samplerate);
  14828. pts = aacOverFlow.sample.pts + frameDuration;
  14829. } else {
  14830. logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  14831. return;
  14832. }
  14833. // scan for aac samples
  14834. let frameIndex = 0;
  14835. let frame;
  14836. while (offset < len) {
  14837. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  14838. offset += frame.length;
  14839. if (!frame.missing) {
  14840. frameIndex++;
  14841. for (; offset < len - 1; offset++) {
  14842. if (isHeader$1(data, offset)) {
  14843. break;
  14844. }
  14845. }
  14846. } else {
  14847. this.aacOverFlow = frame;
  14848. break;
  14849. }
  14850. }
  14851. }
  14852. parseMPEGPES(track, pes) {
  14853. const data = pes.data;
  14854. const length = data.length;
  14855. let frameIndex = 0;
  14856. let offset = 0;
  14857. const pts = pes.pts;
  14858. if (pts === undefined) {
  14859. logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  14860. return;
  14861. }
  14862. while (offset < length) {
  14863. if (isHeader(data, offset)) {
  14864. const frame = appendFrame(track, data, offset, pts, frameIndex);
  14865. if (frame) {
  14866. offset += frame.length;
  14867. frameIndex++;
  14868. } else {
  14869. // logger.log('Unable to parse Mpeg audio frame');
  14870. break;
  14871. }
  14872. } else {
  14873. // nothing found, keep looking
  14874. offset++;
  14875. }
  14876. }
  14877. }
  14878. parseAC3PES(track, pes) {
  14879. }
  14880. parseID3PES(id3Track, pes) {
  14881. if (pes.pts === undefined) {
  14882. logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  14883. return;
  14884. }
  14885. const id3Sample = _extends({}, pes, {
  14886. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  14887. duration: Number.POSITIVE_INFINITY
  14888. });
  14889. id3Track.samples.push(id3Sample);
  14890. }
  14891. }
  14892. function parsePID(data, offset) {
  14893. // pid is a 13-bit field starting at the last bit of TS[1]
  14894. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  14895. }
  14896. function parsePAT(data, offset) {
  14897. // skip the PSI header and parse the first PMT entry
  14898. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  14899. }
  14900. function parsePMT(data, offset, typeSupported, isSampleAes, observer) {
  14901. const result = {
  14902. audioPid: -1,
  14903. videoPid: -1,
  14904. id3Pid: -1,
  14905. segmentVideoCodec: 'avc',
  14906. segmentAudioCodec: 'aac'
  14907. };
  14908. const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  14909. const tableEnd = offset + 3 + sectionLength - 4;
  14910. // to determine where the table is, we have to figure out how
  14911. // long the program info descriptors are
  14912. const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  14913. // advance the offset to the first entry in the mapping table
  14914. offset += 12 + programInfoLength;
  14915. while (offset < tableEnd) {
  14916. const pid = parsePID(data, offset);
  14917. const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  14918. switch (data[offset]) {
  14919. case 0xcf:
  14920. // SAMPLE-AES AAC
  14921. if (!isSampleAes) {
  14922. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');
  14923. break;
  14924. }
  14925. /* falls through */
  14926. case 0x0f:
  14927. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  14928. // logger.log('AAC PID:' + pid);
  14929. if (result.audioPid === -1) {
  14930. result.audioPid = pid;
  14931. }
  14932. break;
  14933. // Packetized metadata (ID3)
  14934. case 0x15:
  14935. // logger.log('ID3 PID:' + pid);
  14936. if (result.id3Pid === -1) {
  14937. result.id3Pid = pid;
  14938. }
  14939. break;
  14940. case 0xdb:
  14941. // SAMPLE-AES AVC
  14942. if (!isSampleAes) {
  14943. logEncryptedSamplesFoundInUnencryptedStream('H.264');
  14944. break;
  14945. }
  14946. /* falls through */
  14947. case 0x1b:
  14948. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  14949. // logger.log('AVC PID:' + pid);
  14950. if (result.videoPid === -1) {
  14951. result.videoPid = pid;
  14952. result.segmentVideoCodec = 'avc';
  14953. }
  14954. break;
  14955. // ISO/IEC 11172-3 (MPEG-1 audio)
  14956. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  14957. case 0x03:
  14958. case 0x04:
  14959. // logger.log('MPEG PID:' + pid);
  14960. if (!typeSupported.mpeg && !typeSupported.mp3) {
  14961. logger.log('MPEG audio found, not supported in this browser');
  14962. } else if (result.audioPid === -1) {
  14963. result.audioPid = pid;
  14964. result.segmentAudioCodec = 'mp3';
  14965. }
  14966. break;
  14967. case 0xc1:
  14968. // SAMPLE-AES AC3
  14969. if (!isSampleAes) {
  14970. logEncryptedSamplesFoundInUnencryptedStream('AC-3');
  14971. break;
  14972. }
  14973. /* falls through */
  14974. case 0x81:
  14975. {
  14976. logger.warn('AC-3 in M2TS support not included in build');
  14977. }
  14978. break;
  14979. case 0x06:
  14980. // stream_type 6 can mean a lot of different things in case of DVB.
  14981. // We need to look at the descriptors. Right now, we're only interested
  14982. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  14983. // an audio PID yet.
  14984. if (result.audioPid === -1 && esInfoLength > 0) {
  14985. let parsePos = offset + 5;
  14986. let remaining = esInfoLength;
  14987. while (remaining > 2) {
  14988. const descriptorId = data[parsePos];
  14989. switch (descriptorId) {
  14990. case 0x6a:
  14991. // DVB Descriptor for AC-3
  14992. {
  14993. logger.warn('AC-3 in M2TS support not included in build');
  14994. }
  14995. break;
  14996. }
  14997. const descriptorLen = data[parsePos + 1] + 2;
  14998. parsePos += descriptorLen;
  14999. remaining -= descriptorLen;
  15000. }
  15001. }
  15002. break;
  15003. case 0xc2: // SAMPLE-AES EC3
  15004. /* falls through */
  15005. case 0x87:
  15006. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));
  15007. return result;
  15008. case 0x24:
  15009. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));
  15010. return result;
  15011. }
  15012. // move to the next table entry
  15013. // skip past the elementary stream descriptors, if present
  15014. offset += esInfoLength + 5;
  15015. }
  15016. return result;
  15017. }
  15018. function emitParsingError(observer, error, levelRetry) {
  15019. logger.warn(`parsing error: ${error.message}`);
  15020. observer.emit(Events.ERROR, Events.ERROR, {
  15021. type: ErrorTypes.MEDIA_ERROR,
  15022. details: ErrorDetails.FRAG_PARSING_ERROR,
  15023. fatal: false,
  15024. levelRetry,
  15025. error,
  15026. reason: error.message
  15027. });
  15028. }
  15029. function logEncryptedSamplesFoundInUnencryptedStream(type) {
  15030. logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  15031. }
  15032. function parsePES(stream) {
  15033. let i = 0;
  15034. let frag;
  15035. let pesLen;
  15036. let pesHdrLen;
  15037. let pesPts;
  15038. let pesDts;
  15039. const data = stream.data;
  15040. // safety check
  15041. if (!stream || stream.size === 0) {
  15042. return null;
  15043. }
  15044. // we might need up to 19 bytes to read PES header
  15045. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  15046. // usually only one merge is needed (and this is rare ...)
  15047. while (data[0].length < 19 && data.length > 1) {
  15048. data[0] = appendUint8Array(data[0], data[1]);
  15049. data.splice(1, 1);
  15050. }
  15051. // retrieve PTS/DTS from first fragment
  15052. frag = data[0];
  15053. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  15054. if (pesPrefix === 1) {
  15055. pesLen = (frag[4] << 8) + frag[5];
  15056. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  15057. // minus 6 : PES header size
  15058. if (pesLen && pesLen > stream.size - 6) {
  15059. return null;
  15060. }
  15061. const pesFlags = frag[7];
  15062. if (pesFlags & 0xc0) {
  15063. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  15064. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  15065. as Bitwise operators treat their operands as a sequence of 32 bits */
  15066. pesPts = (frag[9] & 0x0e) * 536870912 +
  15067. // 1 << 29
  15068. (frag[10] & 0xff) * 4194304 +
  15069. // 1 << 22
  15070. (frag[11] & 0xfe) * 16384 +
  15071. // 1 << 14
  15072. (frag[12] & 0xff) * 128 +
  15073. // 1 << 7
  15074. (frag[13] & 0xfe) / 2;
  15075. if (pesFlags & 0x40) {
  15076. pesDts = (frag[14] & 0x0e) * 536870912 +
  15077. // 1 << 29
  15078. (frag[15] & 0xff) * 4194304 +
  15079. // 1 << 22
  15080. (frag[16] & 0xfe) * 16384 +
  15081. // 1 << 14
  15082. (frag[17] & 0xff) * 128 +
  15083. // 1 << 7
  15084. (frag[18] & 0xfe) / 2;
  15085. if (pesPts - pesDts > 60 * 90000) {
  15086. logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);
  15087. pesPts = pesDts;
  15088. }
  15089. } else {
  15090. pesDts = pesPts;
  15091. }
  15092. }
  15093. pesHdrLen = frag[8];
  15094. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  15095. let payloadStartOffset = pesHdrLen + 9;
  15096. if (stream.size <= payloadStartOffset) {
  15097. return null;
  15098. }
  15099. stream.size -= payloadStartOffset;
  15100. // reassemble PES packet
  15101. const pesData = new Uint8Array(stream.size);
  15102. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  15103. frag = data[j];
  15104. let len = frag.byteLength;
  15105. if (payloadStartOffset) {
  15106. if (payloadStartOffset > len) {
  15107. // trim full frag if PES header bigger than frag
  15108. payloadStartOffset -= len;
  15109. continue;
  15110. } else {
  15111. // trim partial frag if PES header smaller than frag
  15112. frag = frag.subarray(payloadStartOffset);
  15113. len -= payloadStartOffset;
  15114. payloadStartOffset = 0;
  15115. }
  15116. }
  15117. pesData.set(frag, i);
  15118. i += len;
  15119. }
  15120. if (pesLen) {
  15121. // payload size : remove PES header + PES extension
  15122. pesLen -= pesHdrLen + 3;
  15123. }
  15124. return {
  15125. data: pesData,
  15126. pts: pesPts,
  15127. dts: pesDts,
  15128. len: pesLen
  15129. };
  15130. }
  15131. return null;
  15132. }
  15133. /**
  15134. * MP3 demuxer
  15135. */
  15136. class MP3Demuxer extends BaseAudioDemuxer {
  15137. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  15138. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  15139. this._audioTrack = {
  15140. container: 'audio/mpeg',
  15141. type: 'audio',
  15142. id: 2,
  15143. pid: -1,
  15144. sequenceNumber: 0,
  15145. segmentCodec: 'mp3',
  15146. samples: [],
  15147. manifestCodec: audioCodec,
  15148. duration: trackDuration,
  15149. inputTimeScale: 90000,
  15150. dropped: 0
  15151. };
  15152. }
  15153. static probe(data) {
  15154. if (!data) {
  15155. return false;
  15156. }
  15157. // check if data contains ID3 timestamp and MPEG sync word
  15158. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  15159. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  15160. // More info http://www.mp3-tech.org/programmer/frame_header.html
  15161. const id3Data = getID3Data(data, 0);
  15162. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  15163. // Check for ac-3|ec-3 sync bytes and return false if present
  15164. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  15165. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  15166. getAudioBSID(data, offset) <= 16) {
  15167. return false;
  15168. }
  15169. for (let length = data.length; offset < length; offset++) {
  15170. if (probe(data, offset)) {
  15171. logger.log('MPEG Audio sync word found !');
  15172. return true;
  15173. }
  15174. }
  15175. return false;
  15176. }
  15177. canParse(data, offset) {
  15178. return canParse(data, offset);
  15179. }
  15180. appendFrame(track, data, offset) {
  15181. if (this.basePTS === null) {
  15182. return;
  15183. }
  15184. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  15185. }
  15186. }
  15187. /**
  15188. * AAC helper
  15189. */
  15190. class AAC {
  15191. static getSilentFrame(codec, channelCount) {
  15192. switch (codec) {
  15193. case 'mp4a.40.2':
  15194. if (channelCount === 1) {
  15195. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  15196. } else if (channelCount === 2) {
  15197. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  15198. } else if (channelCount === 3) {
  15199. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  15200. } else if (channelCount === 4) {
  15201. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  15202. } else if (channelCount === 5) {
  15203. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  15204. } else if (channelCount === 6) {
  15205. 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]);
  15206. }
  15207. break;
  15208. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  15209. default:
  15210. if (channelCount === 1) {
  15211. // 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
  15212. 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]);
  15213. } else if (channelCount === 2) {
  15214. // 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
  15215. 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]);
  15216. } else if (channelCount === 3) {
  15217. // 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
  15218. 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]);
  15219. }
  15220. break;
  15221. }
  15222. return undefined;
  15223. }
  15224. }
  15225. /**
  15226. * Generate MP4 Box
  15227. */
  15228. const UINT32_MAX = Math.pow(2, 32) - 1;
  15229. class MP4 {
  15230. static init() {
  15231. MP4.types = {
  15232. avc1: [],
  15233. // codingname
  15234. avcC: [],
  15235. btrt: [],
  15236. dinf: [],
  15237. dref: [],
  15238. esds: [],
  15239. ftyp: [],
  15240. hdlr: [],
  15241. mdat: [],
  15242. mdhd: [],
  15243. mdia: [],
  15244. mfhd: [],
  15245. minf: [],
  15246. moof: [],
  15247. moov: [],
  15248. mp4a: [],
  15249. '.mp3': [],
  15250. dac3: [],
  15251. 'ac-3': [],
  15252. mvex: [],
  15253. mvhd: [],
  15254. pasp: [],
  15255. sdtp: [],
  15256. stbl: [],
  15257. stco: [],
  15258. stsc: [],
  15259. stsd: [],
  15260. stsz: [],
  15261. stts: [],
  15262. tfdt: [],
  15263. tfhd: [],
  15264. traf: [],
  15265. trak: [],
  15266. trun: [],
  15267. trex: [],
  15268. tkhd: [],
  15269. vmhd: [],
  15270. smhd: []
  15271. };
  15272. let i;
  15273. for (i in MP4.types) {
  15274. if (MP4.types.hasOwnProperty(i)) {
  15275. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  15276. }
  15277. }
  15278. const videoHdlr = new Uint8Array([0x00,
  15279. // version 0
  15280. 0x00, 0x00, 0x00,
  15281. // flags
  15282. 0x00, 0x00, 0x00, 0x00,
  15283. // pre_defined
  15284. 0x76, 0x69, 0x64, 0x65,
  15285. // handler_type: 'vide'
  15286. 0x00, 0x00, 0x00, 0x00,
  15287. // reserved
  15288. 0x00, 0x00, 0x00, 0x00,
  15289. // reserved
  15290. 0x00, 0x00, 0x00, 0x00,
  15291. // reserved
  15292. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  15293. ]);
  15294. const audioHdlr = new Uint8Array([0x00,
  15295. // version 0
  15296. 0x00, 0x00, 0x00,
  15297. // flags
  15298. 0x00, 0x00, 0x00, 0x00,
  15299. // pre_defined
  15300. 0x73, 0x6f, 0x75, 0x6e,
  15301. // handler_type: 'soun'
  15302. 0x00, 0x00, 0x00, 0x00,
  15303. // reserved
  15304. 0x00, 0x00, 0x00, 0x00,
  15305. // reserved
  15306. 0x00, 0x00, 0x00, 0x00,
  15307. // reserved
  15308. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  15309. ]);
  15310. MP4.HDLR_TYPES = {
  15311. video: videoHdlr,
  15312. audio: audioHdlr
  15313. };
  15314. const dref = new Uint8Array([0x00,
  15315. // version 0
  15316. 0x00, 0x00, 0x00,
  15317. // flags
  15318. 0x00, 0x00, 0x00, 0x01,
  15319. // entry_count
  15320. 0x00, 0x00, 0x00, 0x0c,
  15321. // entry_size
  15322. 0x75, 0x72, 0x6c, 0x20,
  15323. // 'url' type
  15324. 0x00,
  15325. // version 0
  15326. 0x00, 0x00, 0x01 // entry_flags
  15327. ]);
  15328. const stco = new Uint8Array([0x00,
  15329. // version
  15330. 0x00, 0x00, 0x00,
  15331. // flags
  15332. 0x00, 0x00, 0x00, 0x00 // entry_count
  15333. ]);
  15334. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  15335. MP4.STSZ = new Uint8Array([0x00,
  15336. // version
  15337. 0x00, 0x00, 0x00,
  15338. // flags
  15339. 0x00, 0x00, 0x00, 0x00,
  15340. // sample_size
  15341. 0x00, 0x00, 0x00, 0x00 // sample_count
  15342. ]);
  15343. MP4.VMHD = new Uint8Array([0x00,
  15344. // version
  15345. 0x00, 0x00, 0x01,
  15346. // flags
  15347. 0x00, 0x00,
  15348. // graphicsmode
  15349. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  15350. ]);
  15351. MP4.SMHD = new Uint8Array([0x00,
  15352. // version
  15353. 0x00, 0x00, 0x00,
  15354. // flags
  15355. 0x00, 0x00,
  15356. // balance
  15357. 0x00, 0x00 // reserved
  15358. ]);
  15359. MP4.STSD = new Uint8Array([0x00,
  15360. // version 0
  15361. 0x00, 0x00, 0x00,
  15362. // flags
  15363. 0x00, 0x00, 0x00, 0x01]); // entry_count
  15364. const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  15365. const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  15366. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  15367. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  15368. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  15369. }
  15370. static box(type, ...payload) {
  15371. let size = 8;
  15372. let i = payload.length;
  15373. const len = i;
  15374. // calculate the total size we need to allocate
  15375. while (i--) {
  15376. size += payload[i].byteLength;
  15377. }
  15378. const result = new Uint8Array(size);
  15379. result[0] = size >> 24 & 0xff;
  15380. result[1] = size >> 16 & 0xff;
  15381. result[2] = size >> 8 & 0xff;
  15382. result[3] = size & 0xff;
  15383. result.set(type, 4);
  15384. // copy the payload into the result
  15385. for (i = 0, size = 8; i < len; i++) {
  15386. // copy payload[i] array @ offset size
  15387. result.set(payload[i], size);
  15388. size += payload[i].byteLength;
  15389. }
  15390. return result;
  15391. }
  15392. static hdlr(type) {
  15393. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  15394. }
  15395. static mdat(data) {
  15396. return MP4.box(MP4.types.mdat, data);
  15397. }
  15398. static mdhd(timescale, duration) {
  15399. duration *= timescale;
  15400. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15401. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15402. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  15403. // version 1
  15404. 0x00, 0x00, 0x00,
  15405. // flags
  15406. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15407. // creation_time
  15408. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15409. // modification_time
  15410. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15411. // timescale
  15412. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  15413. // 'und' language (undetermined)
  15414. 0x00, 0x00]));
  15415. }
  15416. static mdia(track) {
  15417. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  15418. }
  15419. static mfhd(sequenceNumber) {
  15420. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  15421. // flags
  15422. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  15423. ]));
  15424. }
  15425. static minf(track) {
  15426. if (track.type === 'audio') {
  15427. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  15428. } else {
  15429. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  15430. }
  15431. }
  15432. static moof(sn, baseMediaDecodeTime, track) {
  15433. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  15434. }
  15435. static moov(tracks) {
  15436. let i = tracks.length;
  15437. const boxes = [];
  15438. while (i--) {
  15439. boxes[i] = MP4.trak(tracks[i]);
  15440. }
  15441. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  15442. }
  15443. static mvex(tracks) {
  15444. let i = tracks.length;
  15445. const boxes = [];
  15446. while (i--) {
  15447. boxes[i] = MP4.trex(tracks[i]);
  15448. }
  15449. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  15450. }
  15451. static mvhd(timescale, duration) {
  15452. duration *= timescale;
  15453. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15454. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15455. const bytes = new Uint8Array([0x01,
  15456. // version 1
  15457. 0x00, 0x00, 0x00,
  15458. // flags
  15459. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15460. // creation_time
  15461. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15462. // modification_time
  15463. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15464. // timescale
  15465. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  15466. // 1.0 rate
  15467. 0x01, 0x00,
  15468. // 1.0 volume
  15469. 0x00, 0x00,
  15470. // reserved
  15471. 0x00, 0x00, 0x00, 0x00,
  15472. // reserved
  15473. 0x00, 0x00, 0x00, 0x00,
  15474. // reserved
  15475. 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,
  15476. // transformation: unity matrix
  15477. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15478. // pre_defined
  15479. 0xff, 0xff, 0xff, 0xff // next_track_ID
  15480. ]);
  15481. return MP4.box(MP4.types.mvhd, bytes);
  15482. }
  15483. static sdtp(track) {
  15484. const samples = track.samples || [];
  15485. const bytes = new Uint8Array(4 + samples.length);
  15486. let i;
  15487. let flags;
  15488. // leave the full box header (4 bytes) all zero
  15489. // write the sample table
  15490. for (i = 0; i < samples.length; i++) {
  15491. flags = samples[i].flags;
  15492. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  15493. }
  15494. return MP4.box(MP4.types.sdtp, bytes);
  15495. }
  15496. static stbl(track) {
  15497. 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));
  15498. }
  15499. static avc1(track) {
  15500. let sps = [];
  15501. let pps = [];
  15502. let i;
  15503. let data;
  15504. let len;
  15505. // assemble the SPSs
  15506. for (i = 0; i < track.sps.length; i++) {
  15507. data = track.sps[i];
  15508. len = data.byteLength;
  15509. sps.push(len >>> 8 & 0xff);
  15510. sps.push(len & 0xff);
  15511. // SPS
  15512. sps = sps.concat(Array.prototype.slice.call(data));
  15513. }
  15514. // assemble the PPSs
  15515. for (i = 0; i < track.pps.length; i++) {
  15516. data = track.pps[i];
  15517. len = data.byteLength;
  15518. pps.push(len >>> 8 & 0xff);
  15519. pps.push(len & 0xff);
  15520. pps = pps.concat(Array.prototype.slice.call(data));
  15521. }
  15522. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  15523. // version
  15524. sps[3],
  15525. // profile
  15526. sps[4],
  15527. // profile compat
  15528. sps[5],
  15529. // level
  15530. 0xfc | 3,
  15531. // lengthSizeMinusOne, hard-coded to 4 bytes
  15532. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  15533. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  15534. ]).concat(pps))); // "PPS"
  15535. const width = track.width;
  15536. const height = track.height;
  15537. const hSpacing = track.pixelRatio[0];
  15538. const vSpacing = track.pixelRatio[1];
  15539. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  15540. // reserved
  15541. 0x00, 0x00, 0x00,
  15542. // reserved
  15543. 0x00, 0x01,
  15544. // data_reference_index
  15545. 0x00, 0x00,
  15546. // pre_defined
  15547. 0x00, 0x00,
  15548. // reserved
  15549. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15550. // pre_defined
  15551. width >> 8 & 0xff, width & 0xff,
  15552. // width
  15553. height >> 8 & 0xff, height & 0xff,
  15554. // height
  15555. 0x00, 0x48, 0x00, 0x00,
  15556. // horizresolution
  15557. 0x00, 0x48, 0x00, 0x00,
  15558. // vertresolution
  15559. 0x00, 0x00, 0x00, 0x00,
  15560. // reserved
  15561. 0x00, 0x01,
  15562. // frame_count
  15563. 0x12, 0x64, 0x61, 0x69, 0x6c,
  15564. // dailymotion/hls.js
  15565. 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,
  15566. // compressorname
  15567. 0x00, 0x18,
  15568. // depth = 24
  15569. 0x11, 0x11]),
  15570. // pre_defined = -1
  15571. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  15572. // bufferSizeDB
  15573. 0x00, 0x2d, 0xc6, 0xc0,
  15574. // maxBitrate
  15575. 0x00, 0x2d, 0xc6, 0xc0])),
  15576. // avgBitrate
  15577. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  15578. // hSpacing
  15579. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  15580. // vSpacing
  15581. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  15582. }
  15583. static esds(track) {
  15584. const configlen = track.config.length;
  15585. return new Uint8Array([0x00,
  15586. // version 0
  15587. 0x00, 0x00, 0x00,
  15588. // flags
  15589. 0x03,
  15590. // descriptor_type
  15591. 0x17 + configlen,
  15592. // length
  15593. 0x00, 0x01,
  15594. // es_id
  15595. 0x00,
  15596. // stream_priority
  15597. 0x04,
  15598. // descriptor_type
  15599. 0x0f + configlen,
  15600. // length
  15601. 0x40,
  15602. // codec : mpeg4_audio
  15603. 0x15,
  15604. // stream_type
  15605. 0x00, 0x00, 0x00,
  15606. // buffer_size
  15607. 0x00, 0x00, 0x00, 0x00,
  15608. // maxBitrate
  15609. 0x00, 0x00, 0x00, 0x00,
  15610. // avgBitrate
  15611. 0x05 // descriptor_type
  15612. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  15613. }
  15614. static audioStsd(track) {
  15615. const samplerate = track.samplerate;
  15616. return new Uint8Array([0x00, 0x00, 0x00,
  15617. // reserved
  15618. 0x00, 0x00, 0x00,
  15619. // reserved
  15620. 0x00, 0x01,
  15621. // data_reference_index
  15622. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15623. // reserved
  15624. 0x00, track.channelCount,
  15625. // channelcount
  15626. 0x00, 0x10,
  15627. // sampleSize:16bits
  15628. 0x00, 0x00, 0x00, 0x00,
  15629. // reserved2
  15630. samplerate >> 8 & 0xff, samplerate & 0xff,
  15631. //
  15632. 0x00, 0x00]);
  15633. }
  15634. static mp4a(track) {
  15635. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  15636. }
  15637. static mp3(track) {
  15638. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  15639. }
  15640. static ac3(track) {
  15641. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  15642. }
  15643. static stsd(track) {
  15644. if (track.type === 'audio') {
  15645. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  15646. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  15647. }
  15648. if (track.segmentCodec === 'ac3') {
  15649. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  15650. }
  15651. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  15652. } else {
  15653. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  15654. }
  15655. }
  15656. static tkhd(track) {
  15657. const id = track.id;
  15658. const duration = track.duration * track.timescale;
  15659. const width = track.width;
  15660. const height = track.height;
  15661. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15662. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15663. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  15664. // version 1
  15665. 0x00, 0x00, 0x07,
  15666. // flags
  15667. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15668. // creation_time
  15669. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15670. // modification_time
  15671. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  15672. // track_ID
  15673. 0x00, 0x00, 0x00, 0x00,
  15674. // reserved
  15675. 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,
  15676. // reserved
  15677. 0x00, 0x00,
  15678. // layer
  15679. 0x00, 0x00,
  15680. // alternate_group
  15681. 0x00, 0x00,
  15682. // non-audio track volume
  15683. 0x00, 0x00,
  15684. // reserved
  15685. 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,
  15686. // transformation: unity matrix
  15687. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  15688. // width
  15689. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  15690. ]));
  15691. }
  15692. static traf(track, baseMediaDecodeTime) {
  15693. const sampleDependencyTable = MP4.sdtp(track);
  15694. const id = track.id;
  15695. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  15696. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  15697. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  15698. // version 0
  15699. 0x00, 0x00, 0x00,
  15700. // flags
  15701. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  15702. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  15703. // version 1
  15704. 0x00, 0x00, 0x00,
  15705. // flags
  15706. 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 +
  15707. // tfhd
  15708. 20 +
  15709. // tfdt
  15710. 8 +
  15711. // traf header
  15712. 16 +
  15713. // mfhd
  15714. 8 +
  15715. // moof header
  15716. 8),
  15717. // mdat header
  15718. sampleDependencyTable);
  15719. }
  15720. /**
  15721. * Generate a track box.
  15722. * @param track a track definition
  15723. */
  15724. static trak(track) {
  15725. track.duration = track.duration || 0xffffffff;
  15726. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  15727. }
  15728. static trex(track) {
  15729. const id = track.id;
  15730. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  15731. // version 0
  15732. 0x00, 0x00, 0x00,
  15733. // flags
  15734. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  15735. // track_ID
  15736. 0x00, 0x00, 0x00, 0x01,
  15737. // default_sample_description_index
  15738. 0x00, 0x00, 0x00, 0x00,
  15739. // default_sample_duration
  15740. 0x00, 0x00, 0x00, 0x00,
  15741. // default_sample_size
  15742. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  15743. ]));
  15744. }
  15745. static trun(track, offset) {
  15746. const samples = track.samples || [];
  15747. const len = samples.length;
  15748. const arraylen = 12 + 16 * len;
  15749. const array = new Uint8Array(arraylen);
  15750. let i;
  15751. let sample;
  15752. let duration;
  15753. let size;
  15754. let flags;
  15755. let cts;
  15756. offset += 8 + arraylen;
  15757. array.set([track.type === 'video' ? 0x01 : 0x00,
  15758. // version 1 for video with signed-int sample_composition_time_offset
  15759. 0x00, 0x0f, 0x01,
  15760. // flags
  15761. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  15762. // sample_count
  15763. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  15764. ], 0);
  15765. for (i = 0; i < len; i++) {
  15766. sample = samples[i];
  15767. duration = sample.duration;
  15768. size = sample.size;
  15769. flags = sample.flags;
  15770. cts = sample.cts;
  15771. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  15772. // sample_duration
  15773. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  15774. // sample_size
  15775. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  15776. // sample_flags
  15777. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  15778. ], 12 + 16 * i);
  15779. }
  15780. return MP4.box(MP4.types.trun, array);
  15781. }
  15782. static initSegment(tracks) {
  15783. if (!MP4.types) {
  15784. MP4.init();
  15785. }
  15786. const movie = MP4.moov(tracks);
  15787. const result = appendUint8Array(MP4.FTYP, movie);
  15788. return result;
  15789. }
  15790. }
  15791. MP4.types = void 0;
  15792. MP4.HDLR_TYPES = void 0;
  15793. MP4.STTS = void 0;
  15794. MP4.STSC = void 0;
  15795. MP4.STCO = void 0;
  15796. MP4.STSZ = void 0;
  15797. MP4.VMHD = void 0;
  15798. MP4.SMHD = void 0;
  15799. MP4.STSD = void 0;
  15800. MP4.FTYP = void 0;
  15801. MP4.DINF = void 0;
  15802. const MPEG_TS_CLOCK_FREQ_HZ = 90000;
  15803. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  15804. const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  15805. return round ? Math.round(result) : result;
  15806. }
  15807. function toMsFromMpegTsClock(baseTime, round = false) {
  15808. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  15809. }
  15810. const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  15811. const AAC_SAMPLES_PER_FRAME = 1024;
  15812. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  15813. const AC3_SAMPLES_PER_FRAME = 1536;
  15814. let chromeVersion = null;
  15815. let safariWebkitVersion = null;
  15816. class MP4Remuxer {
  15817. constructor(observer, config, typeSupported, vendor = '') {
  15818. this.observer = void 0;
  15819. this.config = void 0;
  15820. this.typeSupported = void 0;
  15821. this.ISGenerated = false;
  15822. this._initPTS = null;
  15823. this._initDTS = null;
  15824. this.nextAvcDts = null;
  15825. this.nextAudioPts = null;
  15826. this.videoSampleDuration = null;
  15827. this.isAudioContiguous = false;
  15828. this.isVideoContiguous = false;
  15829. this.videoTrackConfig = void 0;
  15830. this.observer = observer;
  15831. this.config = config;
  15832. this.typeSupported = typeSupported;
  15833. this.ISGenerated = false;
  15834. if (chromeVersion === null) {
  15835. const userAgent = navigator.userAgent || '';
  15836. const result = userAgent.match(/Chrome\/(\d+)/i);
  15837. chromeVersion = result ? parseInt(result[1]) : 0;
  15838. }
  15839. if (safariWebkitVersion === null) {
  15840. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  15841. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  15842. }
  15843. }
  15844. destroy() {
  15845. // @ts-ignore
  15846. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  15847. }
  15848. resetTimeStamp(defaultTimeStamp) {
  15849. logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  15850. this._initPTS = this._initDTS = defaultTimeStamp;
  15851. }
  15852. resetNextTimestamp() {
  15853. logger.log('[mp4-remuxer]: reset next timestamp');
  15854. this.isVideoContiguous = false;
  15855. this.isAudioContiguous = false;
  15856. }
  15857. resetInitSegment() {
  15858. logger.log('[mp4-remuxer]: ISGenerated flag reset');
  15859. this.ISGenerated = false;
  15860. this.videoTrackConfig = undefined;
  15861. }
  15862. getVideoStartPts(videoSamples) {
  15863. let rolloverDetected = false;
  15864. const startPTS = videoSamples.reduce((minPTS, sample) => {
  15865. const delta = sample.pts - minPTS;
  15866. if (delta < -4294967296) {
  15867. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  15868. rolloverDetected = true;
  15869. return normalizePts(minPTS, sample.pts);
  15870. } else if (delta > 0) {
  15871. return minPTS;
  15872. } else {
  15873. return sample.pts;
  15874. }
  15875. }, videoSamples[0].pts);
  15876. if (rolloverDetected) {
  15877. logger.debug('PTS rollover detected');
  15878. }
  15879. return startPTS;
  15880. }
  15881. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  15882. let video;
  15883. let audio;
  15884. let initSegment;
  15885. let text;
  15886. let id3;
  15887. let independent;
  15888. let audioTimeOffset = timeOffset;
  15889. let videoTimeOffset = timeOffset;
  15890. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  15891. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  15892. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  15893. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  15894. // then we can remux one track without waiting for the other.
  15895. const hasAudio = audioTrack.pid > -1;
  15896. const hasVideo = videoTrack.pid > -1;
  15897. const length = videoTrack.samples.length;
  15898. const enoughAudioSamples = audioTrack.samples.length > 0;
  15899. const enoughVideoSamples = flush && length > 0 || length > 1;
  15900. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  15901. if (canRemuxAvc) {
  15902. if (this.ISGenerated) {
  15903. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  15904. const config = this.videoTrackConfig;
  15905. 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]))) {
  15906. this.resetInitSegment();
  15907. }
  15908. } else {
  15909. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15910. }
  15911. const isVideoContiguous = this.isVideoContiguous;
  15912. let firstKeyFrameIndex = -1;
  15913. let firstKeyFramePTS;
  15914. if (enoughVideoSamples) {
  15915. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  15916. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  15917. independent = true;
  15918. if (firstKeyFrameIndex > 0) {
  15919. logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  15920. const startPTS = this.getVideoStartPts(videoTrack.samples);
  15921. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  15922. videoTrack.dropped += firstKeyFrameIndex;
  15923. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  15924. firstKeyFramePTS = videoTimeOffset;
  15925. } else if (firstKeyFrameIndex === -1) {
  15926. logger.warn(`[mp4-remuxer]: No keyframe found out of ${length} video samples`);
  15927. independent = false;
  15928. }
  15929. }
  15930. }
  15931. if (this.ISGenerated) {
  15932. if (enoughAudioSamples && enoughVideoSamples) {
  15933. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  15934. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  15935. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  15936. // drift between audio and video streams
  15937. const startPTS = this.getVideoStartPts(videoTrack.samples);
  15938. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  15939. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  15940. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  15941. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  15942. }
  15943. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  15944. if (enoughAudioSamples) {
  15945. // if initSegment was generated without audio samples, regenerate it again
  15946. if (!audioTrack.samplerate) {
  15947. logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  15948. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15949. }
  15950. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  15951. if (enoughVideoSamples) {
  15952. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  15953. // if initSegment was generated without video samples, regenerate it again
  15954. if (!videoTrack.inputTimeScale) {
  15955. logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  15956. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  15957. }
  15958. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  15959. }
  15960. } else if (enoughVideoSamples) {
  15961. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  15962. }
  15963. if (video) {
  15964. video.firstKeyFrame = firstKeyFrameIndex;
  15965. video.independent = firstKeyFrameIndex !== -1;
  15966. video.firstKeyFramePTS = firstKeyFramePTS;
  15967. }
  15968. }
  15969. }
  15970. // Allow ID3 and text to remux, even if more audio/video samples are required
  15971. if (this.ISGenerated && this._initPTS && this._initDTS) {
  15972. if (id3Track.samples.length) {
  15973. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  15974. }
  15975. if (textTrack.samples.length) {
  15976. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  15977. }
  15978. }
  15979. return {
  15980. audio,
  15981. video,
  15982. initSegment,
  15983. independent,
  15984. text,
  15985. id3
  15986. };
  15987. }
  15988. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  15989. const audioSamples = audioTrack.samples;
  15990. const videoSamples = videoTrack.samples;
  15991. const typeSupported = this.typeSupported;
  15992. const tracks = {};
  15993. const _initPTS = this._initPTS;
  15994. let computePTSDTS = !_initPTS || accurateTimeOffset;
  15995. let container = 'audio/mp4';
  15996. let initPTS;
  15997. let initDTS;
  15998. let timescale;
  15999. if (computePTSDTS) {
  16000. initPTS = initDTS = Infinity;
  16001. }
  16002. if (audioTrack.config && audioSamples.length) {
  16003. // let's use audio sampling rate as MP4 time scale.
  16004. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  16005. // using audio sampling rate here helps having an integer MP4 frame duration
  16006. // this avoids potential rounding issue and AV sync issue
  16007. audioTrack.timescale = audioTrack.samplerate;
  16008. switch (audioTrack.segmentCodec) {
  16009. case 'mp3':
  16010. if (typeSupported.mpeg) {
  16011. // Chrome and Safari
  16012. container = 'audio/mpeg';
  16013. audioTrack.codec = '';
  16014. } else if (typeSupported.mp3) {
  16015. // Firefox
  16016. audioTrack.codec = 'mp3';
  16017. }
  16018. break;
  16019. case 'ac3':
  16020. audioTrack.codec = 'ac-3';
  16021. break;
  16022. }
  16023. tracks.audio = {
  16024. id: 'audio',
  16025. container: container,
  16026. codec: audioTrack.codec,
  16027. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  16028. metadata: {
  16029. channelCount: audioTrack.channelCount
  16030. }
  16031. };
  16032. if (computePTSDTS) {
  16033. timescale = audioTrack.inputTimeScale;
  16034. if (!_initPTS || timescale !== _initPTS.timescale) {
  16035. // remember first PTS of this demuxing context. for audio, PTS = DTS
  16036. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  16037. } else {
  16038. computePTSDTS = false;
  16039. }
  16040. }
  16041. }
  16042. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  16043. // let's use input time scale as MP4 video timescale
  16044. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  16045. videoTrack.timescale = videoTrack.inputTimeScale;
  16046. tracks.video = {
  16047. id: 'main',
  16048. container: 'video/mp4',
  16049. codec: videoTrack.codec,
  16050. initSegment: MP4.initSegment([videoTrack]),
  16051. metadata: {
  16052. width: videoTrack.width,
  16053. height: videoTrack.height
  16054. }
  16055. };
  16056. if (computePTSDTS) {
  16057. timescale = videoTrack.inputTimeScale;
  16058. if (!_initPTS || timescale !== _initPTS.timescale) {
  16059. const startPTS = this.getVideoStartPts(videoSamples);
  16060. const startOffset = Math.round(timescale * timeOffset);
  16061. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  16062. initPTS = Math.min(initPTS, startPTS - startOffset);
  16063. } else {
  16064. computePTSDTS = false;
  16065. }
  16066. }
  16067. this.videoTrackConfig = {
  16068. width: videoTrack.width,
  16069. height: videoTrack.height,
  16070. pixelRatio: videoTrack.pixelRatio
  16071. };
  16072. }
  16073. if (Object.keys(tracks).length) {
  16074. this.ISGenerated = true;
  16075. if (computePTSDTS) {
  16076. this._initPTS = {
  16077. baseTime: initPTS,
  16078. timescale: timescale
  16079. };
  16080. this._initDTS = {
  16081. baseTime: initDTS,
  16082. timescale: timescale
  16083. };
  16084. } else {
  16085. initPTS = timescale = undefined;
  16086. }
  16087. return {
  16088. tracks,
  16089. initPTS,
  16090. timescale
  16091. };
  16092. }
  16093. }
  16094. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  16095. const timeScale = track.inputTimeScale;
  16096. const inputSamples = track.samples;
  16097. const outputSamples = [];
  16098. const nbSamples = inputSamples.length;
  16099. const initPTS = this._initPTS;
  16100. let nextAvcDts = this.nextAvcDts;
  16101. let offset = 8;
  16102. let mp4SampleDuration = this.videoSampleDuration;
  16103. let firstDTS;
  16104. let lastDTS;
  16105. let minPTS = Number.POSITIVE_INFINITY;
  16106. let maxPTS = Number.NEGATIVE_INFINITY;
  16107. let sortSamples = false;
  16108. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  16109. if (!contiguous || nextAvcDts === null) {
  16110. const pts = timeOffset * timeScale;
  16111. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  16112. if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {
  16113. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  16114. contiguous = true;
  16115. } else {
  16116. // if not contiguous, let's use target timeOffset
  16117. nextAvcDts = pts - cts;
  16118. }
  16119. }
  16120. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  16121. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  16122. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  16123. for (let i = 0; i < nbSamples; i++) {
  16124. const sample = inputSamples[i];
  16125. sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
  16126. sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
  16127. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  16128. sortSamples = true;
  16129. }
  16130. }
  16131. // sort video samples by DTS then PTS then demux id order
  16132. if (sortSamples) {
  16133. inputSamples.sort(function (a, b) {
  16134. const deltadts = a.dts - b.dts;
  16135. const deltapts = a.pts - b.pts;
  16136. return deltadts || deltapts;
  16137. });
  16138. }
  16139. // Get first/last DTS
  16140. firstDTS = inputSamples[0].dts;
  16141. lastDTS = inputSamples[inputSamples.length - 1].dts;
  16142. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  16143. // set this constant duration as being the avg delta between consecutive DTS.
  16144. const inputDuration = lastDTS - firstDTS;
  16145. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  16146. // if fragment are contiguous, detect hole/overlapping between fragments
  16147. if (contiguous) {
  16148. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  16149. const delta = firstDTS - nextAvcDts;
  16150. const foundHole = delta > averageSampleDuration;
  16151. const foundOverlap = delta < -1;
  16152. if (foundHole || foundOverlap) {
  16153. if (foundHole) {
  16154. logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  16155. } else {
  16156. logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  16157. }
  16158. if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
  16159. firstDTS = nextAvcDts;
  16160. const firstPTS = inputSamples[0].pts - delta;
  16161. if (foundHole) {
  16162. inputSamples[0].dts = firstDTS;
  16163. inputSamples[0].pts = firstPTS;
  16164. } else {
  16165. for (let i = 0; i < inputSamples.length; i++) {
  16166. if (inputSamples[i].dts > firstPTS) {
  16167. break;
  16168. }
  16169. inputSamples[i].dts -= delta;
  16170. inputSamples[i].pts -= delta;
  16171. }
  16172. }
  16173. logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  16174. }
  16175. }
  16176. }
  16177. firstDTS = Math.max(0, firstDTS);
  16178. let nbNalu = 0;
  16179. let naluLen = 0;
  16180. let dtsStep = firstDTS;
  16181. for (let i = 0; i < nbSamples; i++) {
  16182. // compute total/avc sample length and nb of NAL units
  16183. const sample = inputSamples[i];
  16184. const units = sample.units;
  16185. const nbUnits = units.length;
  16186. let sampleLen = 0;
  16187. for (let j = 0; j < nbUnits; j++) {
  16188. sampleLen += units[j].data.length;
  16189. }
  16190. naluLen += sampleLen;
  16191. nbNalu += nbUnits;
  16192. sample.length = sampleLen;
  16193. // ensure sample monotonic DTS
  16194. if (sample.dts < dtsStep) {
  16195. sample.dts = dtsStep;
  16196. dtsStep += averageSampleDuration / 4 | 0 || 1;
  16197. } else {
  16198. dtsStep = sample.dts;
  16199. }
  16200. minPTS = Math.min(sample.pts, minPTS);
  16201. maxPTS = Math.max(sample.pts, maxPTS);
  16202. }
  16203. lastDTS = inputSamples[nbSamples - 1].dts;
  16204. /* concatenate the video data and construct the mdat in place
  16205. (need 8 more bytes to fill length and mpdat type) */
  16206. const mdatSize = naluLen + 4 * nbNalu + 8;
  16207. let mdat;
  16208. try {
  16209. mdat = new Uint8Array(mdatSize);
  16210. } catch (err) {
  16211. this.observer.emit(Events.ERROR, Events.ERROR, {
  16212. type: ErrorTypes.MUX_ERROR,
  16213. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16214. fatal: false,
  16215. error: err,
  16216. bytes: mdatSize,
  16217. reason: `fail allocating video mdat ${mdatSize}`
  16218. });
  16219. return;
  16220. }
  16221. const view = new DataView(mdat.buffer);
  16222. view.setUint32(0, mdatSize);
  16223. mdat.set(MP4.types.mdat, 4);
  16224. let stretchedLastFrame = false;
  16225. let minDtsDelta = Number.POSITIVE_INFINITY;
  16226. let minPtsDelta = Number.POSITIVE_INFINITY;
  16227. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  16228. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  16229. for (let i = 0; i < nbSamples; i++) {
  16230. const VideoSample = inputSamples[i];
  16231. const VideoSampleUnits = VideoSample.units;
  16232. let mp4SampleLength = 0;
  16233. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  16234. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  16235. const unit = VideoSampleUnits[j];
  16236. const unitData = unit.data;
  16237. const unitDataLen = unit.data.byteLength;
  16238. view.setUint32(offset, unitDataLen);
  16239. offset += 4;
  16240. mdat.set(unitData, offset);
  16241. offset += unitDataLen;
  16242. mp4SampleLength += 4 + unitDataLen;
  16243. }
  16244. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  16245. let ptsDelta;
  16246. if (i < nbSamples - 1) {
  16247. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  16248. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  16249. } else {
  16250. const config = this.config;
  16251. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  16252. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  16253. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  16254. // In some cases, a segment's audio track duration may exceed the video track duration.
  16255. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  16256. // see if the delta to the next segment is longer than maxBufferHole.
  16257. // If so, playback would potentially get stuck, so we artificially inflate
  16258. // the duration of the last frame to minimize any potential gap between segments.
  16259. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  16260. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts;
  16261. if (deltaToFrameEnd > gapTolerance) {
  16262. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  16263. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  16264. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  16265. if (mp4SampleDuration < 0) {
  16266. mp4SampleDuration = lastFrameDuration;
  16267. } else {
  16268. stretchedLastFrame = true;
  16269. }
  16270. logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  16271. } else {
  16272. mp4SampleDuration = lastFrameDuration;
  16273. }
  16274. } else {
  16275. mp4SampleDuration = lastFrameDuration;
  16276. }
  16277. }
  16278. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  16279. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  16280. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  16281. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  16282. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  16283. outputSamples.push(new Mp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  16284. }
  16285. if (outputSamples.length) {
  16286. if (chromeVersion) {
  16287. if (chromeVersion < 70) {
  16288. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  16289. // https://code.google.com/p/chromium/issues/detail?id=229412
  16290. const flags = outputSamples[0].flags;
  16291. flags.dependsOn = 2;
  16292. flags.isNonSync = 0;
  16293. }
  16294. } else if (safariWebkitVersion) {
  16295. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  16296. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  16297. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  16298. logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  16299. let dts = firstDTS;
  16300. for (let i = 0, len = outputSamples.length; i < len; i++) {
  16301. const nextDts = dts + outputSamples[i].duration;
  16302. const pts = dts + outputSamples[i].cts;
  16303. if (i < len - 1) {
  16304. const nextPts = nextDts + outputSamples[i + 1].cts;
  16305. outputSamples[i].duration = nextPts - pts;
  16306. } else {
  16307. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  16308. }
  16309. outputSamples[i].cts = 0;
  16310. dts = nextDts;
  16311. }
  16312. }
  16313. }
  16314. }
  16315. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  16316. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  16317. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  16318. this.videoSampleDuration = mp4SampleDuration;
  16319. this.isVideoContiguous = true;
  16320. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  16321. samples: outputSamples
  16322. }));
  16323. const type = 'video';
  16324. const data = {
  16325. data1: moof,
  16326. data2: mdat,
  16327. startPTS: minPTS / timeScale,
  16328. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  16329. startDTS: firstDTS / timeScale,
  16330. endDTS: nextAvcDts / timeScale,
  16331. type,
  16332. hasAudio: false,
  16333. hasVideo: true,
  16334. nb: outputSamples.length,
  16335. dropped: track.dropped
  16336. };
  16337. track.samples = [];
  16338. track.dropped = 0;
  16339. return data;
  16340. }
  16341. getSamplesPerFrame(track) {
  16342. switch (track.segmentCodec) {
  16343. case 'mp3':
  16344. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  16345. case 'ac3':
  16346. return AC3_SAMPLES_PER_FRAME;
  16347. default:
  16348. return AAC_SAMPLES_PER_FRAME;
  16349. }
  16350. }
  16351. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  16352. const inputTimeScale = track.inputTimeScale;
  16353. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16354. const scaleFactor = inputTimeScale / mp4timeScale;
  16355. const mp4SampleDuration = this.getSamplesPerFrame(track);
  16356. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  16357. const initPTS = this._initPTS;
  16358. const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  16359. const outputSamples = [];
  16360. const alignedWithVideo = videoTimeOffset !== undefined;
  16361. let inputSamples = track.samples;
  16362. let offset = rawMPEG ? 0 : 8;
  16363. let nextAudioPts = this.nextAudioPts || -1;
  16364. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  16365. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  16366. // for sake of clarity:
  16367. // consecutive fragments are frags with
  16368. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  16369. // - less than 20 audio frames distance
  16370. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  16371. // this helps ensuring audio continuity
  16372. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  16373. const timeOffsetMpegTS = timeOffset * inputTimeScale;
  16374. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  16375. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);
  16376. // compute normalized PTS
  16377. inputSamples.forEach(function (sample) {
  16378. sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
  16379. });
  16380. if (!contiguous || nextAudioPts < 0) {
  16381. // filter out sample with negative PTS that are not playable anyway
  16382. // if we don't remove these negative samples, they will shift all audio samples forward.
  16383. // leading to audio overlap between current / next fragment
  16384. inputSamples = inputSamples.filter(sample => sample.pts >= 0);
  16385. // in case all samples have negative PTS, and have been filtered out, return now
  16386. if (!inputSamples.length) {
  16387. return;
  16388. }
  16389. if (videoTimeOffset === 0) {
  16390. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  16391. nextAudioPts = 0;
  16392. } else if (accurateTimeOffset && !alignedWithVideo) {
  16393. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  16394. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  16395. } else {
  16396. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  16397. nextAudioPts = inputSamples[0].pts;
  16398. }
  16399. }
  16400. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  16401. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  16402. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  16403. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  16404. // frame.
  16405. if (track.segmentCodec === 'aac') {
  16406. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  16407. for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  16408. // First, let's see how far off this frame is from where we expect it to be
  16409. const sample = inputSamples[i];
  16410. const pts = sample.pts;
  16411. const delta = pts - nextPts;
  16412. const duration = Math.abs(1000 * delta / inputTimeScale);
  16413. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  16414. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  16415. if (i === 0) {
  16416. logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1000 * delta / inputTimeScale)} ms.`);
  16417. this.nextAudioPts = nextAudioPts = nextPts = pts;
  16418. }
  16419. } // eslint-disable-line brace-style
  16420. // Insert missing frames if:
  16421. // 1: We're more than maxAudioFramesDrift frame away
  16422. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  16423. // 3: currentTime (aka nextPtsNorm) is not 0
  16424. // 4: remuxing with video (videoTimeOffset !== undefined)
  16425. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  16426. let missing = Math.round(delta / inputSampleDuration);
  16427. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  16428. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  16429. nextPts = pts - missing * inputSampleDuration;
  16430. if (nextPts < 0) {
  16431. missing--;
  16432. nextPts += inputSampleDuration;
  16433. }
  16434. if (i === 0) {
  16435. this.nextAudioPts = nextAudioPts = nextPts;
  16436. }
  16437. logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);
  16438. for (let j = 0; j < missing; j++) {
  16439. const newStamp = Math.max(nextPts, 0);
  16440. let fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16441. if (!fillFrame) {
  16442. logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  16443. fillFrame = sample.unit.subarray();
  16444. }
  16445. inputSamples.splice(i, 0, {
  16446. unit: fillFrame,
  16447. pts: newStamp
  16448. });
  16449. nextPts += inputSampleDuration;
  16450. i++;
  16451. }
  16452. }
  16453. sample.pts = nextPts;
  16454. nextPts += inputSampleDuration;
  16455. }
  16456. }
  16457. let firstPTS = null;
  16458. let lastPTS = null;
  16459. let mdat;
  16460. let mdatSize = 0;
  16461. let sampleLength = inputSamples.length;
  16462. while (sampleLength--) {
  16463. mdatSize += inputSamples[sampleLength].unit.byteLength;
  16464. }
  16465. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  16466. const audioSample = inputSamples[j];
  16467. const unit = audioSample.unit;
  16468. let pts = audioSample.pts;
  16469. if (lastPTS !== null) {
  16470. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  16471. // the previous sample
  16472. const prevSample = outputSamples[j - 1];
  16473. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  16474. } else {
  16475. if (contiguous && track.segmentCodec === 'aac') {
  16476. // set PTS/DTS to expected PTS/DTS
  16477. pts = nextAudioPts;
  16478. }
  16479. // remember first PTS of our audioSamples
  16480. firstPTS = pts;
  16481. if (mdatSize > 0) {
  16482. /* concatenate the audio data and construct the mdat in place
  16483. (need 8 more bytes to fill length and mdat type) */
  16484. mdatSize += offset;
  16485. try {
  16486. mdat = new Uint8Array(mdatSize);
  16487. } catch (err) {
  16488. this.observer.emit(Events.ERROR, Events.ERROR, {
  16489. type: ErrorTypes.MUX_ERROR,
  16490. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16491. fatal: false,
  16492. error: err,
  16493. bytes: mdatSize,
  16494. reason: `fail allocating audio mdat ${mdatSize}`
  16495. });
  16496. return;
  16497. }
  16498. if (!rawMPEG) {
  16499. const view = new DataView(mdat.buffer);
  16500. view.setUint32(0, mdatSize);
  16501. mdat.set(MP4.types.mdat, 4);
  16502. }
  16503. } else {
  16504. // no audio samples
  16505. return;
  16506. }
  16507. }
  16508. mdat.set(unit, offset);
  16509. const unitLen = unit.byteLength;
  16510. offset += unitLen;
  16511. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  16512. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  16513. // becomes the PTS diff with the previous sample
  16514. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  16515. lastPTS = pts;
  16516. }
  16517. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  16518. const nbSamples = outputSamples.length;
  16519. if (!nbSamples) {
  16520. return;
  16521. }
  16522. // The next audio sample PTS should be equal to last sample PTS + duration
  16523. const lastSample = outputSamples[outputSamples.length - 1];
  16524. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  16525. // Set the track samples from inputSamples to outputSamples before remuxing
  16526. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  16527. samples: outputSamples
  16528. }));
  16529. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  16530. track.samples = [];
  16531. const start = firstPTS / inputTimeScale;
  16532. const end = nextAudioPts / inputTimeScale;
  16533. const type = 'audio';
  16534. const audioData = {
  16535. data1: moof,
  16536. data2: mdat,
  16537. startPTS: start,
  16538. endPTS: end,
  16539. startDTS: start,
  16540. endDTS: end,
  16541. type,
  16542. hasAudio: true,
  16543. hasVideo: false,
  16544. nb: nbSamples
  16545. };
  16546. this.isAudioContiguous = true;
  16547. return audioData;
  16548. }
  16549. remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  16550. const inputTimeScale = track.inputTimeScale;
  16551. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16552. const scaleFactor = inputTimeScale / mp4timeScale;
  16553. const nextAudioPts = this.nextAudioPts;
  16554. // sync with video's timestamp
  16555. const initDTS = this._initDTS;
  16556. const init90kHz = initDTS.baseTime * 90000 / initDTS.timescale;
  16557. const startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz;
  16558. const endDTS = videoData.endDTS * inputTimeScale + init90kHz;
  16559. // one sample's duration value
  16560. const frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  16561. // samples count of this segment's duration
  16562. const nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  16563. // silent frame
  16564. const silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16565. logger.warn('[mp4-remuxer]: remux empty Audio');
  16566. // Can't remux if we can't generate a silent frame...
  16567. if (!silentFrame) {
  16568. logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  16569. return;
  16570. }
  16571. const samples = [];
  16572. for (let i = 0; i < nbSamples; i++) {
  16573. const stamp = startDTS + i * frameDuration;
  16574. samples.push({
  16575. unit: silentFrame,
  16576. pts: stamp,
  16577. dts: stamp
  16578. });
  16579. }
  16580. track.samples = samples;
  16581. return this.remuxAudio(track, timeOffset, contiguous, false);
  16582. }
  16583. }
  16584. function normalizePts(value, reference) {
  16585. let offset;
  16586. if (reference === null) {
  16587. return value;
  16588. }
  16589. if (reference < value) {
  16590. // - 2^33
  16591. offset = -8589934592;
  16592. } else {
  16593. // + 2^33
  16594. offset = 8589934592;
  16595. }
  16596. /* PTS is 33bit (from 0 to 2^33 -1)
  16597. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  16598. PTS looping occured. fill the gap */
  16599. while (Math.abs(value - reference) > 4294967296) {
  16600. value += offset;
  16601. }
  16602. return value;
  16603. }
  16604. function findKeyframeIndex(samples) {
  16605. for (let i = 0; i < samples.length; i++) {
  16606. if (samples[i].key) {
  16607. return i;
  16608. }
  16609. }
  16610. return -1;
  16611. }
  16612. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  16613. const length = track.samples.length;
  16614. if (!length) {
  16615. return;
  16616. }
  16617. const inputTimeScale = track.inputTimeScale;
  16618. for (let index = 0; index < length; index++) {
  16619. const sample = track.samples[index];
  16620. // setting id3 pts, dts to relative time
  16621. // using this._initPTS and this._initDTS to calculate relative time
  16622. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16623. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16624. }
  16625. const samples = track.samples;
  16626. track.samples = [];
  16627. return {
  16628. samples
  16629. };
  16630. }
  16631. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  16632. const length = track.samples.length;
  16633. if (!length) {
  16634. return;
  16635. }
  16636. const inputTimeScale = track.inputTimeScale;
  16637. for (let index = 0; index < length; index++) {
  16638. const sample = track.samples[index];
  16639. // setting text pts, dts to relative time
  16640. // using this._initPTS and this._initDTS to calculate relative time
  16641. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16642. }
  16643. track.samples.sort((a, b) => a.pts - b.pts);
  16644. const samples = track.samples;
  16645. track.samples = [];
  16646. return {
  16647. samples
  16648. };
  16649. }
  16650. class Mp4Sample {
  16651. constructor(isKeyframe, duration, size, cts) {
  16652. this.size = void 0;
  16653. this.duration = void 0;
  16654. this.cts = void 0;
  16655. this.flags = void 0;
  16656. this.duration = duration;
  16657. this.size = size;
  16658. this.cts = cts;
  16659. this.flags = {
  16660. isLeading: 0,
  16661. isDependedOn: 0,
  16662. hasRedundancy: 0,
  16663. degradPrio: 0,
  16664. dependsOn: isKeyframe ? 2 : 1,
  16665. isNonSync: isKeyframe ? 0 : 1
  16666. };
  16667. }
  16668. }
  16669. class PassThroughRemuxer {
  16670. constructor() {
  16671. this.emitInitSegment = false;
  16672. this.audioCodec = void 0;
  16673. this.videoCodec = void 0;
  16674. this.initData = void 0;
  16675. this.initPTS = null;
  16676. this.initTracks = void 0;
  16677. this.lastEndTime = null;
  16678. }
  16679. destroy() {}
  16680. resetTimeStamp(defaultInitPTS) {
  16681. this.initPTS = defaultInitPTS;
  16682. this.lastEndTime = null;
  16683. }
  16684. resetNextTimestamp() {
  16685. this.lastEndTime = null;
  16686. }
  16687. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  16688. this.audioCodec = audioCodec;
  16689. this.videoCodec = videoCodec;
  16690. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  16691. this.emitInitSegment = true;
  16692. }
  16693. generateInitSegment(initSegment) {
  16694. let {
  16695. audioCodec,
  16696. videoCodec
  16697. } = this;
  16698. if (!(initSegment != null && initSegment.byteLength)) {
  16699. this.initTracks = undefined;
  16700. this.initData = undefined;
  16701. return;
  16702. }
  16703. const initData = this.initData = parseInitSegment(initSegment);
  16704. // Get codec from initSegment or fallback to default
  16705. if (initData.audio) {
  16706. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
  16707. }
  16708. if (initData.video) {
  16709. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
  16710. }
  16711. const tracks = {};
  16712. if (initData.audio && initData.video) {
  16713. tracks.audiovideo = {
  16714. container: 'video/mp4',
  16715. codec: audioCodec + ',' + videoCodec,
  16716. initSegment,
  16717. id: 'main'
  16718. };
  16719. } else if (initData.audio) {
  16720. tracks.audio = {
  16721. container: 'audio/mp4',
  16722. codec: audioCodec,
  16723. initSegment,
  16724. id: 'audio'
  16725. };
  16726. } else if (initData.video) {
  16727. tracks.video = {
  16728. container: 'video/mp4',
  16729. codec: videoCodec,
  16730. initSegment,
  16731. id: 'main'
  16732. };
  16733. } else {
  16734. logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  16735. }
  16736. this.initTracks = tracks;
  16737. }
  16738. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  16739. var _initData, _initData2;
  16740. let {
  16741. initPTS,
  16742. lastEndTime
  16743. } = this;
  16744. const result = {
  16745. audio: undefined,
  16746. video: undefined,
  16747. text: textTrack,
  16748. id3: id3Track,
  16749. initSegment: undefined
  16750. };
  16751. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  16752. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  16753. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  16754. if (!isFiniteNumber(lastEndTime)) {
  16755. lastEndTime = this.lastEndTime = timeOffset || 0;
  16756. }
  16757. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  16758. // audio or video (or both); adding it to video was an arbitrary choice.
  16759. const data = videoTrack.samples;
  16760. if (!(data != null && data.length)) {
  16761. return result;
  16762. }
  16763. const initSegment = {
  16764. initPTS: undefined,
  16765. timescale: 1
  16766. };
  16767. let initData = this.initData;
  16768. if (!((_initData = initData) != null && _initData.length)) {
  16769. this.generateInitSegment(data);
  16770. initData = this.initData;
  16771. }
  16772. if (!((_initData2 = initData) != null && _initData2.length)) {
  16773. // We can't remux if the initSegment could not be generated
  16774. logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  16775. return result;
  16776. }
  16777. if (this.emitInitSegment) {
  16778. initSegment.tracks = this.initTracks;
  16779. this.emitInitSegment = false;
  16780. }
  16781. const duration = getDuration(data, initData);
  16782. const startDTS = getStartDTS(initData, data);
  16783. const decodeTime = startDTS === null ? timeOffset : startDTS;
  16784. if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) {
  16785. initSegment.initPTS = decodeTime - timeOffset;
  16786. if (initPTS && initPTS.timescale === 1) {
  16787. logger.warn(`Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`);
  16788. }
  16789. this.initPTS = initPTS = {
  16790. baseTime: initSegment.initPTS,
  16791. timescale: 1
  16792. };
  16793. }
  16794. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  16795. const endTime = startTime + duration;
  16796. offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
  16797. if (duration > 0) {
  16798. this.lastEndTime = endTime;
  16799. } else {
  16800. logger.warn('Duration parsed from mp4 should be greater than zero');
  16801. this.resetNextTimestamp();
  16802. }
  16803. const hasAudio = !!initData.audio;
  16804. const hasVideo = !!initData.video;
  16805. let type = '';
  16806. if (hasAudio) {
  16807. type += 'audio';
  16808. }
  16809. if (hasVideo) {
  16810. type += 'video';
  16811. }
  16812. const track = {
  16813. data1: data,
  16814. startPTS: startTime,
  16815. startDTS: startTime,
  16816. endPTS: endTime,
  16817. endDTS: endTime,
  16818. type,
  16819. hasAudio,
  16820. hasVideo,
  16821. nb: 1,
  16822. dropped: 0
  16823. };
  16824. result.audio = track.type === 'audio' ? track : undefined;
  16825. result.video = track.type !== 'audio' ? track : undefined;
  16826. result.initSegment = initSegment;
  16827. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  16828. if (textTrack.samples.length) {
  16829. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  16830. }
  16831. return result;
  16832. }
  16833. }
  16834. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  16835. if (initPTS === null) {
  16836. return true;
  16837. }
  16838. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  16839. const minDuration = Math.max(duration, 1);
  16840. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  16841. return Math.abs(startTime - timeOffset) > minDuration;
  16842. }
  16843. function getParsedTrackCodec(track, type) {
  16844. const parsedCodec = track == null ? void 0 : track.codec;
  16845. if (parsedCodec && parsedCodec.length > 4) {
  16846. return parsedCodec;
  16847. }
  16848. if (type === ElementaryStreamTypes.AUDIO) {
  16849. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  16850. return parsedCodec;
  16851. }
  16852. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  16853. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  16854. const preferManagedMediaSource = false;
  16855. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  16856. }
  16857. const result = 'mp4a.40.5';
  16858. logger.info(`Parsed audio codec "${parsedCodec}" or audio object type not handled. Using "${result}"`);
  16859. return result;
  16860. }
  16861. // Provide defaults based on codec type
  16862. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  16863. logger.warn(`Unhandled video codec "${parsedCodec}"`);
  16864. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  16865. return 'hvc1.1.6.L120.90';
  16866. }
  16867. if (parsedCodec === 'av01') {
  16868. return 'av01.0.04M.08';
  16869. }
  16870. return 'avc1.42e01e';
  16871. }
  16872. /** returns `undefined` is `self` is missing, e.g. in node */
  16873. const optionalSelf = typeof self !== 'undefined' ? self : undefined;
  16874. let now;
  16875. // performance.now() not available on WebWorker, at least on Safari Desktop
  16876. try {
  16877. now = self.performance.now.bind(self.performance);
  16878. } catch (err) {
  16879. logger.debug('Unable to use Performance API on this environment');
  16880. now = optionalSelf == null ? void 0 : optionalSelf.Date.now;
  16881. }
  16882. const muxConfig = [{
  16883. demux: MP4Demuxer,
  16884. remux: PassThroughRemuxer
  16885. }, {
  16886. demux: TSDemuxer,
  16887. remux: MP4Remuxer
  16888. }, {
  16889. demux: AACDemuxer,
  16890. remux: MP4Remuxer
  16891. }, {
  16892. demux: MP3Demuxer,
  16893. remux: MP4Remuxer
  16894. }];
  16895. class Transmuxer {
  16896. constructor(observer, typeSupported, config, vendor, id) {
  16897. this.async = false;
  16898. this.observer = void 0;
  16899. this.typeSupported = void 0;
  16900. this.config = void 0;
  16901. this.vendor = void 0;
  16902. this.id = void 0;
  16903. this.demuxer = void 0;
  16904. this.remuxer = void 0;
  16905. this.decrypter = void 0;
  16906. this.probe = void 0;
  16907. this.decryptionPromise = null;
  16908. this.transmuxConfig = void 0;
  16909. this.currentTransmuxState = void 0;
  16910. this.observer = observer;
  16911. this.typeSupported = typeSupported;
  16912. this.config = config;
  16913. this.vendor = vendor;
  16914. this.id = id;
  16915. }
  16916. configure(transmuxConfig) {
  16917. this.transmuxConfig = transmuxConfig;
  16918. if (this.decrypter) {
  16919. this.decrypter.reset();
  16920. }
  16921. }
  16922. push(data, decryptdata, chunkMeta, state) {
  16923. const stats = chunkMeta.transmuxing;
  16924. stats.executeStart = now();
  16925. let uintData = new Uint8Array(data);
  16926. const {
  16927. currentTransmuxState,
  16928. transmuxConfig
  16929. } = this;
  16930. if (state) {
  16931. this.currentTransmuxState = state;
  16932. }
  16933. const {
  16934. contiguous,
  16935. discontinuity,
  16936. trackSwitch,
  16937. accurateTimeOffset,
  16938. timeOffset,
  16939. initSegmentChange
  16940. } = state || currentTransmuxState;
  16941. const {
  16942. audioCodec,
  16943. videoCodec,
  16944. defaultInitPts,
  16945. duration,
  16946. initSegmentData
  16947. } = transmuxConfig;
  16948. const keyData = getEncryptionType(uintData, decryptdata);
  16949. if (keyData && keyData.method === 'AES-128') {
  16950. const decrypter = this.getDecrypter();
  16951. // Software decryption is synchronous; webCrypto is not
  16952. if (decrypter.isSync()) {
  16953. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  16954. // data is handled in the flush() call
  16955. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  16956. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  16957. const loadingParts = chunkMeta.part > -1;
  16958. if (loadingParts) {
  16959. decryptedData = decrypter.flush();
  16960. }
  16961. if (!decryptedData) {
  16962. stats.executeEnd = now();
  16963. return emptyResult(chunkMeta);
  16964. }
  16965. uintData = new Uint8Array(decryptedData);
  16966. } else {
  16967. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(decryptedData => {
  16968. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  16969. // the decrypted data has been transmuxed
  16970. const result = this.push(decryptedData, null, chunkMeta);
  16971. this.decryptionPromise = null;
  16972. return result;
  16973. });
  16974. return this.decryptionPromise;
  16975. }
  16976. }
  16977. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  16978. if (resetMuxers) {
  16979. const error = this.configureTransmuxer(uintData);
  16980. if (error) {
  16981. logger.warn(`[transmuxer] ${error.message}`);
  16982. this.observer.emit(Events.ERROR, Events.ERROR, {
  16983. type: ErrorTypes.MEDIA_ERROR,
  16984. details: ErrorDetails.FRAG_PARSING_ERROR,
  16985. fatal: false,
  16986. error,
  16987. reason: error.message
  16988. });
  16989. stats.executeEnd = now();
  16990. return emptyResult(chunkMeta);
  16991. }
  16992. }
  16993. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  16994. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  16995. }
  16996. if (discontinuity || initSegmentChange || resetMuxers) {
  16997. this.resetInitialTimestamp(defaultInitPts);
  16998. }
  16999. if (!contiguous) {
  17000. this.resetContiguity();
  17001. }
  17002. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17003. const currentState = this.currentTransmuxState;
  17004. currentState.contiguous = true;
  17005. currentState.discontinuity = false;
  17006. currentState.trackSwitch = false;
  17007. stats.executeEnd = now();
  17008. return result;
  17009. }
  17010. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  17011. flush(chunkMeta) {
  17012. const stats = chunkMeta.transmuxing;
  17013. stats.executeStart = now();
  17014. const {
  17015. decrypter,
  17016. currentTransmuxState,
  17017. decryptionPromise
  17018. } = this;
  17019. if (decryptionPromise) {
  17020. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  17021. // only flushing is required for async decryption
  17022. return decryptionPromise.then(() => {
  17023. return this.flush(chunkMeta);
  17024. });
  17025. }
  17026. const transmuxResults = [];
  17027. const {
  17028. timeOffset
  17029. } = currentTransmuxState;
  17030. if (decrypter) {
  17031. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  17032. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  17033. // or for progressive downloads with small segments)
  17034. const decryptedData = decrypter.flush();
  17035. if (decryptedData) {
  17036. // Push always returns a TransmuxerResult if decryptdata is null
  17037. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  17038. }
  17039. }
  17040. const {
  17041. demuxer,
  17042. remuxer
  17043. } = this;
  17044. if (!demuxer || !remuxer) {
  17045. // If probing failed, then Hls.js has been given content its not able to handle
  17046. stats.executeEnd = now();
  17047. return [emptyResult(chunkMeta)];
  17048. }
  17049. const demuxResultOrPromise = demuxer.flush(timeOffset);
  17050. if (isPromise(demuxResultOrPromise)) {
  17051. // Decrypt final SAMPLE-AES samples
  17052. return demuxResultOrPromise.then(demuxResult => {
  17053. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  17054. return transmuxResults;
  17055. });
  17056. }
  17057. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  17058. return transmuxResults;
  17059. }
  17060. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  17061. const {
  17062. audioTrack,
  17063. videoTrack,
  17064. id3Track,
  17065. textTrack
  17066. } = demuxResult;
  17067. const {
  17068. accurateTimeOffset,
  17069. timeOffset
  17070. } = this.currentTransmuxState;
  17071. logger.log(`[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''} of level ${chunkMeta.level}`);
  17072. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  17073. transmuxResults.push({
  17074. remuxResult,
  17075. chunkMeta
  17076. });
  17077. chunkMeta.transmuxing.executeEnd = now();
  17078. }
  17079. resetInitialTimestamp(defaultInitPts) {
  17080. const {
  17081. demuxer,
  17082. remuxer
  17083. } = this;
  17084. if (!demuxer || !remuxer) {
  17085. return;
  17086. }
  17087. demuxer.resetTimeStamp(defaultInitPts);
  17088. remuxer.resetTimeStamp(defaultInitPts);
  17089. }
  17090. resetContiguity() {
  17091. const {
  17092. demuxer,
  17093. remuxer
  17094. } = this;
  17095. if (!demuxer || !remuxer) {
  17096. return;
  17097. }
  17098. demuxer.resetContiguity();
  17099. remuxer.resetNextTimestamp();
  17100. }
  17101. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  17102. const {
  17103. demuxer,
  17104. remuxer
  17105. } = this;
  17106. if (!demuxer || !remuxer) {
  17107. return;
  17108. }
  17109. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  17110. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  17111. }
  17112. destroy() {
  17113. if (this.demuxer) {
  17114. this.demuxer.destroy();
  17115. this.demuxer = undefined;
  17116. }
  17117. if (this.remuxer) {
  17118. this.remuxer.destroy();
  17119. this.remuxer = undefined;
  17120. }
  17121. }
  17122. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  17123. let result;
  17124. if (keyData && keyData.method === 'SAMPLE-AES') {
  17125. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17126. } else {
  17127. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  17128. }
  17129. return result;
  17130. }
  17131. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  17132. const {
  17133. audioTrack,
  17134. videoTrack,
  17135. id3Track,
  17136. textTrack
  17137. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  17138. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  17139. return {
  17140. remuxResult,
  17141. chunkMeta
  17142. };
  17143. }
  17144. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  17145. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {
  17146. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  17147. return {
  17148. remuxResult,
  17149. chunkMeta
  17150. };
  17151. });
  17152. }
  17153. configureTransmuxer(data) {
  17154. const {
  17155. config,
  17156. observer,
  17157. typeSupported,
  17158. vendor
  17159. } = this;
  17160. // probe for content type
  17161. let mux;
  17162. for (let i = 0, len = muxConfig.length; i < len; i++) {
  17163. var _muxConfig$i$demux;
  17164. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data)) {
  17165. mux = muxConfig[i];
  17166. break;
  17167. }
  17168. }
  17169. if (!mux) {
  17170. return new Error('Failed to find demuxer by probing fragment data');
  17171. }
  17172. // so let's check that current remuxer and demuxer are still valid
  17173. const demuxer = this.demuxer;
  17174. const remuxer = this.remuxer;
  17175. const Remuxer = mux.remux;
  17176. const Demuxer = mux.demux;
  17177. if (!remuxer || !(remuxer instanceof Remuxer)) {
  17178. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  17179. }
  17180. if (!demuxer || !(demuxer instanceof Demuxer)) {
  17181. this.demuxer = new Demuxer(observer, config, typeSupported);
  17182. this.probe = Demuxer.probe;
  17183. }
  17184. }
  17185. needsProbing(discontinuity, trackSwitch) {
  17186. // in case of continuity change, or track switch
  17187. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  17188. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  17189. }
  17190. getDecrypter() {
  17191. let decrypter = this.decrypter;
  17192. if (!decrypter) {
  17193. decrypter = this.decrypter = new Decrypter(this.config);
  17194. }
  17195. return decrypter;
  17196. }
  17197. }
  17198. function getEncryptionType(data, decryptData) {
  17199. let encryptionType = null;
  17200. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  17201. encryptionType = decryptData;
  17202. }
  17203. return encryptionType;
  17204. }
  17205. const emptyResult = chunkMeta => ({
  17206. remuxResult: {},
  17207. chunkMeta
  17208. });
  17209. function isPromise(p) {
  17210. return 'then' in p && p.then instanceof Function;
  17211. }
  17212. class TransmuxConfig {
  17213. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  17214. this.audioCodec = void 0;
  17215. this.videoCodec = void 0;
  17216. this.initSegmentData = void 0;
  17217. this.duration = void 0;
  17218. this.defaultInitPts = void 0;
  17219. this.audioCodec = audioCodec;
  17220. this.videoCodec = videoCodec;
  17221. this.initSegmentData = initSegmentData;
  17222. this.duration = duration;
  17223. this.defaultInitPts = defaultInitPts || null;
  17224. }
  17225. }
  17226. class TransmuxState {
  17227. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  17228. this.discontinuity = void 0;
  17229. this.contiguous = void 0;
  17230. this.accurateTimeOffset = void 0;
  17231. this.trackSwitch = void 0;
  17232. this.timeOffset = void 0;
  17233. this.initSegmentChange = void 0;
  17234. this.discontinuity = discontinuity;
  17235. this.contiguous = contiguous;
  17236. this.accurateTimeOffset = accurateTimeOffset;
  17237. this.trackSwitch = trackSwitch;
  17238. this.timeOffset = timeOffset;
  17239. this.initSegmentChange = initSegmentChange;
  17240. }
  17241. }
  17242. var eventemitter3 = {exports: {}};
  17243. (function (module) {
  17244. var has = Object.prototype.hasOwnProperty
  17245. , prefix = '~';
  17246. /**
  17247. * Constructor to create a storage for our `EE` objects.
  17248. * An `Events` instance is a plain object whose properties are event names.
  17249. *
  17250. * @constructor
  17251. * @private
  17252. */
  17253. function Events() {}
  17254. //
  17255. // We try to not inherit from `Object.prototype`. In some engines creating an
  17256. // instance in this way is faster than calling `Object.create(null)` directly.
  17257. // If `Object.create(null)` is not supported we prefix the event names with a
  17258. // character to make sure that the built-in object properties are not
  17259. // overridden or used as an attack vector.
  17260. //
  17261. if (Object.create) {
  17262. Events.prototype = Object.create(null);
  17263. //
  17264. // This hack is needed because the `__proto__` property is still inherited in
  17265. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  17266. //
  17267. if (!new Events().__proto__) prefix = false;
  17268. }
  17269. /**
  17270. * Representation of a single event listener.
  17271. *
  17272. * @param {Function} fn The listener function.
  17273. * @param {*} context The context to invoke the listener with.
  17274. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  17275. * @constructor
  17276. * @private
  17277. */
  17278. function EE(fn, context, once) {
  17279. this.fn = fn;
  17280. this.context = context;
  17281. this.once = once || false;
  17282. }
  17283. /**
  17284. * Add a listener for a given event.
  17285. *
  17286. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17287. * @param {(String|Symbol)} event The event name.
  17288. * @param {Function} fn The listener function.
  17289. * @param {*} context The context to invoke the listener with.
  17290. * @param {Boolean} once Specify if the listener is a one-time listener.
  17291. * @returns {EventEmitter}
  17292. * @private
  17293. */
  17294. function addListener(emitter, event, fn, context, once) {
  17295. if (typeof fn !== 'function') {
  17296. throw new TypeError('The listener must be a function');
  17297. }
  17298. var listener = new EE(fn, context || emitter, once)
  17299. , evt = prefix ? prefix + event : event;
  17300. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  17301. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  17302. else emitter._events[evt] = [emitter._events[evt], listener];
  17303. return emitter;
  17304. }
  17305. /**
  17306. * Clear event by name.
  17307. *
  17308. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17309. * @param {(String|Symbol)} evt The Event name.
  17310. * @private
  17311. */
  17312. function clearEvent(emitter, evt) {
  17313. if (--emitter._eventsCount === 0) emitter._events = new Events();
  17314. else delete emitter._events[evt];
  17315. }
  17316. /**
  17317. * Minimal `EventEmitter` interface that is molded against the Node.js
  17318. * `EventEmitter` interface.
  17319. *
  17320. * @constructor
  17321. * @public
  17322. */
  17323. function EventEmitter() {
  17324. this._events = new Events();
  17325. this._eventsCount = 0;
  17326. }
  17327. /**
  17328. * Return an array listing the events for which the emitter has registered
  17329. * listeners.
  17330. *
  17331. * @returns {Array}
  17332. * @public
  17333. */
  17334. EventEmitter.prototype.eventNames = function eventNames() {
  17335. var names = []
  17336. , events
  17337. , name;
  17338. if (this._eventsCount === 0) return names;
  17339. for (name in (events = this._events)) {
  17340. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  17341. }
  17342. if (Object.getOwnPropertySymbols) {
  17343. return names.concat(Object.getOwnPropertySymbols(events));
  17344. }
  17345. return names;
  17346. };
  17347. /**
  17348. * Return the listeners registered for a given event.
  17349. *
  17350. * @param {(String|Symbol)} event The event name.
  17351. * @returns {Array} The registered listeners.
  17352. * @public
  17353. */
  17354. EventEmitter.prototype.listeners = function listeners(event) {
  17355. var evt = prefix ? prefix + event : event
  17356. , handlers = this._events[evt];
  17357. if (!handlers) return [];
  17358. if (handlers.fn) return [handlers.fn];
  17359. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  17360. ee[i] = handlers[i].fn;
  17361. }
  17362. return ee;
  17363. };
  17364. /**
  17365. * Return the number of listeners listening to a given event.
  17366. *
  17367. * @param {(String|Symbol)} event The event name.
  17368. * @returns {Number} The number of listeners.
  17369. * @public
  17370. */
  17371. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  17372. var evt = prefix ? prefix + event : event
  17373. , listeners = this._events[evt];
  17374. if (!listeners) return 0;
  17375. if (listeners.fn) return 1;
  17376. return listeners.length;
  17377. };
  17378. /**
  17379. * Calls each of the listeners registered for a given event.
  17380. *
  17381. * @param {(String|Symbol)} event The event name.
  17382. * @returns {Boolean} `true` if the event had listeners, else `false`.
  17383. * @public
  17384. */
  17385. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  17386. var evt = prefix ? prefix + event : event;
  17387. if (!this._events[evt]) return false;
  17388. var listeners = this._events[evt]
  17389. , len = arguments.length
  17390. , args
  17391. , i;
  17392. if (listeners.fn) {
  17393. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  17394. switch (len) {
  17395. case 1: return listeners.fn.call(listeners.context), true;
  17396. case 2: return listeners.fn.call(listeners.context, a1), true;
  17397. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  17398. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  17399. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  17400. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  17401. }
  17402. for (i = 1, args = new Array(len -1); i < len; i++) {
  17403. args[i - 1] = arguments[i];
  17404. }
  17405. listeners.fn.apply(listeners.context, args);
  17406. } else {
  17407. var length = listeners.length
  17408. , j;
  17409. for (i = 0; i < length; i++) {
  17410. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  17411. switch (len) {
  17412. case 1: listeners[i].fn.call(listeners[i].context); break;
  17413. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  17414. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  17415. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  17416. default:
  17417. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  17418. args[j - 1] = arguments[j];
  17419. }
  17420. listeners[i].fn.apply(listeners[i].context, args);
  17421. }
  17422. }
  17423. }
  17424. return true;
  17425. };
  17426. /**
  17427. * Add a listener for a given event.
  17428. *
  17429. * @param {(String|Symbol)} event The event name.
  17430. * @param {Function} fn The listener function.
  17431. * @param {*} [context=this] The context to invoke the listener with.
  17432. * @returns {EventEmitter} `this`.
  17433. * @public
  17434. */
  17435. EventEmitter.prototype.on = function on(event, fn, context) {
  17436. return addListener(this, event, fn, context, false);
  17437. };
  17438. /**
  17439. * Add a one-time listener for a given event.
  17440. *
  17441. * @param {(String|Symbol)} event The event name.
  17442. * @param {Function} fn The listener function.
  17443. * @param {*} [context=this] The context to invoke the listener with.
  17444. * @returns {EventEmitter} `this`.
  17445. * @public
  17446. */
  17447. EventEmitter.prototype.once = function once(event, fn, context) {
  17448. return addListener(this, event, fn, context, true);
  17449. };
  17450. /**
  17451. * Remove the listeners of a given event.
  17452. *
  17453. * @param {(String|Symbol)} event The event name.
  17454. * @param {Function} fn Only remove the listeners that match this function.
  17455. * @param {*} context Only remove the listeners that have this context.
  17456. * @param {Boolean} once Only remove one-time listeners.
  17457. * @returns {EventEmitter} `this`.
  17458. * @public
  17459. */
  17460. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  17461. var evt = prefix ? prefix + event : event;
  17462. if (!this._events[evt]) return this;
  17463. if (!fn) {
  17464. clearEvent(this, evt);
  17465. return this;
  17466. }
  17467. var listeners = this._events[evt];
  17468. if (listeners.fn) {
  17469. if (
  17470. listeners.fn === fn &&
  17471. (!once || listeners.once) &&
  17472. (!context || listeners.context === context)
  17473. ) {
  17474. clearEvent(this, evt);
  17475. }
  17476. } else {
  17477. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  17478. if (
  17479. listeners[i].fn !== fn ||
  17480. (once && !listeners[i].once) ||
  17481. (context && listeners[i].context !== context)
  17482. ) {
  17483. events.push(listeners[i]);
  17484. }
  17485. }
  17486. //
  17487. // Reset the array, or remove it completely if we have no more listeners.
  17488. //
  17489. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  17490. else clearEvent(this, evt);
  17491. }
  17492. return this;
  17493. };
  17494. /**
  17495. * Remove all listeners, or those of the specified event.
  17496. *
  17497. * @param {(String|Symbol)} [event] The event name.
  17498. * @returns {EventEmitter} `this`.
  17499. * @public
  17500. */
  17501. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  17502. var evt;
  17503. if (event) {
  17504. evt = prefix ? prefix + event : event;
  17505. if (this._events[evt]) clearEvent(this, evt);
  17506. } else {
  17507. this._events = new Events();
  17508. this._eventsCount = 0;
  17509. }
  17510. return this;
  17511. };
  17512. //
  17513. // Alias methods names because people roll like that.
  17514. //
  17515. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  17516. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  17517. //
  17518. // Expose the prefix.
  17519. //
  17520. EventEmitter.prefixed = prefix;
  17521. //
  17522. // Allow `EventEmitter` to be imported as module namespace.
  17523. //
  17524. EventEmitter.EventEmitter = EventEmitter;
  17525. //
  17526. // Expose the module.
  17527. //
  17528. {
  17529. module.exports = EventEmitter;
  17530. }
  17531. } (eventemitter3));
  17532. var eventemitter3Exports = eventemitter3.exports;
  17533. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  17534. class TransmuxerInterface {
  17535. constructor(hls, id, onTransmuxComplete, onFlush) {
  17536. this.error = null;
  17537. this.hls = void 0;
  17538. this.id = void 0;
  17539. this.observer = void 0;
  17540. this.frag = null;
  17541. this.part = null;
  17542. this.useWorker = void 0;
  17543. this.workerContext = null;
  17544. this.onwmsg = void 0;
  17545. this.transmuxer = null;
  17546. this.onTransmuxComplete = void 0;
  17547. this.onFlush = void 0;
  17548. const config = hls.config;
  17549. this.hls = hls;
  17550. this.id = id;
  17551. this.useWorker = !!config.enableWorker;
  17552. this.onTransmuxComplete = onTransmuxComplete;
  17553. this.onFlush = onFlush;
  17554. const forwardMessage = (ev, data) => {
  17555. data = data || {};
  17556. data.frag = this.frag;
  17557. data.id = this.id;
  17558. if (ev === Events.ERROR) {
  17559. this.error = data.error;
  17560. }
  17561. this.hls.trigger(ev, data);
  17562. };
  17563. // forward events to main thread
  17564. this.observer = new EventEmitter();
  17565. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  17566. this.observer.on(Events.ERROR, forwardMessage);
  17567. const MediaSource = getMediaSource(config.preferManagedMediaSource) || {
  17568. isTypeSupported: () => false
  17569. };
  17570. const m2tsTypeSupported = {
  17571. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  17572. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  17573. ac3: false
  17574. };
  17575. if (this.useWorker && typeof Worker !== 'undefined') {
  17576. const canCreateWorker = config.workerPath || hasUMDWorker();
  17577. if (canCreateWorker) {
  17578. try {
  17579. if (config.workerPath) {
  17580. logger.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  17581. this.workerContext = loadWorker(config.workerPath);
  17582. } else {
  17583. logger.log(`injecting Web Worker for "${id}"`);
  17584. this.workerContext = injectWorker();
  17585. }
  17586. this.onwmsg = event => this.onWorkerMessage(event);
  17587. const {
  17588. worker
  17589. } = this.workerContext;
  17590. worker.addEventListener('message', this.onwmsg);
  17591. worker.onerror = event => {
  17592. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  17593. config.enableWorker = false;
  17594. logger.warn(`Error in "${id}" Web Worker, fallback to inline`);
  17595. this.hls.trigger(Events.ERROR, {
  17596. type: ErrorTypes.OTHER_ERROR,
  17597. details: ErrorDetails.INTERNAL_EXCEPTION,
  17598. fatal: false,
  17599. event: 'demuxerWorker',
  17600. error
  17601. });
  17602. };
  17603. worker.postMessage({
  17604. cmd: 'init',
  17605. typeSupported: m2tsTypeSupported,
  17606. vendor: '',
  17607. id: id,
  17608. config: JSON.stringify(config)
  17609. });
  17610. } catch (err) {
  17611. logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  17612. this.resetWorker();
  17613. this.error = null;
  17614. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  17615. }
  17616. return;
  17617. }
  17618. }
  17619. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  17620. }
  17621. resetWorker() {
  17622. if (this.workerContext) {
  17623. const {
  17624. worker,
  17625. objectURL
  17626. } = this.workerContext;
  17627. if (objectURL) {
  17628. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  17629. self.URL.revokeObjectURL(objectURL);
  17630. }
  17631. worker.removeEventListener('message', this.onwmsg);
  17632. worker.onerror = null;
  17633. worker.terminate();
  17634. this.workerContext = null;
  17635. }
  17636. }
  17637. destroy() {
  17638. if (this.workerContext) {
  17639. this.resetWorker();
  17640. this.onwmsg = undefined;
  17641. } else {
  17642. const transmuxer = this.transmuxer;
  17643. if (transmuxer) {
  17644. transmuxer.destroy();
  17645. this.transmuxer = null;
  17646. }
  17647. }
  17648. const observer = this.observer;
  17649. if (observer) {
  17650. observer.removeAllListeners();
  17651. }
  17652. this.frag = null;
  17653. // @ts-ignore
  17654. this.observer = null;
  17655. // @ts-ignore
  17656. this.hls = null;
  17657. }
  17658. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  17659. var _frag$initSegment, _lastFrag$initSegment;
  17660. chunkMeta.transmuxing.start = self.performance.now();
  17661. const {
  17662. transmuxer
  17663. } = this;
  17664. const timeOffset = part ? part.start : frag.start;
  17665. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  17666. const decryptdata = frag.decryptdata;
  17667. const lastFrag = this.frag;
  17668. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  17669. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  17670. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  17671. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  17672. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  17673. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  17674. const now = self.performance.now();
  17675. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  17676. frag.stats.parsing.start = now;
  17677. }
  17678. if (part && (partDiff || !contiguous)) {
  17679. part.stats.parsing.start = now;
  17680. }
  17681. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  17682. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  17683. if (!contiguous || discontinuity || initSegmentChange) {
  17684. logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}
  17685. discontinuity: ${discontinuity}
  17686. trackSwitch: ${trackSwitch}
  17687. contiguous: ${contiguous}
  17688. accurateTimeOffset: ${accurateTimeOffset}
  17689. timeOffset: ${timeOffset}
  17690. initSegmentChange: ${initSegmentChange}`);
  17691. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  17692. this.configureTransmuxer(config);
  17693. }
  17694. this.frag = frag;
  17695. this.part = part;
  17696. // Frags with sn of 'initSegment' are not transmuxed
  17697. if (this.workerContext) {
  17698. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  17699. this.workerContext.worker.postMessage({
  17700. cmd: 'demux',
  17701. data,
  17702. decryptdata,
  17703. chunkMeta,
  17704. state
  17705. }, data instanceof ArrayBuffer ? [data] : []);
  17706. } else if (transmuxer) {
  17707. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  17708. if (isPromise(transmuxResult)) {
  17709. transmuxer.async = true;
  17710. transmuxResult.then(data => {
  17711. this.handleTransmuxComplete(data);
  17712. }).catch(error => {
  17713. this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  17714. });
  17715. } else {
  17716. transmuxer.async = false;
  17717. this.handleTransmuxComplete(transmuxResult);
  17718. }
  17719. }
  17720. }
  17721. flush(chunkMeta) {
  17722. chunkMeta.transmuxing.start = self.performance.now();
  17723. const {
  17724. transmuxer
  17725. } = this;
  17726. if (this.workerContext) {
  17727. this.workerContext.worker.postMessage({
  17728. cmd: 'flush',
  17729. chunkMeta
  17730. });
  17731. } else if (transmuxer) {
  17732. let transmuxResult = transmuxer.flush(chunkMeta);
  17733. const asyncFlush = isPromise(transmuxResult);
  17734. if (asyncFlush || transmuxer.async) {
  17735. if (!isPromise(transmuxResult)) {
  17736. transmuxResult = Promise.resolve(transmuxResult);
  17737. }
  17738. transmuxResult.then(data => {
  17739. this.handleFlushResult(data, chunkMeta);
  17740. }).catch(error => {
  17741. this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  17742. });
  17743. } else {
  17744. this.handleFlushResult(transmuxResult, chunkMeta);
  17745. }
  17746. }
  17747. }
  17748. transmuxerError(error, chunkMeta, reason) {
  17749. if (!this.hls) {
  17750. return;
  17751. }
  17752. this.error = error;
  17753. this.hls.trigger(Events.ERROR, {
  17754. type: ErrorTypes.MEDIA_ERROR,
  17755. details: ErrorDetails.FRAG_PARSING_ERROR,
  17756. chunkMeta,
  17757. frag: this.frag || undefined,
  17758. fatal: false,
  17759. error,
  17760. err: error,
  17761. reason
  17762. });
  17763. }
  17764. handleFlushResult(results, chunkMeta) {
  17765. results.forEach(result => {
  17766. this.handleTransmuxComplete(result);
  17767. });
  17768. this.onFlush(chunkMeta);
  17769. }
  17770. onWorkerMessage(event) {
  17771. const data = event.data;
  17772. if (!(data != null && data.event)) {
  17773. logger.warn(`worker message received with no ${data ? 'event name' : 'data'}`);
  17774. return;
  17775. }
  17776. const hls = this.hls;
  17777. if (!this.hls) {
  17778. return;
  17779. }
  17780. switch (data.event) {
  17781. case 'init':
  17782. {
  17783. var _this$workerContext;
  17784. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  17785. if (objectURL) {
  17786. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  17787. self.URL.revokeObjectURL(objectURL);
  17788. }
  17789. break;
  17790. }
  17791. case 'transmuxComplete':
  17792. {
  17793. this.handleTransmuxComplete(data.data);
  17794. break;
  17795. }
  17796. case 'flush':
  17797. {
  17798. this.onFlush(data.data);
  17799. break;
  17800. }
  17801. // pass logs from the worker thread to the main logger
  17802. case 'workerLog':
  17803. if (logger[data.data.logType]) {
  17804. logger[data.data.logType](data.data.message);
  17805. }
  17806. break;
  17807. default:
  17808. {
  17809. data.data = data.data || {};
  17810. data.data.frag = this.frag;
  17811. data.data.id = this.id;
  17812. hls.trigger(data.event, data.data);
  17813. break;
  17814. }
  17815. }
  17816. }
  17817. configureTransmuxer(config) {
  17818. const {
  17819. transmuxer
  17820. } = this;
  17821. if (this.workerContext) {
  17822. this.workerContext.worker.postMessage({
  17823. cmd: 'configure',
  17824. config
  17825. });
  17826. } else if (transmuxer) {
  17827. transmuxer.configure(config);
  17828. }
  17829. }
  17830. handleTransmuxComplete(result) {
  17831. result.chunkMeta.transmuxing.end = self.performance.now();
  17832. this.onTransmuxComplete(result);
  17833. }
  17834. }
  17835. const STALL_MINIMUM_DURATION_MS = 250;
  17836. const MAX_START_GAP_JUMP = 2.0;
  17837. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  17838. const SKIP_BUFFER_RANGE_START = 0.05;
  17839. class GapController {
  17840. constructor(config, media, fragmentTracker, hls) {
  17841. this.config = void 0;
  17842. this.media = null;
  17843. this.fragmentTracker = void 0;
  17844. this.hls = void 0;
  17845. this.nudgeRetry = 0;
  17846. this.stallReported = false;
  17847. this.stalled = null;
  17848. this.moved = false;
  17849. this.seeking = false;
  17850. this.config = config;
  17851. this.media = media;
  17852. this.fragmentTracker = fragmentTracker;
  17853. this.hls = hls;
  17854. }
  17855. destroy() {
  17856. this.media = null;
  17857. // @ts-ignore
  17858. this.hls = this.fragmentTracker = null;
  17859. }
  17860. /**
  17861. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  17862. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  17863. *
  17864. * @param lastCurrentTime - Previously read playhead position
  17865. */
  17866. poll(lastCurrentTime, activeFrag) {
  17867. const {
  17868. config,
  17869. media,
  17870. stalled
  17871. } = this;
  17872. if (media === null) {
  17873. return;
  17874. }
  17875. const {
  17876. currentTime,
  17877. seeking
  17878. } = media;
  17879. const seeked = this.seeking && !seeking;
  17880. const beginSeek = !this.seeking && seeking;
  17881. this.seeking = seeking;
  17882. // The playhead is moving, no-op
  17883. if (currentTime !== lastCurrentTime) {
  17884. this.moved = true;
  17885. if (!seeking) {
  17886. this.nudgeRetry = 0;
  17887. }
  17888. if (stalled !== null) {
  17889. // The playhead is now moving, but was previously stalled
  17890. if (this.stallReported) {
  17891. const _stalledDuration = self.performance.now() - stalled;
  17892. logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(_stalledDuration)}ms`);
  17893. this.stallReported = false;
  17894. }
  17895. this.stalled = null;
  17896. }
  17897. return;
  17898. }
  17899. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  17900. if (beginSeek || seeked) {
  17901. this.stalled = null;
  17902. return;
  17903. }
  17904. // The playhead should not be moving
  17905. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) {
  17906. this.nudgeRetry = 0;
  17907. return;
  17908. }
  17909. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  17910. const nextStart = bufferInfo.nextStart || 0;
  17911. if (seeking) {
  17912. // Waiting for seeking in a buffered range to complete
  17913. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  17914. // Next buffered range is too far ahead to jump to while still seeking
  17915. const noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  17916. if (hasEnoughBuffer || noBufferGap) {
  17917. return;
  17918. }
  17919. // Reset moved state when seeking to a point in or before a gap
  17920. this.moved = false;
  17921. }
  17922. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  17923. // The addition poll gives the browser a chance to jump the gap for us
  17924. if (!this.moved && this.stalled !== null) {
  17925. var _level$details;
  17926. // There is no playable buffer (seeked, waiting for buffer)
  17927. const isBuffered = bufferInfo.len > 0;
  17928. if (!isBuffered && !nextStart) {
  17929. return;
  17930. }
  17931. // Jump start gaps within jump threshold
  17932. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  17933. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  17934. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  17935. // that begins over 1 target duration after the video start position.
  17936. const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  17937. const isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live;
  17938. const maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  17939. const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);
  17940. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  17941. if (!media.paused) {
  17942. this._trySkipBufferHole(partialOrGap);
  17943. }
  17944. return;
  17945. }
  17946. }
  17947. // Start tracking stall time
  17948. const tnow = self.performance.now();
  17949. if (stalled === null) {
  17950. this.stalled = tnow;
  17951. return;
  17952. }
  17953. const stalledDuration = tnow - stalled;
  17954. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  17955. // Report stalling after trying to fix
  17956. this._reportStall(bufferInfo);
  17957. if (!this.media) {
  17958. return;
  17959. }
  17960. }
  17961. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  17962. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  17963. }
  17964. /**
  17965. * Detects and attempts to fix known buffer stalling issues.
  17966. * @param bufferInfo - The properties of the current buffer.
  17967. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  17968. * @private
  17969. */
  17970. _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  17971. const {
  17972. config,
  17973. fragmentTracker,
  17974. media
  17975. } = this;
  17976. if (media === null) {
  17977. return;
  17978. }
  17979. const currentTime = media.currentTime;
  17980. const partial = fragmentTracker.getPartialFragment(currentTime);
  17981. if (partial) {
  17982. // Try to skip over the buffer hole caused by a partial fragment
  17983. // This method isn't limited by the size of the gap between buffered ranges
  17984. const targetTime = this._trySkipBufferHole(partial);
  17985. // we return here in this case, meaning
  17986. // the branch below only executes when we haven't seeked to a new position
  17987. if (targetTime || !this.media) {
  17988. return;
  17989. }
  17990. }
  17991. // if we haven't had to skip over a buffer hole of a partial fragment
  17992. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  17993. // needs to cross some sort of threshold covering all source-buffers content
  17994. // to start playing properly.
  17995. if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  17996. logger.warn('Trying to nudge playhead over buffer-hole');
  17997. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  17998. // We only try to jump the hole if it's under the configured size
  17999. // Reset stalled so to rearm watchdog timer
  18000. this.stalled = null;
  18001. this._tryNudgeBuffer();
  18002. }
  18003. }
  18004. /**
  18005. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  18006. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  18007. * @private
  18008. */
  18009. _reportStall(bufferInfo) {
  18010. const {
  18011. hls,
  18012. media,
  18013. stallReported
  18014. } = this;
  18015. if (!stallReported && media) {
  18016. // Report stalled error once
  18017. this.stallReported = true;
  18018. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${JSON.stringify(bufferInfo)})`);
  18019. logger.warn(error.message);
  18020. hls.trigger(Events.ERROR, {
  18021. type: ErrorTypes.MEDIA_ERROR,
  18022. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18023. fatal: false,
  18024. error,
  18025. buffer: bufferInfo.len
  18026. });
  18027. }
  18028. }
  18029. /**
  18030. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  18031. * @param partial - The partial fragment found at the current time (where playback is stalling).
  18032. * @private
  18033. */
  18034. _trySkipBufferHole(partial) {
  18035. const {
  18036. config,
  18037. hls,
  18038. media
  18039. } = this;
  18040. if (media === null) {
  18041. return 0;
  18042. }
  18043. // Check if currentTime is between unbuffered regions of partial fragments
  18044. const currentTime = media.currentTime;
  18045. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18046. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  18047. if (startTime) {
  18048. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  18049. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  18050. const gapLength = startTime - currentTime;
  18051. if (gapLength > 0 && (bufferStarved || waiting)) {
  18052. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  18053. if (gapLength > config.maxBufferHole) {
  18054. const {
  18055. fragmentTracker
  18056. } = this;
  18057. let startGap = false;
  18058. if (currentTime === 0) {
  18059. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  18060. if (startFrag && startTime < startFrag.end) {
  18061. startGap = true;
  18062. }
  18063. }
  18064. if (!startGap) {
  18065. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  18066. if (startProvisioned) {
  18067. let moreToLoad = false;
  18068. let pos = startProvisioned.end;
  18069. while (pos < startTime) {
  18070. const provisioned = fragmentTracker.getPartialFragment(pos);
  18071. if (provisioned) {
  18072. pos += provisioned.duration;
  18073. } else {
  18074. moreToLoad = true;
  18075. break;
  18076. }
  18077. }
  18078. if (moreToLoad) {
  18079. return 0;
  18080. }
  18081. }
  18082. }
  18083. }
  18084. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  18085. logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  18086. this.moved = true;
  18087. this.stalled = null;
  18088. media.currentTime = targetTime;
  18089. if (partial && !partial.gap) {
  18090. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  18091. hls.trigger(Events.ERROR, {
  18092. type: ErrorTypes.MEDIA_ERROR,
  18093. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18094. fatal: false,
  18095. error,
  18096. reason: error.message,
  18097. frag: partial
  18098. });
  18099. }
  18100. return targetTime;
  18101. }
  18102. }
  18103. return 0;
  18104. }
  18105. /**
  18106. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  18107. * @private
  18108. */
  18109. _tryNudgeBuffer() {
  18110. const {
  18111. config,
  18112. hls,
  18113. media,
  18114. nudgeRetry
  18115. } = this;
  18116. if (media === null) {
  18117. return;
  18118. }
  18119. const currentTime = media.currentTime;
  18120. this.nudgeRetry++;
  18121. if (nudgeRetry < config.nudgeMaxRetry) {
  18122. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  18123. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  18124. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  18125. logger.warn(error.message);
  18126. media.currentTime = targetTime;
  18127. hls.trigger(Events.ERROR, {
  18128. type: ErrorTypes.MEDIA_ERROR,
  18129. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  18130. error,
  18131. fatal: false
  18132. });
  18133. } else {
  18134. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  18135. logger.error(error.message);
  18136. hls.trigger(Events.ERROR, {
  18137. type: ErrorTypes.MEDIA_ERROR,
  18138. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18139. error,
  18140. fatal: true
  18141. });
  18142. }
  18143. }
  18144. }
  18145. const TICK_INTERVAL = 100; // how often to tick in ms
  18146. class StreamController extends BaseStreamController {
  18147. constructor(hls, fragmentTracker, keyLoader) {
  18148. super(hls, fragmentTracker, keyLoader, '[stream-controller]', PlaylistLevelType.MAIN);
  18149. this.audioCodecSwap = false;
  18150. this.gapController = null;
  18151. this.level = -1;
  18152. this._forceStartLoad = false;
  18153. this.altAudio = false;
  18154. this.audioOnly = false;
  18155. this.fragPlaying = null;
  18156. this.onvplaying = null;
  18157. this.onvseeked = null;
  18158. this.fragLastKbps = 0;
  18159. this.couldBacktrack = false;
  18160. this.backtrackFragment = null;
  18161. this.audioCodecSwitch = false;
  18162. this.videoBuffer = null;
  18163. this._registerListeners();
  18164. }
  18165. _registerListeners() {
  18166. const {
  18167. hls
  18168. } = this;
  18169. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18170. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18171. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18172. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18173. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  18174. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18175. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18176. hls.on(Events.ERROR, this.onError, this);
  18177. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18178. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18179. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18180. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18181. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18182. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18183. }
  18184. _unregisterListeners() {
  18185. const {
  18186. hls
  18187. } = this;
  18188. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18189. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18190. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18191. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18192. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18193. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18194. hls.off(Events.ERROR, this.onError, this);
  18195. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18196. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18197. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18198. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18199. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18200. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18201. }
  18202. onHandlerDestroying() {
  18203. this._unregisterListeners();
  18204. super.onHandlerDestroying();
  18205. }
  18206. startLoad(startPosition) {
  18207. if (this.levels) {
  18208. const {
  18209. lastCurrentTime,
  18210. hls
  18211. } = this;
  18212. this.stopLoad();
  18213. this.setInterval(TICK_INTERVAL);
  18214. this.level = -1;
  18215. if (!this.startFragRequested) {
  18216. // determine load level
  18217. let startLevel = hls.startLevel;
  18218. if (startLevel === -1) {
  18219. if (hls.config.testBandwidth && this.levels.length > 1) {
  18220. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  18221. startLevel = 0;
  18222. this.bitrateTest = true;
  18223. } else {
  18224. startLevel = hls.firstAutoLevel;
  18225. }
  18226. }
  18227. // set new level to playlist loader : this will trigger start level load
  18228. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  18229. hls.nextLoadLevel = startLevel;
  18230. this.level = hls.loadLevel;
  18231. this.loadedmetadata = false;
  18232. }
  18233. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  18234. if (lastCurrentTime > 0 && startPosition === -1) {
  18235. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  18236. startPosition = lastCurrentTime;
  18237. }
  18238. this.state = State.IDLE;
  18239. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  18240. this.tick();
  18241. } else {
  18242. this._forceStartLoad = true;
  18243. this.state = State.STOPPED;
  18244. }
  18245. }
  18246. stopLoad() {
  18247. this._forceStartLoad = false;
  18248. super.stopLoad();
  18249. }
  18250. doTick() {
  18251. switch (this.state) {
  18252. case State.WAITING_LEVEL:
  18253. {
  18254. const {
  18255. levels,
  18256. level
  18257. } = this;
  18258. const currentLevel = levels == null ? void 0 : levels[level];
  18259. const details = currentLevel == null ? void 0 : currentLevel.details;
  18260. if (details && (!details.live || this.levelLastLoaded === currentLevel)) {
  18261. if (this.waitForCdnTuneIn(details)) {
  18262. break;
  18263. }
  18264. this.state = State.IDLE;
  18265. break;
  18266. } else if (this.hls.nextLoadLevel !== this.level) {
  18267. this.state = State.IDLE;
  18268. break;
  18269. }
  18270. break;
  18271. }
  18272. case State.FRAG_LOADING_WAITING_RETRY:
  18273. {
  18274. var _this$media;
  18275. const now = self.performance.now();
  18276. const retryDate = this.retryDate;
  18277. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  18278. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  18279. const {
  18280. levels,
  18281. level
  18282. } = this;
  18283. const currentLevel = levels == null ? void 0 : levels[level];
  18284. this.resetStartWhenNotLoaded(currentLevel || null);
  18285. this.state = State.IDLE;
  18286. }
  18287. }
  18288. break;
  18289. }
  18290. if (this.state === State.IDLE) {
  18291. this.doTickIdle();
  18292. }
  18293. this.onTickEnd();
  18294. }
  18295. onTickEnd() {
  18296. super.onTickEnd();
  18297. this.checkBuffer();
  18298. this.checkFragmentChanged();
  18299. }
  18300. doTickIdle() {
  18301. const {
  18302. hls,
  18303. levelLastLoaded,
  18304. levels,
  18305. media
  18306. } = this;
  18307. // if start level not parsed yet OR
  18308. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  18309. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  18310. if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  18311. return;
  18312. }
  18313. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  18314. if (this.altAudio && this.audioOnly) {
  18315. return;
  18316. }
  18317. const level = hls.nextLoadLevel;
  18318. if (!(levels != null && levels[level])) {
  18319. return;
  18320. }
  18321. const levelInfo = levels[level];
  18322. // if buffer length is less than maxBufLen try to load a new fragment
  18323. const bufferInfo = this.getMainFwdBufferInfo();
  18324. if (bufferInfo === null) {
  18325. return;
  18326. }
  18327. const lastDetails = this.getLevelDetails();
  18328. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  18329. const data = {};
  18330. if (this.altAudio) {
  18331. data.type = 'video';
  18332. }
  18333. this.hls.trigger(Events.BUFFER_EOS, data);
  18334. this.state = State.ENDED;
  18335. return;
  18336. }
  18337. // set next load level : this will trigger a playlist load if needed
  18338. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  18339. this.log(`Adapting to level ${level} from level ${this.level}`);
  18340. }
  18341. this.level = hls.nextLoadLevel = level;
  18342. const levelDetails = levelInfo.details;
  18343. // if level info not retrieved yet, switch state and wait for level retrieval
  18344. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  18345. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  18346. if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) {
  18347. this.level = level;
  18348. this.state = State.WAITING_LEVEL;
  18349. return;
  18350. }
  18351. const bufferLen = bufferInfo.len;
  18352. // 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
  18353. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  18354. // Stay idle if we are still with buffer margins
  18355. if (bufferLen >= maxBufLen) {
  18356. return;
  18357. }
  18358. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  18359. this.backtrackFragment = null;
  18360. }
  18361. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  18362. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  18363. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  18364. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  18365. var _this$backtrackFragme;
  18366. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  18367. const fragIdx = backtrackSn - levelDetails.startSN;
  18368. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  18369. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  18370. frag = backtrackFrag;
  18371. this.fragmentTracker.removeFragment(backtrackFrag);
  18372. }
  18373. } else if (this.backtrackFragment && bufferInfo.len) {
  18374. this.backtrackFragment = null;
  18375. }
  18376. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  18377. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  18378. const gapStart = frag.gap;
  18379. if (!gapStart) {
  18380. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  18381. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  18382. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  18383. if (mediaBuffer) {
  18384. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  18385. }
  18386. }
  18387. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  18388. }
  18389. if (!frag) {
  18390. return;
  18391. }
  18392. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  18393. frag = frag.initSegment;
  18394. }
  18395. this.loadFragment(frag, levelInfo, targetBufferTime);
  18396. }
  18397. loadFragment(frag, level, targetBufferTime) {
  18398. // Check if fragment is not loaded
  18399. const fragState = this.fragmentTracker.getState(frag);
  18400. this.fragCurrent = frag;
  18401. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  18402. if (frag.sn === 'initSegment') {
  18403. this._loadInitSegment(frag, level);
  18404. } else if (this.bitrateTest) {
  18405. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  18406. this._loadBitrateTestFrag(frag, level);
  18407. } else {
  18408. this.startFragRequested = true;
  18409. super.loadFragment(frag, level, targetBufferTime);
  18410. }
  18411. } else {
  18412. this.clearTrackerIfNeeded(frag);
  18413. }
  18414. }
  18415. getBufferedFrag(position) {
  18416. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  18417. }
  18418. followingBufferedFrag(frag) {
  18419. if (frag) {
  18420. // try to get range of next fragment (500ms after this range)
  18421. return this.getBufferedFrag(frag.end + 0.5);
  18422. }
  18423. return null;
  18424. }
  18425. /*
  18426. on immediate level switch :
  18427. - pause playback if playing
  18428. - cancel any pending load request
  18429. - and trigger a buffer flush
  18430. */
  18431. immediateLevelSwitch() {
  18432. this.abortCurrentFrag();
  18433. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  18434. }
  18435. /**
  18436. * try to switch ASAP without breaking video playback:
  18437. * in order to ensure smooth but quick level switching,
  18438. * we need to find the next flushable buffer range
  18439. * we should take into account new segment fetch time
  18440. */
  18441. nextLevelSwitch() {
  18442. const {
  18443. levels,
  18444. media
  18445. } = this;
  18446. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  18447. if (media != null && media.readyState) {
  18448. let fetchdelay;
  18449. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  18450. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  18451. // flush buffer preceding current fragment (flush until current fragment start offset)
  18452. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  18453. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  18454. }
  18455. const levelDetails = this.getLevelDetails();
  18456. if (levelDetails != null && levelDetails.live) {
  18457. const bufferInfo = this.getMainFwdBufferInfo();
  18458. // Do not flush in live stream with low buffer
  18459. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  18460. return;
  18461. }
  18462. }
  18463. if (!media.paused && levels) {
  18464. // add a safety delay of 1s
  18465. const nextLevelId = this.hls.nextLoadLevel;
  18466. const nextLevel = levels[nextLevelId];
  18467. const fragLastKbps = this.fragLastKbps;
  18468. if (fragLastKbps && this.fragCurrent) {
  18469. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  18470. } else {
  18471. fetchdelay = 0;
  18472. }
  18473. } else {
  18474. fetchdelay = 0;
  18475. }
  18476. // this.log('fetchdelay:'+fetchdelay);
  18477. // find buffer range that will be reached once new fragment will be fetched
  18478. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  18479. if (bufferedFrag) {
  18480. // we can flush buffer range following this one without stalling playback
  18481. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  18482. if (nextBufferedFrag) {
  18483. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  18484. this.abortCurrentFrag();
  18485. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  18486. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  18487. const fragDuration = nextBufferedFrag.duration;
  18488. 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)));
  18489. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  18490. }
  18491. }
  18492. }
  18493. }
  18494. abortCurrentFrag() {
  18495. const fragCurrent = this.fragCurrent;
  18496. this.fragCurrent = null;
  18497. this.backtrackFragment = null;
  18498. if (fragCurrent) {
  18499. fragCurrent.abortRequests();
  18500. this.fragmentTracker.removeFragment(fragCurrent);
  18501. }
  18502. switch (this.state) {
  18503. case State.KEY_LOADING:
  18504. case State.FRAG_LOADING:
  18505. case State.FRAG_LOADING_WAITING_RETRY:
  18506. case State.PARSING:
  18507. case State.PARSED:
  18508. this.state = State.IDLE;
  18509. break;
  18510. }
  18511. this.nextLoadPosition = this.getLoadPosition();
  18512. }
  18513. flushMainBuffer(startOffset, endOffset) {
  18514. super.flushMainBuffer(startOffset, endOffset, this.altAudio ? 'video' : null);
  18515. }
  18516. onMediaAttached(event, data) {
  18517. super.onMediaAttached(event, data);
  18518. const media = data.media;
  18519. this.onvplaying = this.onMediaPlaying.bind(this);
  18520. this.onvseeked = this.onMediaSeeked.bind(this);
  18521. media.addEventListener('playing', this.onvplaying);
  18522. media.addEventListener('seeked', this.onvseeked);
  18523. this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls);
  18524. }
  18525. onMediaDetaching() {
  18526. const {
  18527. media
  18528. } = this;
  18529. if (media && this.onvplaying && this.onvseeked) {
  18530. media.removeEventListener('playing', this.onvplaying);
  18531. media.removeEventListener('seeked', this.onvseeked);
  18532. this.onvplaying = this.onvseeked = null;
  18533. this.videoBuffer = null;
  18534. }
  18535. this.fragPlaying = null;
  18536. if (this.gapController) {
  18537. this.gapController.destroy();
  18538. this.gapController = null;
  18539. }
  18540. super.onMediaDetaching();
  18541. }
  18542. onMediaPlaying() {
  18543. // tick to speed up FRAG_CHANGED triggering
  18544. this.tick();
  18545. }
  18546. onMediaSeeked() {
  18547. const media = this.media;
  18548. const currentTime = media ? media.currentTime : null;
  18549. if (isFiniteNumber(currentTime)) {
  18550. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  18551. }
  18552. // If seeked was issued before buffer was appended do not tick immediately
  18553. const bufferInfo = this.getMainFwdBufferInfo();
  18554. if (bufferInfo === null || bufferInfo.len === 0) {
  18555. this.warn(`Main forward buffer length on "seeked" event ${bufferInfo ? bufferInfo.len : 'empty'})`);
  18556. return;
  18557. }
  18558. // tick to speed up FRAG_CHANGED triggering
  18559. this.tick();
  18560. }
  18561. onManifestLoading() {
  18562. // reset buffer on manifest loading
  18563. this.log('Trigger BUFFER_RESET');
  18564. this.hls.trigger(Events.BUFFER_RESET, undefined);
  18565. this.fragmentTracker.removeAllFragments();
  18566. this.couldBacktrack = false;
  18567. this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
  18568. this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null;
  18569. this.altAudio = this.audioOnly = this.startFragRequested = false;
  18570. }
  18571. onManifestParsed(event, data) {
  18572. // detect if we have different kind of audio codecs used amongst playlists
  18573. let aac = false;
  18574. let heaac = false;
  18575. data.levels.forEach(level => {
  18576. const codec = level.audioCodec;
  18577. if (codec) {
  18578. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  18579. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  18580. }
  18581. });
  18582. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  18583. if (this.audioCodecSwitch) {
  18584. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  18585. }
  18586. this.levels = data.levels;
  18587. this.startFragRequested = false;
  18588. }
  18589. onLevelLoading(event, data) {
  18590. const {
  18591. levels
  18592. } = this;
  18593. if (!levels || this.state !== State.IDLE) {
  18594. return;
  18595. }
  18596. const level = levels[data.level];
  18597. if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) {
  18598. this.state = State.WAITING_LEVEL;
  18599. }
  18600. }
  18601. onLevelLoaded(event, data) {
  18602. var _curLevel$details;
  18603. const {
  18604. levels
  18605. } = this;
  18606. const newLevelId = data.level;
  18607. const newDetails = data.details;
  18608. const duration = newDetails.totalduration;
  18609. if (!levels) {
  18610. this.warn(`Levels were reset while loading level ${newLevelId}`);
  18611. return;
  18612. }
  18613. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  18614. const curLevel = levels[newLevelId];
  18615. const fragCurrent = this.fragCurrent;
  18616. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  18617. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  18618. this.abortCurrentFrag();
  18619. }
  18620. }
  18621. let sliding = 0;
  18622. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  18623. var _this$levelLastLoaded;
  18624. this.checkLiveUpdate(newDetails);
  18625. if (newDetails.deltaUpdateFailed) {
  18626. return;
  18627. }
  18628. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  18629. }
  18630. // override level info
  18631. curLevel.details = newDetails;
  18632. this.levelLastLoaded = curLevel;
  18633. this.hls.trigger(Events.LEVEL_UPDATED, {
  18634. details: newDetails,
  18635. level: newLevelId
  18636. });
  18637. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  18638. if (this.state === State.WAITING_LEVEL) {
  18639. if (this.waitForCdnTuneIn(newDetails)) {
  18640. // Wait for Low-Latency CDN Tune-in
  18641. return;
  18642. }
  18643. this.state = State.IDLE;
  18644. }
  18645. if (!this.startFragRequested) {
  18646. this.setStartPosition(newDetails, sliding);
  18647. } else if (newDetails.live) {
  18648. this.synchronizeToLiveEdge(newDetails);
  18649. }
  18650. // trigger handler right now
  18651. this.tick();
  18652. }
  18653. _handleFragmentLoadProgress(data) {
  18654. var _frag$initSegment;
  18655. const {
  18656. frag,
  18657. part,
  18658. payload
  18659. } = data;
  18660. const {
  18661. levels
  18662. } = this;
  18663. if (!levels) {
  18664. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  18665. return;
  18666. }
  18667. const currentLevel = levels[frag.level];
  18668. const details = currentLevel.details;
  18669. if (!details) {
  18670. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  18671. this.fragmentTracker.removeFragment(frag);
  18672. return;
  18673. }
  18674. const videoCodec = currentLevel.videoCodec;
  18675. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  18676. const accurateTimeOffset = details.PTSKnown || !details.live;
  18677. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  18678. const audioCodec = this._getAudioCodec(currentLevel);
  18679. // transmux the MPEG-TS data to ISO-BMFF segments
  18680. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  18681. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  18682. const partIndex = part ? part.index : -1;
  18683. const partial = partIndex !== -1;
  18684. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  18685. const initPTS = this.initPTS[frag.cc];
  18686. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  18687. }
  18688. onAudioTrackSwitching(event, data) {
  18689. // if any URL found on new audio track, it is an alternate audio track
  18690. const fromAltAudio = this.altAudio;
  18691. const altAudio = !!data.url;
  18692. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  18693. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  18694. // we will just have to change buffer scheduling on audioTrackSwitched
  18695. if (!altAudio) {
  18696. if (this.mediaBuffer !== this.media) {
  18697. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  18698. this.mediaBuffer = this.media;
  18699. const fragCurrent = this.fragCurrent;
  18700. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  18701. if (fragCurrent) {
  18702. this.log('Switching to main audio track, cancel main fragment load');
  18703. fragCurrent.abortRequests();
  18704. this.fragmentTracker.removeFragment(fragCurrent);
  18705. }
  18706. // destroy transmuxer to force init segment generation (following audio switch)
  18707. this.resetTransmuxer();
  18708. // switch to IDLE state to load new fragment
  18709. this.resetLoadingState();
  18710. } else if (this.audioOnly) {
  18711. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  18712. this.resetTransmuxer();
  18713. }
  18714. const hls = this.hls;
  18715. // If switching from alt to main audio, flush all audio and trigger track switched
  18716. if (fromAltAudio) {
  18717. hls.trigger(Events.BUFFER_FLUSHING, {
  18718. startOffset: 0,
  18719. endOffset: Number.POSITIVE_INFINITY,
  18720. type: null
  18721. });
  18722. this.fragmentTracker.removeAllFragments();
  18723. }
  18724. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  18725. }
  18726. }
  18727. onAudioTrackSwitched(event, data) {
  18728. const trackId = data.id;
  18729. const altAudio = !!this.hls.audioTracks[trackId].url;
  18730. if (altAudio) {
  18731. const videoBuffer = this.videoBuffer;
  18732. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  18733. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  18734. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  18735. this.mediaBuffer = videoBuffer;
  18736. }
  18737. }
  18738. this.altAudio = altAudio;
  18739. this.tick();
  18740. }
  18741. onBufferCreated(event, data) {
  18742. const tracks = data.tracks;
  18743. let mediaTrack;
  18744. let name;
  18745. let alternate = false;
  18746. for (const type in tracks) {
  18747. const track = tracks[type];
  18748. if (track.id === 'main') {
  18749. name = type;
  18750. mediaTrack = track;
  18751. // keep video source buffer reference
  18752. if (type === 'video') {
  18753. const videoTrack = tracks[type];
  18754. if (videoTrack) {
  18755. this.videoBuffer = videoTrack.buffer;
  18756. }
  18757. }
  18758. } else {
  18759. alternate = true;
  18760. }
  18761. }
  18762. if (alternate && mediaTrack) {
  18763. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  18764. this.mediaBuffer = mediaTrack.buffer;
  18765. } else {
  18766. this.mediaBuffer = this.media;
  18767. }
  18768. }
  18769. onFragBuffered(event, data) {
  18770. const {
  18771. frag,
  18772. part
  18773. } = data;
  18774. if (frag && frag.type !== PlaylistLevelType.MAIN) {
  18775. return;
  18776. }
  18777. if (this.fragContextChanged(frag)) {
  18778. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  18779. // Avoid setting state back to IDLE, since that will interfere with a level switch
  18780. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  18781. if (this.state === State.PARSED) {
  18782. this.state = State.IDLE;
  18783. }
  18784. return;
  18785. }
  18786. const stats = part ? part.stats : frag.stats;
  18787. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  18788. if (frag.sn !== 'initSegment') {
  18789. this.fragPrevious = frag;
  18790. }
  18791. this.fragBufferedComplete(frag, part);
  18792. }
  18793. onError(event, data) {
  18794. var _data$context;
  18795. if (data.fatal) {
  18796. this.state = State.ERROR;
  18797. return;
  18798. }
  18799. switch (data.details) {
  18800. case ErrorDetails.FRAG_GAP:
  18801. case ErrorDetails.FRAG_PARSING_ERROR:
  18802. case ErrorDetails.FRAG_DECRYPT_ERROR:
  18803. case ErrorDetails.FRAG_LOAD_ERROR:
  18804. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  18805. case ErrorDetails.KEY_LOAD_ERROR:
  18806. case ErrorDetails.KEY_LOAD_TIMEOUT:
  18807. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  18808. break;
  18809. case ErrorDetails.LEVEL_LOAD_ERROR:
  18810. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  18811. case ErrorDetails.LEVEL_PARSING_ERROR:
  18812. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  18813. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  18814. this.state = State.IDLE;
  18815. }
  18816. break;
  18817. case ErrorDetails.BUFFER_APPEND_ERROR:
  18818. case ErrorDetails.BUFFER_FULL_ERROR:
  18819. if (!data.parent || data.parent !== 'main') {
  18820. return;
  18821. }
  18822. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  18823. this.resetLoadingState();
  18824. return;
  18825. }
  18826. if (this.reduceLengthAndFlushBuffer(data)) {
  18827. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  18828. }
  18829. break;
  18830. case ErrorDetails.INTERNAL_EXCEPTION:
  18831. this.recoverWorkerError(data);
  18832. break;
  18833. }
  18834. }
  18835. // Checks the health of the buffer and attempts to resolve playback stalls.
  18836. checkBuffer() {
  18837. const {
  18838. media,
  18839. gapController
  18840. } = this;
  18841. if (!media || !gapController || !media.readyState) {
  18842. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  18843. return;
  18844. }
  18845. if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
  18846. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  18847. const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;
  18848. gapController.poll(this.lastCurrentTime, activeFrag);
  18849. }
  18850. this.lastCurrentTime = media.currentTime;
  18851. }
  18852. onFragLoadEmergencyAborted() {
  18853. this.state = State.IDLE;
  18854. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  18855. // in that case, reset startFragRequested flag
  18856. if (!this.loadedmetadata) {
  18857. this.startFragRequested = false;
  18858. this.nextLoadPosition = this.startPosition;
  18859. }
  18860. this.tickImmediate();
  18861. }
  18862. onBufferFlushed(event, {
  18863. type
  18864. }) {
  18865. if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  18866. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  18867. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  18868. this.tick();
  18869. }
  18870. }
  18871. onLevelsUpdated(event, data) {
  18872. if (this.level > -1 && this.fragCurrent) {
  18873. this.level = this.fragCurrent.level;
  18874. }
  18875. this.levels = data.levels;
  18876. }
  18877. swapAudioCodec() {
  18878. this.audioCodecSwap = !this.audioCodecSwap;
  18879. }
  18880. /**
  18881. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  18882. */
  18883. seekToStartPos() {
  18884. const {
  18885. media
  18886. } = this;
  18887. if (!media) {
  18888. return;
  18889. }
  18890. const currentTime = media.currentTime;
  18891. let startPosition = this.startPosition;
  18892. // only adjust currentTime if different from startPosition or if startPosition not buffered
  18893. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  18894. if (startPosition >= 0 && currentTime < startPosition) {
  18895. if (media.seeking) {
  18896. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  18897. return;
  18898. }
  18899. const buffered = BufferHelper.getBuffered(media);
  18900. const bufferStart = buffered.length ? buffered.start(0) : 0;
  18901. const delta = bufferStart - startPosition;
  18902. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  18903. this.log(`adjusting start position by ${delta} to match buffer start`);
  18904. startPosition += delta;
  18905. this.startPosition = startPosition;
  18906. }
  18907. this.log(`seek to target start position ${startPosition} from current time ${currentTime}`);
  18908. media.currentTime = startPosition;
  18909. }
  18910. }
  18911. _getAudioCodec(currentLevel) {
  18912. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  18913. if (this.audioCodecSwap && audioCodec) {
  18914. this.log('Swapping audio codec');
  18915. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  18916. audioCodec = 'mp4a.40.2';
  18917. } else {
  18918. audioCodec = 'mp4a.40.5';
  18919. }
  18920. }
  18921. return audioCodec;
  18922. }
  18923. _loadBitrateTestFrag(frag, level) {
  18924. frag.bitrateTest = true;
  18925. this._doFragLoad(frag, level).then(data => {
  18926. const {
  18927. hls
  18928. } = this;
  18929. if (!data || this.fragContextChanged(frag)) {
  18930. return;
  18931. }
  18932. level.fragmentError = 0;
  18933. this.state = State.IDLE;
  18934. this.startFragRequested = false;
  18935. this.bitrateTest = false;
  18936. const stats = frag.stats;
  18937. // Bitrate tests fragments are neither parsed nor buffered
  18938. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  18939. hls.trigger(Events.FRAG_LOADED, data);
  18940. frag.bitrateTest = false;
  18941. });
  18942. }
  18943. _handleTransmuxComplete(transmuxResult) {
  18944. var _id3$samples;
  18945. const id = 'main';
  18946. const {
  18947. hls
  18948. } = this;
  18949. const {
  18950. remuxResult,
  18951. chunkMeta
  18952. } = transmuxResult;
  18953. const context = this.getCurrentContext(chunkMeta);
  18954. if (!context) {
  18955. this.resetWhenMissingContext(chunkMeta);
  18956. return;
  18957. }
  18958. const {
  18959. frag,
  18960. part,
  18961. level
  18962. } = context;
  18963. const {
  18964. video,
  18965. text,
  18966. id3,
  18967. initSegment
  18968. } = remuxResult;
  18969. const {
  18970. details
  18971. } = level;
  18972. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  18973. const audio = this.altAudio ? undefined : remuxResult.audio;
  18974. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  18975. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  18976. if (this.fragContextChanged(frag)) {
  18977. this.fragmentTracker.removeFragment(frag);
  18978. return;
  18979. }
  18980. this.state = State.PARSING;
  18981. if (initSegment) {
  18982. if (initSegment != null && initSegment.tracks) {
  18983. const mapFragment = frag.initSegment || frag;
  18984. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  18985. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  18986. frag: mapFragment,
  18987. id,
  18988. tracks: initSegment.tracks
  18989. });
  18990. }
  18991. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  18992. const initPTS = initSegment.initPTS;
  18993. const timescale = initSegment.timescale;
  18994. if (isFiniteNumber(initPTS)) {
  18995. this.initPTS[frag.cc] = {
  18996. baseTime: initPTS,
  18997. timescale
  18998. };
  18999. hls.trigger(Events.INIT_PTS_FOUND, {
  19000. frag,
  19001. id,
  19002. initPTS,
  19003. timescale
  19004. });
  19005. }
  19006. }
  19007. // Avoid buffering if backtracking this fragment
  19008. if (video && details && frag.sn !== 'initSegment') {
  19009. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  19010. const isFirstFragment = frag.sn === details.startSN;
  19011. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  19012. if (remuxResult.independent !== false) {
  19013. const {
  19014. startPTS,
  19015. endPTS,
  19016. startDTS,
  19017. endDTS
  19018. } = video;
  19019. if (part) {
  19020. part.elementaryStreams[video.type] = {
  19021. startPTS,
  19022. endPTS,
  19023. startDTS,
  19024. endDTS
  19025. };
  19026. } else {
  19027. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  19028. this.couldBacktrack = true;
  19029. }
  19030. if (video.dropped && video.independent) {
  19031. // Backtrack if dropped frames create a gap after currentTime
  19032. const bufferInfo = this.getMainFwdBufferInfo();
  19033. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  19034. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  19035. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  19036. this.backtrack(frag);
  19037. return;
  19038. } else if (isFirstInDiscontinuity) {
  19039. // Mark segment with a gap to avoid loop loading
  19040. frag.gap = true;
  19041. }
  19042. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  19043. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  19044. } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {
  19045. // Mark segment with a gap to skip large start gap
  19046. frag.gap = true;
  19047. }
  19048. }
  19049. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  19050. if (this.backtrackFragment) {
  19051. this.backtrackFragment = frag;
  19052. }
  19053. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  19054. } else if (isFirstFragment || isFirstInDiscontinuity) {
  19055. // Mark segment with a gap to avoid loop loading
  19056. frag.gap = true;
  19057. } else {
  19058. this.backtrack(frag);
  19059. return;
  19060. }
  19061. }
  19062. if (audio) {
  19063. const {
  19064. startPTS,
  19065. endPTS,
  19066. startDTS,
  19067. endDTS
  19068. } = audio;
  19069. if (part) {
  19070. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  19071. startPTS,
  19072. endPTS,
  19073. startDTS,
  19074. endDTS
  19075. };
  19076. }
  19077. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  19078. this.bufferFragmentData(audio, frag, part, chunkMeta);
  19079. }
  19080. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  19081. const emittedID3 = {
  19082. id,
  19083. frag,
  19084. details,
  19085. samples: id3.samples
  19086. };
  19087. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  19088. }
  19089. if (details && text) {
  19090. const emittedText = {
  19091. id,
  19092. frag,
  19093. details,
  19094. samples: text.samples
  19095. };
  19096. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  19097. }
  19098. }
  19099. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  19100. if (this.state !== State.PARSING) {
  19101. return;
  19102. }
  19103. this.audioOnly = !!tracks.audio && !tracks.video;
  19104. // if audio track is expected to come from audio stream controller, discard any coming from main
  19105. if (this.altAudio && !this.audioOnly) {
  19106. delete tracks.audio;
  19107. }
  19108. // include levelCodec in audio and video tracks
  19109. const {
  19110. audio,
  19111. video,
  19112. audiovideo
  19113. } = tracks;
  19114. if (audio) {
  19115. let audioCodec = currentLevel.audioCodec;
  19116. const ua = navigator.userAgent.toLowerCase();
  19117. if (this.audioCodecSwitch) {
  19118. if (audioCodec) {
  19119. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  19120. audioCodec = 'mp4a.40.2';
  19121. } else {
  19122. audioCodec = 'mp4a.40.5';
  19123. }
  19124. }
  19125. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  19126. // force HE-AAC, as it seems that most browsers prefers it.
  19127. // don't force HE-AAC if mono stream, or in Firefox
  19128. const audioMetadata = audio.metadata;
  19129. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  19130. audioCodec = 'mp4a.40.5';
  19131. }
  19132. }
  19133. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  19134. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  19135. // Exclude mpeg audio
  19136. audioCodec = 'mp4a.40.2';
  19137. this.log(`Android: force audio codec to ${audioCodec}`);
  19138. }
  19139. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  19140. this.log(`Swapping manifest audio codec "${currentLevel.audioCodec}" for "${audioCodec}"`);
  19141. }
  19142. audio.levelCodec = audioCodec;
  19143. audio.id = 'main';
  19144. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${currentLevel.audioCodec || ''}/${audio.codec}]`);
  19145. }
  19146. if (video) {
  19147. video.levelCodec = currentLevel.videoCodec;
  19148. video.id = 'main';
  19149. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${video.codec}]`);
  19150. }
  19151. if (audiovideo) {
  19152. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  19153. }
  19154. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  19155. // loop through tracks that are going to be provided to bufferController
  19156. Object.keys(tracks).forEach(trackName => {
  19157. const track = tracks[trackName];
  19158. const initSegment = track.initSegment;
  19159. if (initSegment != null && initSegment.byteLength) {
  19160. this.hls.trigger(Events.BUFFER_APPENDING, {
  19161. type: trackName,
  19162. data: initSegment,
  19163. frag,
  19164. part: null,
  19165. chunkMeta,
  19166. parent: frag.type
  19167. });
  19168. }
  19169. });
  19170. // trigger handler right now
  19171. this.tickImmediate();
  19172. }
  19173. getMainFwdBufferInfo() {
  19174. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN);
  19175. }
  19176. backtrack(frag) {
  19177. this.couldBacktrack = true;
  19178. // Causes findFragments to backtrack through fragments to find the keyframe
  19179. this.backtrackFragment = frag;
  19180. this.resetTransmuxer();
  19181. this.flushBufferGap(frag);
  19182. this.fragmentTracker.removeFragment(frag);
  19183. this.fragPrevious = null;
  19184. this.nextLoadPosition = frag.start;
  19185. this.state = State.IDLE;
  19186. }
  19187. checkFragmentChanged() {
  19188. const video = this.media;
  19189. let fragPlayingCurrent = null;
  19190. if (video && video.readyState > 1 && video.seeking === false) {
  19191. const currentTime = video.currentTime;
  19192. /* if video element is in seeked state, currentTime can only increase.
  19193. (assuming that playback rate is positive ...)
  19194. As sometimes currentTime jumps back to zero after a
  19195. media decode error, check this, to avoid seeking back to
  19196. wrong position after a media decode error
  19197. */
  19198. if (BufferHelper.isBuffered(video, currentTime)) {
  19199. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  19200. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  19201. /* ensure that FRAG_CHANGED event is triggered at startup,
  19202. when first video frame is displayed and playback is paused.
  19203. add a tolerance of 100ms, in case current position is not buffered,
  19204. check if current pos+100ms is buffered and use that buffer range
  19205. for FRAG_CHANGED event reporting */
  19206. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  19207. }
  19208. if (fragPlayingCurrent) {
  19209. this.backtrackFragment = null;
  19210. const fragPlaying = this.fragPlaying;
  19211. const fragCurrentLevel = fragPlayingCurrent.level;
  19212. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  19213. this.fragPlaying = fragPlayingCurrent;
  19214. this.hls.trigger(Events.FRAG_CHANGED, {
  19215. frag: fragPlayingCurrent
  19216. });
  19217. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  19218. this.hls.trigger(Events.LEVEL_SWITCHED, {
  19219. level: fragCurrentLevel
  19220. });
  19221. }
  19222. }
  19223. }
  19224. }
  19225. }
  19226. get nextLevel() {
  19227. const frag = this.nextBufferedFrag;
  19228. if (frag) {
  19229. return frag.level;
  19230. }
  19231. return -1;
  19232. }
  19233. get currentFrag() {
  19234. const media = this.media;
  19235. if (media) {
  19236. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  19237. }
  19238. return null;
  19239. }
  19240. get currentProgramDateTime() {
  19241. const media = this.media;
  19242. if (media) {
  19243. const currentTime = media.currentTime;
  19244. const frag = this.currentFrag;
  19245. if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) {
  19246. const epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  19247. return new Date(epocMs);
  19248. }
  19249. }
  19250. return null;
  19251. }
  19252. get currentLevel() {
  19253. const frag = this.currentFrag;
  19254. if (frag) {
  19255. return frag.level;
  19256. }
  19257. return -1;
  19258. }
  19259. get nextBufferedFrag() {
  19260. const frag = this.currentFrag;
  19261. if (frag) {
  19262. return this.followingBufferedFrag(frag);
  19263. }
  19264. return null;
  19265. }
  19266. get forceStartLoad() {
  19267. return this._forceStartLoad;
  19268. }
  19269. }
  19270. /**
  19271. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  19272. * @public
  19273. */
  19274. class Hls {
  19275. /**
  19276. * Get the video-dev/hls.js package version.
  19277. */
  19278. static get version() {
  19279. return "1.5.15";
  19280. }
  19281. /**
  19282. * Check if the required MediaSource Extensions are available.
  19283. */
  19284. static isMSESupported() {
  19285. return isMSESupported();
  19286. }
  19287. /**
  19288. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  19289. */
  19290. static isSupported() {
  19291. return isSupported();
  19292. }
  19293. /**
  19294. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  19295. */
  19296. static getMediaSource() {
  19297. return getMediaSource();
  19298. }
  19299. static get Events() {
  19300. return Events;
  19301. }
  19302. static get ErrorTypes() {
  19303. return ErrorTypes;
  19304. }
  19305. static get ErrorDetails() {
  19306. return ErrorDetails;
  19307. }
  19308. /**
  19309. * Get the default configuration applied to new instances.
  19310. */
  19311. static get DefaultConfig() {
  19312. if (!Hls.defaultConfig) {
  19313. return hlsDefaultConfig;
  19314. }
  19315. return Hls.defaultConfig;
  19316. }
  19317. /**
  19318. * Replace the default configuration applied to new instances.
  19319. */
  19320. static set DefaultConfig(defaultConfig) {
  19321. Hls.defaultConfig = defaultConfig;
  19322. }
  19323. /**
  19324. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  19325. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  19326. */
  19327. constructor(userConfig = {}) {
  19328. /**
  19329. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  19330. */
  19331. this.config = void 0;
  19332. /**
  19333. * The configuration object provided on player instantiation.
  19334. */
  19335. this.userConfig = void 0;
  19336. this.coreComponents = void 0;
  19337. this.networkControllers = void 0;
  19338. this.started = false;
  19339. this._emitter = new EventEmitter();
  19340. this._autoLevelCapping = -1;
  19341. this._maxHdcpLevel = null;
  19342. this.abrController = void 0;
  19343. this.bufferController = void 0;
  19344. this.capLevelController = void 0;
  19345. this.latencyController = void 0;
  19346. this.levelController = void 0;
  19347. this.streamController = void 0;
  19348. this.audioTrackController = void 0;
  19349. this.subtitleTrackController = void 0;
  19350. this.emeController = void 0;
  19351. this.cmcdController = void 0;
  19352. this._media = null;
  19353. this.url = null;
  19354. this.triggeringException = void 0;
  19355. enableLogs(userConfig.debug || false, 'Hls instance');
  19356. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig);
  19357. this.userConfig = userConfig;
  19358. if (config.progressive) {
  19359. enableStreamingMode(config);
  19360. }
  19361. // core controllers and network loaders
  19362. const {
  19363. abrController: ConfigAbrController,
  19364. bufferController: ConfigBufferController,
  19365. capLevelController: ConfigCapLevelController,
  19366. errorController: ConfigErrorController,
  19367. fpsController: ConfigFpsController
  19368. } = config;
  19369. const errorController = new ConfigErrorController(this);
  19370. const abrController = this.abrController = new ConfigAbrController(this);
  19371. const bufferController = this.bufferController = new ConfigBufferController(this);
  19372. const capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  19373. const fpsController = new ConfigFpsController(this);
  19374. const playListLoader = new PlaylistLoader(this);
  19375. const id3TrackController = new ID3TrackController(this);
  19376. const ConfigContentSteeringController = config.contentSteeringController;
  19377. // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first
  19378. const contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null;
  19379. const levelController = this.levelController = new LevelController(this, contentSteering);
  19380. // FragmentTracker must be defined before StreamController because the order of event handling is important
  19381. const fragmentTracker = new FragmentTracker(this);
  19382. const keyLoader = new KeyLoader(this.config);
  19383. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  19384. // Cap level controller uses streamController to flush the buffer
  19385. capLevelController.setStreamController(streamController);
  19386. // fpsController uses streamController to switch when frames are being dropped
  19387. fpsController.setStreamController(streamController);
  19388. const networkControllers = [playListLoader, levelController, streamController];
  19389. if (contentSteering) {
  19390. networkControllers.splice(1, 0, contentSteering);
  19391. }
  19392. this.networkControllers = networkControllers;
  19393. const coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  19394. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  19395. const AudioStreamControllerClass = config.audioStreamController;
  19396. if (AudioStreamControllerClass) {
  19397. networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  19398. }
  19399. // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important
  19400. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  19401. const SubtitleStreamControllerClass = config.subtitleStreamController;
  19402. if (SubtitleStreamControllerClass) {
  19403. networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  19404. }
  19405. this.createController(config.timelineController, coreComponents);
  19406. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  19407. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  19408. this.latencyController = this.createController(LatencyController, coreComponents);
  19409. this.coreComponents = coreComponents;
  19410. // Error controller handles errors before and after all other controllers
  19411. // This listener will be invoked after all other controllers error listeners
  19412. networkControllers.push(errorController);
  19413. const onErrorOut = errorController.onErrorOut;
  19414. if (typeof onErrorOut === 'function') {
  19415. this.on(Events.ERROR, onErrorOut, errorController);
  19416. }
  19417. }
  19418. createController(ControllerClass, components) {
  19419. if (ControllerClass) {
  19420. const controllerInstance = new ControllerClass(this);
  19421. if (components) {
  19422. components.push(controllerInstance);
  19423. }
  19424. return controllerInstance;
  19425. }
  19426. return null;
  19427. }
  19428. // Delegate the EventEmitter through the public API of Hls.js
  19429. on(event, listener, context = this) {
  19430. this._emitter.on(event, listener, context);
  19431. }
  19432. once(event, listener, context = this) {
  19433. this._emitter.once(event, listener, context);
  19434. }
  19435. removeAllListeners(event) {
  19436. this._emitter.removeAllListeners(event);
  19437. }
  19438. off(event, listener, context = this, once) {
  19439. this._emitter.off(event, listener, context, once);
  19440. }
  19441. listeners(event) {
  19442. return this._emitter.listeners(event);
  19443. }
  19444. emit(event, name, eventObject) {
  19445. return this._emitter.emit(event, name, eventObject);
  19446. }
  19447. trigger(event, eventObject) {
  19448. if (this.config.debug) {
  19449. return this.emit(event, event, eventObject);
  19450. } else {
  19451. try {
  19452. return this.emit(event, event, eventObject);
  19453. } catch (error) {
  19454. logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  19455. // Prevent recursion in error event handlers that throw #5497
  19456. if (!this.triggeringException) {
  19457. this.triggeringException = true;
  19458. const fatal = event === Events.ERROR;
  19459. this.trigger(Events.ERROR, {
  19460. type: ErrorTypes.OTHER_ERROR,
  19461. details: ErrorDetails.INTERNAL_EXCEPTION,
  19462. fatal,
  19463. event,
  19464. error
  19465. });
  19466. this.triggeringException = false;
  19467. }
  19468. }
  19469. }
  19470. return false;
  19471. }
  19472. listenerCount(event) {
  19473. return this._emitter.listenerCount(event);
  19474. }
  19475. /**
  19476. * Dispose of the instance
  19477. */
  19478. destroy() {
  19479. logger.log('destroy');
  19480. this.trigger(Events.DESTROYING, undefined);
  19481. this.detachMedia();
  19482. this.removeAllListeners();
  19483. this._autoLevelCapping = -1;
  19484. this.url = null;
  19485. this.networkControllers.forEach(component => component.destroy());
  19486. this.networkControllers.length = 0;
  19487. this.coreComponents.forEach(component => component.destroy());
  19488. this.coreComponents.length = 0;
  19489. // Remove any references that could be held in config options or callbacks
  19490. const config = this.config;
  19491. config.xhrSetup = config.fetchSetup = undefined;
  19492. // @ts-ignore
  19493. this.userConfig = null;
  19494. }
  19495. /**
  19496. * Attaches Hls.js to a media element
  19497. */
  19498. attachMedia(media) {
  19499. logger.log('attachMedia');
  19500. this._media = media;
  19501. this.trigger(Events.MEDIA_ATTACHING, {
  19502. media: media
  19503. });
  19504. }
  19505. /**
  19506. * Detach Hls.js from the media
  19507. */
  19508. detachMedia() {
  19509. logger.log('detachMedia');
  19510. this.trigger(Events.MEDIA_DETACHING, undefined);
  19511. this._media = null;
  19512. }
  19513. /**
  19514. * Set the source URL. Can be relative or absolute.
  19515. */
  19516. loadSource(url) {
  19517. this.stopLoad();
  19518. const media = this.media;
  19519. const loadedSource = this.url;
  19520. const loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  19521. alwaysNormalize: true
  19522. });
  19523. this._autoLevelCapping = -1;
  19524. this._maxHdcpLevel = null;
  19525. logger.log(`loadSource:${loadingSource}`);
  19526. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  19527. this.detachMedia();
  19528. this.attachMedia(media);
  19529. }
  19530. // when attaching to a source URL, trigger a playlist load
  19531. this.trigger(Events.MANIFEST_LOADING, {
  19532. url: url
  19533. });
  19534. }
  19535. /**
  19536. * Start loading data from the stream source.
  19537. * Depending on default config, client starts loading automatically when a source is set.
  19538. *
  19539. * @param startPosition - Set the start position to stream from.
  19540. * Defaults to -1 (None: starts from earliest point)
  19541. */
  19542. startLoad(startPosition = -1) {
  19543. logger.log(`startLoad(${startPosition})`);
  19544. this.started = true;
  19545. this.networkControllers.forEach(controller => {
  19546. controller.startLoad(startPosition);
  19547. });
  19548. }
  19549. /**
  19550. * Stop loading of any stream data.
  19551. */
  19552. stopLoad() {
  19553. logger.log('stopLoad');
  19554. this.started = false;
  19555. this.networkControllers.forEach(controller => {
  19556. controller.stopLoad();
  19557. });
  19558. }
  19559. /**
  19560. * Resumes stream controller segment loading if previously started.
  19561. */
  19562. resumeBuffering() {
  19563. if (this.started) {
  19564. this.networkControllers.forEach(controller => {
  19565. if ('fragmentLoader' in controller) {
  19566. controller.startLoad(-1);
  19567. }
  19568. });
  19569. }
  19570. }
  19571. /**
  19572. * Stops stream controller segment loading without changing 'started' state like stopLoad().
  19573. * This allows for media buffering to be paused without interupting playlist loading.
  19574. */
  19575. pauseBuffering() {
  19576. this.networkControllers.forEach(controller => {
  19577. if ('fragmentLoader' in controller) {
  19578. controller.stopLoad();
  19579. }
  19580. });
  19581. }
  19582. /**
  19583. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  19584. */
  19585. swapAudioCodec() {
  19586. logger.log('swapAudioCodec');
  19587. this.streamController.swapAudioCodec();
  19588. }
  19589. /**
  19590. * When the media-element fails, this allows to detach and then re-attach it
  19591. * as one call (convenience method).
  19592. *
  19593. * Automatic recovery of media-errors by this process is configurable.
  19594. */
  19595. recoverMediaError() {
  19596. logger.log('recoverMediaError');
  19597. const media = this._media;
  19598. this.detachMedia();
  19599. if (media) {
  19600. this.attachMedia(media);
  19601. }
  19602. }
  19603. removeLevel(levelIndex) {
  19604. this.levelController.removeLevel(levelIndex);
  19605. }
  19606. /**
  19607. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  19608. */
  19609. get levels() {
  19610. const levels = this.levelController.levels;
  19611. return levels ? levels : [];
  19612. }
  19613. /**
  19614. * Index of quality level (variant) currently played
  19615. */
  19616. get currentLevel() {
  19617. return this.streamController.currentLevel;
  19618. }
  19619. /**
  19620. * 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.
  19621. */
  19622. set currentLevel(newLevel) {
  19623. logger.log(`set currentLevel:${newLevel}`);
  19624. this.levelController.manualLevel = newLevel;
  19625. this.streamController.immediateLevelSwitch();
  19626. }
  19627. /**
  19628. * Index of next quality level loaded as scheduled by stream controller.
  19629. */
  19630. get nextLevel() {
  19631. return this.streamController.nextLevel;
  19632. }
  19633. /**
  19634. * Set quality level index for next loaded data.
  19635. * This will switch the video quality asap, without interrupting playback.
  19636. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  19637. * @param newLevel - Pass -1 for automatic level selection
  19638. */
  19639. set nextLevel(newLevel) {
  19640. logger.log(`set nextLevel:${newLevel}`);
  19641. this.levelController.manualLevel = newLevel;
  19642. this.streamController.nextLevelSwitch();
  19643. }
  19644. /**
  19645. * Return the quality level of the currently or last (of none is loaded currently) segment
  19646. */
  19647. get loadLevel() {
  19648. return this.levelController.level;
  19649. }
  19650. /**
  19651. * Set quality level index for next loaded data in a conservative way.
  19652. * This will switch the quality without flushing, but interrupt current loading.
  19653. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  19654. * @param newLevel - Pass -1 for automatic level selection
  19655. */
  19656. set loadLevel(newLevel) {
  19657. logger.log(`set loadLevel:${newLevel}`);
  19658. this.levelController.manualLevel = newLevel;
  19659. }
  19660. /**
  19661. * get next quality level loaded
  19662. */
  19663. get nextLoadLevel() {
  19664. return this.levelController.nextLoadLevel;
  19665. }
  19666. /**
  19667. * Set quality level of next loaded segment in a fully "non-destructive" way.
  19668. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  19669. */
  19670. set nextLoadLevel(level) {
  19671. this.levelController.nextLoadLevel = level;
  19672. }
  19673. /**
  19674. * Return "first level": like a default level, if not set,
  19675. * falls back to index of first level referenced in manifest
  19676. */
  19677. get firstLevel() {
  19678. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  19679. }
  19680. /**
  19681. * Sets "first-level", see getter.
  19682. */
  19683. set firstLevel(newLevel) {
  19684. logger.log(`set firstLevel:${newLevel}`);
  19685. this.levelController.firstLevel = newLevel;
  19686. }
  19687. /**
  19688. * Return the desired start level for the first fragment that will be loaded.
  19689. * The default value of -1 indicates automatic start level selection.
  19690. * Setting hls.nextAutoLevel without setting a startLevel will result in
  19691. * the nextAutoLevel value being used for one fragment load.
  19692. */
  19693. get startLevel() {
  19694. const startLevel = this.levelController.startLevel;
  19695. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  19696. return this.abrController.forcedAutoLevel;
  19697. }
  19698. return startLevel;
  19699. }
  19700. /**
  19701. * set start level (level of first fragment that will be played back)
  19702. * if not overrided by user, first level appearing in manifest will be used as start level
  19703. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  19704. * (determined from download of first segment)
  19705. */
  19706. set startLevel(newLevel) {
  19707. logger.log(`set startLevel:${newLevel}`);
  19708. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  19709. if (newLevel !== -1) {
  19710. newLevel = Math.max(newLevel, this.minAutoLevel);
  19711. }
  19712. this.levelController.startLevel = newLevel;
  19713. }
  19714. /**
  19715. * Whether level capping is enabled.
  19716. * Default value is set via `config.capLevelToPlayerSize`.
  19717. */
  19718. get capLevelToPlayerSize() {
  19719. return this.config.capLevelToPlayerSize;
  19720. }
  19721. /**
  19722. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  19723. */
  19724. set capLevelToPlayerSize(shouldStartCapping) {
  19725. const newCapLevelToPlayerSize = !!shouldStartCapping;
  19726. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  19727. if (newCapLevelToPlayerSize) {
  19728. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  19729. } else {
  19730. this.capLevelController.stopCapping();
  19731. this.autoLevelCapping = -1;
  19732. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  19733. }
  19734. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  19735. }
  19736. }
  19737. /**
  19738. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  19739. */
  19740. get autoLevelCapping() {
  19741. return this._autoLevelCapping;
  19742. }
  19743. /**
  19744. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  19745. */
  19746. get bandwidthEstimate() {
  19747. const {
  19748. bwEstimator
  19749. } = this.abrController;
  19750. if (!bwEstimator) {
  19751. return NaN;
  19752. }
  19753. return bwEstimator.getEstimate();
  19754. }
  19755. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  19756. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  19757. }
  19758. /**
  19759. * get time to first byte estimate
  19760. * @type {number}
  19761. */
  19762. get ttfbEstimate() {
  19763. const {
  19764. bwEstimator
  19765. } = this.abrController;
  19766. if (!bwEstimator) {
  19767. return NaN;
  19768. }
  19769. return bwEstimator.getEstimateTTFB();
  19770. }
  19771. /**
  19772. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  19773. */
  19774. set autoLevelCapping(newLevel) {
  19775. if (this._autoLevelCapping !== newLevel) {
  19776. logger.log(`set autoLevelCapping:${newLevel}`);
  19777. this._autoLevelCapping = newLevel;
  19778. this.levelController.checkMaxAutoUpdated();
  19779. }
  19780. }
  19781. get maxHdcpLevel() {
  19782. return this._maxHdcpLevel;
  19783. }
  19784. set maxHdcpLevel(value) {
  19785. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  19786. this._maxHdcpLevel = value;
  19787. this.levelController.checkMaxAutoUpdated();
  19788. }
  19789. }
  19790. /**
  19791. * True when automatic level selection enabled
  19792. */
  19793. get autoLevelEnabled() {
  19794. return this.levelController.manualLevel === -1;
  19795. }
  19796. /**
  19797. * Level set manually (if any)
  19798. */
  19799. get manualLevel() {
  19800. return this.levelController.manualLevel;
  19801. }
  19802. /**
  19803. * min level selectable in auto mode according to config.minAutoBitrate
  19804. */
  19805. get minAutoLevel() {
  19806. const {
  19807. levels,
  19808. config: {
  19809. minAutoBitrate
  19810. }
  19811. } = this;
  19812. if (!levels) return 0;
  19813. const len = levels.length;
  19814. for (let i = 0; i < len; i++) {
  19815. if (levels[i].maxBitrate >= minAutoBitrate) {
  19816. return i;
  19817. }
  19818. }
  19819. return 0;
  19820. }
  19821. /**
  19822. * max level selectable in auto mode according to autoLevelCapping
  19823. */
  19824. get maxAutoLevel() {
  19825. const {
  19826. levels,
  19827. autoLevelCapping,
  19828. maxHdcpLevel
  19829. } = this;
  19830. let maxAutoLevel;
  19831. if (autoLevelCapping === -1 && levels != null && levels.length) {
  19832. maxAutoLevel = levels.length - 1;
  19833. } else {
  19834. maxAutoLevel = autoLevelCapping;
  19835. }
  19836. if (maxHdcpLevel) {
  19837. for (let i = maxAutoLevel; i--;) {
  19838. const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  19839. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  19840. return i;
  19841. }
  19842. }
  19843. }
  19844. return maxAutoLevel;
  19845. }
  19846. get firstAutoLevel() {
  19847. return this.abrController.firstAutoLevel;
  19848. }
  19849. /**
  19850. * next automatically selected quality level
  19851. */
  19852. get nextAutoLevel() {
  19853. return this.abrController.nextAutoLevel;
  19854. }
  19855. /**
  19856. * this setter is used to force next auto level.
  19857. * this is useful to force a switch down in auto mode:
  19858. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  19859. * forced value is valid for one fragment. upon successful frag loading at forced level,
  19860. * this value will be resetted to -1 by ABR controller.
  19861. */
  19862. set nextAutoLevel(nextLevel) {
  19863. this.abrController.nextAutoLevel = nextLevel;
  19864. }
  19865. /**
  19866. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  19867. */
  19868. get playingDate() {
  19869. return this.streamController.currentProgramDateTime;
  19870. }
  19871. get mainForwardBufferInfo() {
  19872. return this.streamController.getMainFwdBufferInfo();
  19873. }
  19874. /**
  19875. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  19876. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  19877. */
  19878. setAudioOption(audioOption) {
  19879. var _this$audioTrackContr;
  19880. return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption);
  19881. }
  19882. /**
  19883. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  19884. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  19885. */
  19886. setSubtitleOption(subtitleOption) {
  19887. var _this$subtitleTrackCo;
  19888. (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption);
  19889. return null;
  19890. }
  19891. /**
  19892. * Get the complete list of audio tracks across all media groups
  19893. */
  19894. get allAudioTracks() {
  19895. const audioTrackController = this.audioTrackController;
  19896. return audioTrackController ? audioTrackController.allAudioTracks : [];
  19897. }
  19898. /**
  19899. * Get the list of selectable audio tracks
  19900. */
  19901. get audioTracks() {
  19902. const audioTrackController = this.audioTrackController;
  19903. return audioTrackController ? audioTrackController.audioTracks : [];
  19904. }
  19905. /**
  19906. * index of the selected audio track (index in audio track lists)
  19907. */
  19908. get audioTrack() {
  19909. const audioTrackController = this.audioTrackController;
  19910. return audioTrackController ? audioTrackController.audioTrack : -1;
  19911. }
  19912. /**
  19913. * selects an audio track, based on its index in audio track lists
  19914. */
  19915. set audioTrack(audioTrackId) {
  19916. const audioTrackController = this.audioTrackController;
  19917. if (audioTrackController) {
  19918. audioTrackController.audioTrack = audioTrackId;
  19919. }
  19920. }
  19921. /**
  19922. * get the complete list of subtitle tracks across all media groups
  19923. */
  19924. get allSubtitleTracks() {
  19925. const subtitleTrackController = this.subtitleTrackController;
  19926. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  19927. }
  19928. /**
  19929. * get alternate subtitle tracks list from playlist
  19930. */
  19931. get subtitleTracks() {
  19932. const subtitleTrackController = this.subtitleTrackController;
  19933. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  19934. }
  19935. /**
  19936. * index of the selected subtitle track (index in subtitle track lists)
  19937. */
  19938. get subtitleTrack() {
  19939. const subtitleTrackController = this.subtitleTrackController;
  19940. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  19941. }
  19942. get media() {
  19943. return this._media;
  19944. }
  19945. /**
  19946. * select an subtitle track, based on its index in subtitle track lists
  19947. */
  19948. set subtitleTrack(subtitleTrackId) {
  19949. const subtitleTrackController = this.subtitleTrackController;
  19950. if (subtitleTrackController) {
  19951. subtitleTrackController.subtitleTrack = subtitleTrackId;
  19952. }
  19953. }
  19954. /**
  19955. * Whether subtitle display is enabled or not
  19956. */
  19957. get subtitleDisplay() {
  19958. const subtitleTrackController = this.subtitleTrackController;
  19959. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  19960. }
  19961. /**
  19962. * Enable/disable subtitle display rendering
  19963. */
  19964. set subtitleDisplay(value) {
  19965. const subtitleTrackController = this.subtitleTrackController;
  19966. if (subtitleTrackController) {
  19967. subtitleTrackController.subtitleDisplay = value;
  19968. }
  19969. }
  19970. /**
  19971. * get mode for Low-Latency HLS loading
  19972. */
  19973. get lowLatencyMode() {
  19974. return this.config.lowLatencyMode;
  19975. }
  19976. /**
  19977. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  19978. */
  19979. set lowLatencyMode(mode) {
  19980. this.config.lowLatencyMode = mode;
  19981. }
  19982. /**
  19983. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  19984. * @returns null prior to loading live Playlist
  19985. */
  19986. get liveSyncPosition() {
  19987. return this.latencyController.liveSyncPosition;
  19988. }
  19989. /**
  19990. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  19991. * @returns 0 before first playlist is loaded
  19992. */
  19993. get latency() {
  19994. return this.latencyController.latency;
  19995. }
  19996. /**
  19997. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  19998. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  19999. * @returns 0 before first playlist is loaded
  20000. */
  20001. get maxLatency() {
  20002. return this.latencyController.maxLatency;
  20003. }
  20004. /**
  20005. * target distance from the edge as calculated by the latency controller
  20006. */
  20007. get targetLatency() {
  20008. return this.latencyController.targetLatency;
  20009. }
  20010. /**
  20011. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  20012. */
  20013. get drift() {
  20014. return this.latencyController.drift;
  20015. }
  20016. /**
  20017. * set to true when startLoad is called before MANIFEST_PARSED event
  20018. */
  20019. get forceStartLoad() {
  20020. return this.streamController.forceStartLoad;
  20021. }
  20022. }
  20023. Hls.defaultConfig = void 0;
  20024. var KeySystemFormats = emptyEs.KeySystemFormats;
  20025. var KeySystems = emptyEs.KeySystems;
  20026. var SubtitleStreamController = emptyEs.SubtitleStreamController;
  20027. var TimelineController = emptyEs.TimelineController;
  20028. export { AbrController, AttrList, Cues as AudioStreamController, Cues as AudioTrackController, BasePlaylistController, BaseSegment, BaseStreamController, BufferController, Cues as CMCDController, CapLevelController, ChunkMetadata, ContentSteeringController, DateRange, Cues as EMEController, ErrorActionFlags, ErrorController, ErrorDetails, ErrorTypes, Events, FPSController, Fragment, Hls, HlsSkip, HlsUrlParameters, KeySystemFormats, KeySystems, Level, LevelDetails, LevelKey, LoadStats, MetadataSchema, NetworkErrorAction, Part, PlaylistLevelType, SubtitleStreamController, Cues as SubtitleTrackController, TimelineController, Hls as default, getMediaSource, isMSESupported, isSupported };
  20029. //# sourceMappingURL=hls.light.mjs.map