hls.mjs 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385
  1. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  2. const isFiniteNumber = Number.isFinite || function (value) {
  3. return typeof value === 'number' && isFinite(value);
  4. };
  5. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  6. const isSafeInteger = Number.isSafeInteger || function (value) {
  7. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  8. };
  9. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10. let ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  11. // Identifier for a network error (loading error / timeout ...)
  12. ErrorTypes["NETWORK_ERROR"] = "networkError";
  13. // Identifier for a media Error (video/parsing/mediasource error)
  14. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  15. // EME (encrypted media extensions) errors
  16. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  17. // Identifier for a mux Error (demuxing/remuxing)
  18. ErrorTypes["MUX_ERROR"] = "muxError";
  19. // Identifier for all other errors
  20. ErrorTypes["OTHER_ERROR"] = "otherError";
  21. return ErrorTypes;
  22. }({});
  23. let ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  24. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  25. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  26. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  27. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  28. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  29. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  30. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  31. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  32. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  33. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  34. ErrorDetails["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  35. ErrorDetails["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  36. ErrorDetails["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  37. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  38. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  39. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  40. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  41. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  42. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  43. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  44. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  45. // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: "no fragments found in level", level: index of the bad level }
  46. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  47. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  48. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  49. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  50. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  51. // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }
  52. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  53. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  54. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  55. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  56. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  57. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  58. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  59. // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  60. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  61. // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  62. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  63. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  64. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  65. // Identifier for fragment load timeout error - data: { frag : fragment object}
  66. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  67. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  68. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  69. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  70. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  71. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  72. // Identifier for a fragment or part load skipped because of a GAP tag or attribute
  73. ErrorDetails["FRAG_GAP"] = "fragGap";
  74. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  75. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  76. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  77. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  78. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  79. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  80. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }
  81. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  82. // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }
  83. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  84. // Identifier for a buffer append error - data: append error description
  85. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  86. // Identifier for a buffer appending error event - data: appending error description
  87. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  88. // Identifier for a buffer stalled error event
  89. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  90. // Identifier for a buffer full event
  91. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  92. // Identifier for a buffer seek over hole event
  93. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  94. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  95. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  96. // Identifier for a Interstitial Asset List load error - data: { url: faulty URL, response: { code: error code, text: error text } }
  97. ErrorDetails["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  98. // Identifier for a Interstitial Asset List load timeout - data: { url: faulty URL, response: { code: error code, text: error text } }
  99. ErrorDetails["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  100. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  101. ErrorDetails["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  102. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  103. ErrorDetails["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  104. // Identifier for an internal exception happening inside hls.js while handling an event
  105. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  106. // Identifier for an internal call to abort a loader
  107. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  108. // Triggered when attachMedia fails
  109. ErrorDetails["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  110. // Uncategorized error
  111. ErrorDetails["UNKNOWN"] = "unknown";
  112. return ErrorDetails;
  113. }({});
  114. let Events = /*#__PURE__*/function (Events) {
  115. // Fired before MediaSource is attaching to media element
  116. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  117. // Fired when MediaSource has been successfully attached to media element
  118. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  119. // Fired before detaching MediaSource from media element
  120. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  121. // Fired when MediaSource has been detached from media element
  122. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  123. // Fired when HTMLMediaElement dispatches "ended" event, or stalls at end of VOD program
  124. Events["MEDIA_ENDED"] = "hlsMediaEnded";
  125. // Fired after playback stall is resolved with playing, seeked, or ended event following BUFFER_STALLED_ERROR
  126. Events["STALL_RESOLVED"] = "hlsStallResolved";
  127. // Fired when the buffer is going to be reset
  128. Events["BUFFER_RESET"] = "hlsBufferReset";
  129. // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  130. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  131. // fired when sourcebuffers have been created - data: { tracks : tracks }
  132. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  133. // fired when we append a segment to the buffer - data: { segment: segment object }
  134. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  135. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  136. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  137. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  138. Events["BUFFER_EOS"] = "hlsBufferEos";
  139. // fired when all buffers are full to the end of the program, after calling MediaSource.endOfStream() (unless restricted)
  140. Events["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  141. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  142. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  143. // fired when the media buffer has been flushed - data: { }
  144. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  145. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  146. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  147. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }
  148. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  149. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  150. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  151. // fired when a level switch is requested - data: { level : id of new level }
  152. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  153. // fired when a level switch is effective - data: { level : id of new level }
  154. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  155. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  156. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  157. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }
  158. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  159. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  160. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  161. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  162. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  163. // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
  164. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  165. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  166. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  167. // fired when an audio track switching is requested - data: { id : audio track id }
  168. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  169. // fired when an audio track switch actually occurs - data: { id : audio track id }
  170. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  171. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  172. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  173. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }
  174. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  175. // fired when an audio tracks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  176. Events["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  177. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  178. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  179. // fired to notify that subtitle tracks were cleared as a result of stopping the media
  180. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  181. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  182. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  183. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  184. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  185. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }
  186. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  187. // fired when a subtitle racks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  188. Events["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  189. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  190. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  191. // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
  192. Events["CUES_PARSED"] = "hlsCuesParsed";
  193. // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
  194. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  195. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }
  196. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  197. // fired when a fragment loading starts - data: { frag : fragment object }
  198. Events["FRAG_LOADING"] = "hlsFragLoading";
  199. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  200. // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',
  201. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  202. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  203. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }
  204. Events["FRAG_LOADED"] = "hlsFragLoaded";
  205. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  206. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  207. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  208. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  209. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  210. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  211. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  212. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  213. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  214. // FRAG_PARSING_DATA = 'hlsFragParsingData',
  215. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  216. Events["FRAG_PARSED"] = "hlsFragParsed";
  217. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }
  218. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  219. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  220. Events["FRAG_CHANGED"] = "hlsFragChanged";
  221. // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }
  222. Events["FPS_DROP"] = "hlsFpsDrop";
  223. // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }
  224. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  225. // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }
  226. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  227. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  228. Events["ERROR"] = "hlsError";
  229. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  230. Events["DESTROYING"] = "hlsDestroying";
  231. // fired when a decrypt key loading starts - data: { frag : fragment object }
  232. Events["KEY_LOADING"] = "hlsKeyLoading";
  233. // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }
  234. Events["KEY_LOADED"] = "hlsKeyLoaded";
  235. // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }
  236. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  237. // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }
  238. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  239. // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }
  240. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  241. // fired when asset list has begun loading
  242. Events["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  243. // fired when a valid asset list is loaded
  244. Events["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  245. // fired when the list of Interstitial Events and Interstitial Schedule is updated
  246. Events["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  247. // fired when the buffer reaches an Interstitial Schedule boundary (both Primary segments and Interstitial Assets)
  248. Events["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  249. // fired when a player instance for an Interstitial Asset has been created
  250. Events["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  251. // Interstitial playback started
  252. Events["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  253. // InterstitialAsset playback started
  254. Events["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  255. // InterstitialAsset playback ended
  256. Events["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  257. // InterstitialAsset playback errored
  258. Events["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  259. // Interstitial playback ended
  260. Events["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  261. // Interstitial schedule resumed primary playback
  262. Events["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  263. // Interstitial players dispatch this event when playout limit is reached
  264. Events["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  265. // Event DateRange cue "enter" event dispatched
  266. Events["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  267. return Events;
  268. }({});
  269. /**
  270. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  271. */
  272. var PlaylistContextType = {
  273. MANIFEST: "manifest",
  274. LEVEL: "level",
  275. AUDIO_TRACK: "audioTrack",
  276. SUBTITLE_TRACK: "subtitleTrack"
  277. };
  278. var PlaylistLevelType = {
  279. MAIN: "main",
  280. AUDIO: "audio",
  281. SUBTITLE: "subtitle"
  282. };
  283. /*
  284. * compute an Exponential Weighted moving average
  285. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  286. * - heavily inspired from shaka-player
  287. */
  288. class EWMA {
  289. // About half of the estimated value will be from the last |halfLife| samples by weight.
  290. constructor(halfLife, estimate = 0, weight = 0) {
  291. this.halfLife = void 0;
  292. this.alpha_ = void 0;
  293. this.estimate_ = void 0;
  294. this.totalWeight_ = void 0;
  295. this.halfLife = halfLife;
  296. // Larger values of alpha expire historical data more slowly.
  297. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  298. this.estimate_ = estimate;
  299. this.totalWeight_ = weight;
  300. }
  301. sample(weight, value) {
  302. const adjAlpha = Math.pow(this.alpha_, weight);
  303. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  304. this.totalWeight_ += weight;
  305. }
  306. getTotalWeight() {
  307. return this.totalWeight_;
  308. }
  309. getEstimate() {
  310. if (this.alpha_) {
  311. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  312. if (zeroFactor) {
  313. return this.estimate_ / zeroFactor;
  314. }
  315. }
  316. return this.estimate_;
  317. }
  318. }
  319. /*
  320. * EWMA Bandwidth Estimator
  321. * - heavily inspired from shaka-player
  322. * Tracks bandwidth samples and estimates available bandwidth.
  323. * Based on the minimum of two exponentially-weighted moving averages with
  324. * different half-lives.
  325. */
  326. class EwmaBandWidthEstimator {
  327. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  328. this.defaultEstimate_ = void 0;
  329. this.minWeight_ = void 0;
  330. this.minDelayMs_ = void 0;
  331. this.slow_ = void 0;
  332. this.fast_ = void 0;
  333. this.defaultTTFB_ = void 0;
  334. this.ttfb_ = void 0;
  335. this.defaultEstimate_ = defaultEstimate;
  336. this.minWeight_ = 0.001;
  337. this.minDelayMs_ = 50;
  338. this.slow_ = new EWMA(slow);
  339. this.fast_ = new EWMA(fast);
  340. this.defaultTTFB_ = defaultTTFB;
  341. this.ttfb_ = new EWMA(slow);
  342. }
  343. update(slow, fast) {
  344. const {
  345. slow_,
  346. fast_,
  347. ttfb_
  348. } = this;
  349. if (slow_.halfLife !== slow) {
  350. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  351. }
  352. if (fast_.halfLife !== fast) {
  353. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  354. }
  355. if (ttfb_.halfLife !== slow) {
  356. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  357. }
  358. }
  359. sample(durationMs, numBytes) {
  360. durationMs = Math.max(durationMs, this.minDelayMs_);
  361. const numBits = 8 * numBytes;
  362. // weight is duration in seconds
  363. const durationS = durationMs / 1000;
  364. // value is bandwidth in bits/s
  365. const bandwidthInBps = numBits / durationS;
  366. this.fast_.sample(durationS, bandwidthInBps);
  367. this.slow_.sample(durationS, bandwidthInBps);
  368. }
  369. sampleTTFB(ttfb) {
  370. // weight is frequency curve applied to TTFB in seconds
  371. // (longer times have less weight with expected input under 1 second)
  372. const seconds = ttfb / 1000;
  373. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  374. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  375. }
  376. canEstimate() {
  377. return this.fast_.getTotalWeight() >= this.minWeight_;
  378. }
  379. getEstimate() {
  380. if (this.canEstimate()) {
  381. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  382. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  383. // Take the minimum of these two estimates. This should have the effect of
  384. // adapting down quickly, but up more slowly.
  385. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  386. } else {
  387. return this.defaultEstimate_;
  388. }
  389. }
  390. getEstimateTTFB() {
  391. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  392. return this.ttfb_.getEstimate();
  393. } else {
  394. return this.defaultTTFB_;
  395. }
  396. }
  397. get defaultEstimate() {
  398. return this.defaultEstimate_;
  399. }
  400. destroy() {}
  401. }
  402. function _defineProperty(e, r, t) {
  403. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  404. value: t,
  405. enumerable: true,
  406. configurable: true,
  407. writable: true
  408. }) : e[r] = t, e;
  409. }
  410. function _extends() {
  411. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  412. for (var e = 1; e < arguments.length; e++) {
  413. var t = arguments[e];
  414. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  415. }
  416. return n;
  417. }, _extends.apply(null, arguments);
  418. }
  419. function ownKeys(e, r) {
  420. var t = Object.keys(e);
  421. if (Object.getOwnPropertySymbols) {
  422. var o = Object.getOwnPropertySymbols(e);
  423. r && (o = o.filter(function (r) {
  424. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  425. })), t.push.apply(t, o);
  426. }
  427. return t;
  428. }
  429. function _objectSpread2(e) {
  430. for (var r = 1; r < arguments.length; r++) {
  431. var t = null != arguments[r] ? arguments[r] : {};
  432. r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
  433. _defineProperty(e, r, t[r]);
  434. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  435. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  436. });
  437. }
  438. return e;
  439. }
  440. function _toPrimitive(t, r) {
  441. if ("object" != typeof t || !t) return t;
  442. var e = t[Symbol.toPrimitive];
  443. if (void 0 !== e) {
  444. var i = e.call(t, r);
  445. if ("object" != typeof i) return i;
  446. throw new TypeError("@@toPrimitive must return a primitive value.");
  447. }
  448. return ("string" === r ? String : Number)(t);
  449. }
  450. function _toPropertyKey(t) {
  451. var i = _toPrimitive(t, "string");
  452. return "symbol" == typeof i ? i : i + "";
  453. }
  454. class Logger {
  455. constructor(label, logger) {
  456. this.trace = void 0;
  457. this.debug = void 0;
  458. this.log = void 0;
  459. this.warn = void 0;
  460. this.info = void 0;
  461. this.error = void 0;
  462. const lb = `[${label}]:`;
  463. this.trace = noop;
  464. this.debug = logger.debug.bind(null, lb);
  465. this.log = logger.log.bind(null, lb);
  466. this.warn = logger.warn.bind(null, lb);
  467. this.info = logger.info.bind(null, lb);
  468. this.error = logger.error.bind(null, lb);
  469. }
  470. }
  471. const noop = function noop() {};
  472. const fakeLogger = {
  473. trace: noop,
  474. debug: noop,
  475. log: noop,
  476. warn: noop,
  477. info: noop,
  478. error: noop
  479. };
  480. function createLogger() {
  481. return _extends({}, fakeLogger);
  482. }
  483. // let lastCallTime;
  484. // function formatMsgWithTimeInfo(type, msg) {
  485. // const now = Date.now();
  486. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  487. // lastCallTime = now;
  488. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  489. // return msg;
  490. // }
  491. function consolePrintFn(type, id) {
  492. const func = self.console[type];
  493. return func ? func.bind(self.console, `${id ? '[' + id + '] ' : ''}[${type}] >`) : noop;
  494. }
  495. function getLoggerFn(key, debugConfig, id) {
  496. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  497. }
  498. const exportedLogger = createLogger();
  499. function enableLogs(debugConfig, context, id) {
  500. // check that console is available
  501. const newLogger = createLogger();
  502. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  503. const keys = [
  504. // Remove out from list here to hard-disable a log-level
  505. // 'trace',
  506. 'debug', 'log', 'info', 'warn', 'error'];
  507. keys.forEach(key => {
  508. newLogger[key] = getLoggerFn(key, debugConfig, id);
  509. });
  510. // Some browsers don't allow to use bind on console object anyway
  511. // fallback to default if needed
  512. try {
  513. newLogger.log(`Debug logs enabled for "${context}" in hls.js version ${"1.6.7"}`);
  514. } catch (e) {
  515. /* log fn threw an exception. All logger methods are no-ops. */
  516. return createLogger();
  517. }
  518. // global exported logger uses the same functions as new logger without `id`
  519. keys.forEach(key => {
  520. exportedLogger[key] = getLoggerFn(key, debugConfig);
  521. });
  522. } else {
  523. // Reset global exported logger
  524. _extends(exportedLogger, newLogger);
  525. }
  526. return newLogger;
  527. }
  528. const logger = exportedLogger;
  529. function getMediaSource(preferManagedMediaSource = true) {
  530. if (typeof self === 'undefined') return undefined;
  531. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  532. return mms || self.MediaSource || self.WebKitMediaSource;
  533. }
  534. function isManagedMediaSource(source) {
  535. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  536. }
  537. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  538. const trackNames = Object.keys(currentTracks);
  539. const requiredTrackNames = Object.keys(requiredTracks);
  540. const trackCount = trackNames.length;
  541. const requiredTrackCount = requiredTrackNames.length;
  542. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some(name => requiredTrackNames.indexOf(name) === -1);
  543. }
  544. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  545. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  546. /* utf.js - UTF-8 <=> UTF-16 convertion
  547. *
  548. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  549. * Version: 1.0
  550. * LastModified: Dec 25 1999
  551. * This library is free. You can redistribute it and/or modify it.
  552. */
  553. /**
  554. * Converts a UTF-8 array to a string.
  555. *
  556. * @param array - The UTF-8 array to convert
  557. *
  558. * @returns The string
  559. *
  560. * @group Utils
  561. *
  562. * @beta
  563. */
  564. function utf8ArrayToStr(array, exitOnNull = false) {
  565. if (typeof TextDecoder !== 'undefined') {
  566. const decoder = new TextDecoder('utf-8');
  567. const decoded = decoder.decode(array);
  568. if (exitOnNull) {
  569. // grab up to the first null
  570. const idx = decoded.indexOf('\0');
  571. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  572. }
  573. // remove any null characters
  574. return decoded.replace(/\0/g, '');
  575. }
  576. const len = array.length;
  577. let c;
  578. let char2;
  579. let char3;
  580. let out = '';
  581. let i = 0;
  582. while (i < len) {
  583. c = array[i++];
  584. if (c === 0x00 && exitOnNull) {
  585. return out;
  586. } else if (c === 0x00 || c === 0x03) {
  587. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  588. continue;
  589. }
  590. switch (c >> 4) {
  591. case 0:
  592. case 1:
  593. case 2:
  594. case 3:
  595. case 4:
  596. case 5:
  597. case 6:
  598. case 7:
  599. // 0xxxxxxx
  600. out += String.fromCharCode(c);
  601. break;
  602. case 12:
  603. case 13:
  604. // 110x xxxx 10xx xxxx
  605. char2 = array[i++];
  606. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  607. break;
  608. case 14:
  609. // 1110 xxxx 10xx xxxx 10xx xxxx
  610. char2 = array[i++];
  611. char3 = array[i++];
  612. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  613. break;
  614. }
  615. }
  616. return out;
  617. }
  618. /**
  619. * hex dump helper class
  620. */
  621. const Hex = {
  622. hexDump: function (array) {
  623. let str = '';
  624. for (let i = 0; i < array.length; i++) {
  625. let h = array[i].toString(16);
  626. if (h.length < 2) {
  627. h = '0' + h;
  628. }
  629. str += h;
  630. }
  631. return str;
  632. }
  633. };
  634. function hexToArrayBuffer(str) {
  635. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  636. }
  637. function getDefaultExportFromCjs (x) {
  638. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  639. }
  640. var urlToolkit = {exports: {}};
  641. var hasRequiredUrlToolkit;
  642. function requireUrlToolkit () {
  643. if (hasRequiredUrlToolkit) return urlToolkit.exports;
  644. hasRequiredUrlToolkit = 1;
  645. (function (module, exports) {
  646. // see https://tools.ietf.org/html/rfc1808
  647. (function (root) {
  648. var URL_REGEX =
  649. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  650. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  651. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  652. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  653. var URLToolkit = {
  654. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  655. // E.g
  656. // With opts.alwaysNormalize = false (default, spec compliant)
  657. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  658. // With opts.alwaysNormalize = true (not spec compliant)
  659. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  660. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  661. opts = opts || {};
  662. // remove any remaining space and CRLF
  663. baseURL = baseURL.trim();
  664. relativeURL = relativeURL.trim();
  665. if (!relativeURL) {
  666. // 2a) If the embedded URL is entirely empty, it inherits the
  667. // entire base URL (i.e., is set equal to the base URL)
  668. // and we are done.
  669. if (!opts.alwaysNormalize) {
  670. return baseURL;
  671. }
  672. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  673. if (!basePartsForNormalise) {
  674. throw new Error('Error trying to parse base URL.');
  675. }
  676. basePartsForNormalise.path = URLToolkit.normalizePath(
  677. basePartsForNormalise.path
  678. );
  679. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  680. }
  681. var relativeParts = URLToolkit.parseURL(relativeURL);
  682. if (!relativeParts) {
  683. throw new Error('Error trying to parse relative URL.');
  684. }
  685. if (relativeParts.scheme) {
  686. // 2b) If the embedded URL starts with a scheme name, it is
  687. // interpreted as an absolute URL and we are done.
  688. if (!opts.alwaysNormalize) {
  689. return relativeURL;
  690. }
  691. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  692. return URLToolkit.buildURLFromParts(relativeParts);
  693. }
  694. var baseParts = URLToolkit.parseURL(baseURL);
  695. if (!baseParts) {
  696. throw new Error('Error trying to parse base URL.');
  697. }
  698. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  699. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  700. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  701. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  702. baseParts.netLoc = pathParts[1];
  703. baseParts.path = pathParts[2];
  704. }
  705. if (baseParts.netLoc && !baseParts.path) {
  706. baseParts.path = '/';
  707. }
  708. var builtParts = {
  709. // 2c) Otherwise, the embedded URL inherits the scheme of
  710. // the base URL.
  711. scheme: baseParts.scheme,
  712. netLoc: relativeParts.netLoc,
  713. path: null,
  714. params: relativeParts.params,
  715. query: relativeParts.query,
  716. fragment: relativeParts.fragment,
  717. };
  718. if (!relativeParts.netLoc) {
  719. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  720. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  721. // (if any) of the base URL.
  722. builtParts.netLoc = baseParts.netLoc;
  723. // 4) If the embedded URL path is preceded by a slash "/", the
  724. // path is not relative and we skip to Step 7.
  725. if (relativeParts.path[0] !== '/') {
  726. if (!relativeParts.path) {
  727. // 5) If the embedded URL path is empty (and not preceded by a
  728. // slash), then the embedded URL inherits the base URL path
  729. builtParts.path = baseParts.path;
  730. // 5a) if the embedded URL's <params> is non-empty, we skip to
  731. // step 7; otherwise, it inherits the <params> of the base
  732. // URL (if any) and
  733. if (!relativeParts.params) {
  734. builtParts.params = baseParts.params;
  735. // 5b) if the embedded URL's <query> is non-empty, we skip to
  736. // step 7; otherwise, it inherits the <query> of the base
  737. // URL (if any) and we skip to step 7.
  738. if (!relativeParts.query) {
  739. builtParts.query = baseParts.query;
  740. }
  741. }
  742. } else {
  743. // 6) The last segment of the base URL's path (anything
  744. // following the rightmost slash "/", or the entire path if no
  745. // slash is present) is removed and the embedded URL's path is
  746. // appended in its place.
  747. var baseURLPath = baseParts.path;
  748. var newPath =
  749. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  750. relativeParts.path;
  751. builtParts.path = URLToolkit.normalizePath(newPath);
  752. }
  753. }
  754. }
  755. if (builtParts.path === null) {
  756. builtParts.path = opts.alwaysNormalize
  757. ? URLToolkit.normalizePath(relativeParts.path)
  758. : relativeParts.path;
  759. }
  760. return URLToolkit.buildURLFromParts(builtParts);
  761. },
  762. parseURL: function (url) {
  763. var parts = URL_REGEX.exec(url);
  764. if (!parts) {
  765. return null;
  766. }
  767. return {
  768. scheme: parts[1] || '',
  769. netLoc: parts[2] || '',
  770. path: parts[3] || '',
  771. params: parts[4] || '',
  772. query: parts[5] || '',
  773. fragment: parts[6] || '',
  774. };
  775. },
  776. normalizePath: function (path) {
  777. // The following operations are
  778. // then applied, in order, to the new path:
  779. // 6a) All occurrences of "./", where "." is a complete path
  780. // segment, are removed.
  781. // 6b) If the path ends with "." as a complete path segment,
  782. // that "." is removed.
  783. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  784. // 6c) All occurrences of "<segment>/../", where <segment> is a
  785. // complete path segment not equal to "..", are removed.
  786. // Removal of these path segments is performed iteratively,
  787. // removing the leftmost matching pattern on each iteration,
  788. // until no matching pattern remains.
  789. // 6d) If the path ends with "<segment>/..", where <segment> is a
  790. // complete path segment not equal to "..", that
  791. // "<segment>/.." is removed.
  792. while (
  793. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  794. ) {}
  795. return path.split('').reverse().join('');
  796. },
  797. buildURLFromParts: function (parts) {
  798. return (
  799. parts.scheme +
  800. parts.netLoc +
  801. parts.path +
  802. parts.params +
  803. parts.query +
  804. parts.fragment
  805. );
  806. },
  807. };
  808. module.exports = URLToolkit;
  809. })();
  810. } (urlToolkit));
  811. return urlToolkit.exports;
  812. }
  813. var urlToolkitExports = requireUrlToolkit();
  814. class LoadStats {
  815. constructor() {
  816. this.aborted = false;
  817. this.loaded = 0;
  818. this.retry = 0;
  819. this.total = 0;
  820. this.chunkCount = 0;
  821. this.bwEstimate = 0;
  822. this.loading = {
  823. start: 0,
  824. first: 0,
  825. end: 0
  826. };
  827. this.parsing = {
  828. start: 0,
  829. end: 0
  830. };
  831. this.buffering = {
  832. start: 0,
  833. first: 0,
  834. end: 0
  835. };
  836. }
  837. }
  838. var ElementaryStreamTypes = {
  839. AUDIO: "audio",
  840. VIDEO: "video",
  841. AUDIOVIDEO: "audiovideo"
  842. };
  843. class BaseSegment {
  844. constructor(base) {
  845. this._byteRange = null;
  846. this._url = null;
  847. this._stats = null;
  848. this._streams = null;
  849. // baseurl is the URL to the playlist
  850. this.base = void 0;
  851. // relurl is the portion of the URL that comes from inside the playlist.
  852. this.relurl = void 0;
  853. if (typeof base === 'string') {
  854. base = {
  855. url: base
  856. };
  857. }
  858. this.base = base;
  859. makeEnumerable(this, 'stats');
  860. }
  861. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  862. setByteRange(value, previous) {
  863. const params = value.split('@', 2);
  864. let start;
  865. if (params.length === 1) {
  866. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  867. } else {
  868. start = parseInt(params[1]);
  869. }
  870. this._byteRange = [start, parseInt(params[0]) + start];
  871. }
  872. get baseurl() {
  873. return this.base.url;
  874. }
  875. get byteRange() {
  876. if (this._byteRange === null) {
  877. return [];
  878. }
  879. return this._byteRange;
  880. }
  881. get byteRangeStartOffset() {
  882. return this.byteRange[0];
  883. }
  884. get byteRangeEndOffset() {
  885. return this.byteRange[1];
  886. }
  887. get elementaryStreams() {
  888. if (this._streams === null) {
  889. this._streams = {
  890. [ElementaryStreamTypes.AUDIO]: null,
  891. [ElementaryStreamTypes.VIDEO]: null,
  892. [ElementaryStreamTypes.AUDIOVIDEO]: null
  893. };
  894. }
  895. return this._streams;
  896. }
  897. set elementaryStreams(value) {
  898. this._streams = value;
  899. }
  900. get hasStats() {
  901. return this._stats !== null;
  902. }
  903. get hasStreams() {
  904. return this._streams !== null;
  905. }
  906. get stats() {
  907. if (this._stats === null) {
  908. this._stats = new LoadStats();
  909. }
  910. return this._stats;
  911. }
  912. set stats(value) {
  913. this._stats = value;
  914. }
  915. get url() {
  916. if (!this._url && this.baseurl && this.relurl) {
  917. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  918. alwaysNormalize: true
  919. });
  920. }
  921. return this._url || '';
  922. }
  923. set url(value) {
  924. this._url = value;
  925. }
  926. clearElementaryStreamInfo() {
  927. const {
  928. elementaryStreams
  929. } = this;
  930. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  931. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  932. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  933. }
  934. }
  935. function isMediaFragment(frag) {
  936. return frag.sn !== 'initSegment';
  937. }
  938. /**
  939. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  940. */
  941. class Fragment extends BaseSegment {
  942. constructor(type, base) {
  943. super(base);
  944. this._decryptdata = null;
  945. this._programDateTime = null;
  946. this._ref = null;
  947. // Approximate bit rate of the fragment expressed in bits per second (bps) as indicated by the last EXT-X-BITRATE (kbps) tag
  948. this._bitrate = void 0;
  949. this.rawProgramDateTime = null;
  950. this.tagList = [];
  951. // EXTINF has to be present for a m3u8 to be considered valid
  952. this.duration = 0;
  953. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  954. this.sn = 0;
  955. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  956. // core difference from the private field _decryptdata is the lack of the initialized IV
  957. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  958. this.levelkeys = void 0;
  959. // A string representing the fragment type
  960. this.type = void 0;
  961. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  962. this.loader = null;
  963. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  964. this.keyLoader = null;
  965. // The level/track index to which the fragment belongs
  966. this.level = -1;
  967. // The continuity counter of the fragment
  968. this.cc = 0;
  969. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  970. this.startPTS = void 0;
  971. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  972. this.endPTS = void 0;
  973. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  974. this.startDTS = void 0;
  975. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  976. this.endDTS = void 0;
  977. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  978. this.start = 0;
  979. // The offset time (seconds) of the fragment from the start of the Playlist
  980. this.playlistOffset = 0;
  981. // Set by `updateFragPTSDTS` in level-helper
  982. this.deltaPTS = void 0;
  983. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  984. this.maxStartPTS = void 0;
  985. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  986. this.minEndPTS = void 0;
  987. // Init Segment bytes (unset for media segments)
  988. this.data = void 0;
  989. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  990. this.bitrateTest = false;
  991. // #EXTINF segment title
  992. this.title = null;
  993. // The Media Initialization Section for this segment
  994. this.initSegment = null;
  995. // Fragment is the last fragment in the media playlist
  996. this.endList = void 0;
  997. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  998. this.gap = void 0;
  999. // Deprecated
  1000. this.urlId = 0;
  1001. this.type = type;
  1002. }
  1003. get byteLength() {
  1004. if (this.hasStats) {
  1005. const total = this.stats.total;
  1006. if (total) {
  1007. return total;
  1008. }
  1009. }
  1010. if (this.byteRange) {
  1011. const start = this.byteRange[0];
  1012. const end = this.byteRange[1];
  1013. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  1014. return end - start;
  1015. }
  1016. }
  1017. return null;
  1018. }
  1019. get bitrate() {
  1020. if (this.byteLength) {
  1021. return this.byteLength * 8 / this.duration;
  1022. }
  1023. if (this._bitrate) {
  1024. return this._bitrate;
  1025. }
  1026. return null;
  1027. }
  1028. set bitrate(value) {
  1029. this._bitrate = value;
  1030. }
  1031. get decryptdata() {
  1032. const {
  1033. levelkeys
  1034. } = this;
  1035. if (!levelkeys && !this._decryptdata) {
  1036. return null;
  1037. }
  1038. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  1039. const key = this.levelkeys.identity;
  1040. if (key) {
  1041. this._decryptdata = key.getDecryptData(this.sn);
  1042. } else {
  1043. const keyFormats = Object.keys(this.levelkeys);
  1044. if (keyFormats.length === 1) {
  1045. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  1046. }
  1047. }
  1048. }
  1049. return this._decryptdata;
  1050. }
  1051. get end() {
  1052. return this.start + this.duration;
  1053. }
  1054. get endProgramDateTime() {
  1055. if (this.programDateTime === null) {
  1056. return null;
  1057. }
  1058. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  1059. return this.programDateTime + duration * 1000;
  1060. }
  1061. get encrypted() {
  1062. var _this$_decryptdata;
  1063. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  1064. // when we want the fragment to start reporting that it is encrypted.
  1065. // Currently, keyFormat will only be set for identity keys
  1066. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  1067. return true;
  1068. } else if (this.levelkeys) {
  1069. const keyFormats = Object.keys(this.levelkeys);
  1070. const len = keyFormats.length;
  1071. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  1072. return true;
  1073. }
  1074. }
  1075. return false;
  1076. }
  1077. get programDateTime() {
  1078. if (this._programDateTime === null && this.rawProgramDateTime) {
  1079. this.programDateTime = Date.parse(this.rawProgramDateTime);
  1080. }
  1081. return this._programDateTime;
  1082. }
  1083. set programDateTime(value) {
  1084. if (!isFiniteNumber(value)) {
  1085. this._programDateTime = this.rawProgramDateTime = null;
  1086. return;
  1087. }
  1088. this._programDateTime = value;
  1089. }
  1090. get ref() {
  1091. if (!isMediaFragment(this)) {
  1092. return null;
  1093. }
  1094. if (!this._ref) {
  1095. this._ref = {
  1096. base: this.base,
  1097. start: this.start,
  1098. duration: this.duration,
  1099. sn: this.sn,
  1100. programDateTime: this.programDateTime
  1101. };
  1102. }
  1103. return this._ref;
  1104. }
  1105. addStart(value) {
  1106. this.setStart(this.start + value);
  1107. }
  1108. setStart(value) {
  1109. this.start = value;
  1110. if (this._ref) {
  1111. this._ref.start = value;
  1112. }
  1113. }
  1114. setDuration(value) {
  1115. this.duration = value;
  1116. if (this._ref) {
  1117. this._ref.duration = value;
  1118. }
  1119. }
  1120. setKeyFormat(keyFormat) {
  1121. if (this.levelkeys) {
  1122. const key = this.levelkeys[keyFormat];
  1123. if (key && !this._decryptdata) {
  1124. this._decryptdata = key.getDecryptData(this.sn);
  1125. }
  1126. }
  1127. }
  1128. abortRequests() {
  1129. var _this$loader, _this$keyLoader;
  1130. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  1131. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  1132. }
  1133. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  1134. const {
  1135. elementaryStreams
  1136. } = this;
  1137. const info = elementaryStreams[type];
  1138. if (!info) {
  1139. elementaryStreams[type] = {
  1140. startPTS,
  1141. endPTS,
  1142. startDTS,
  1143. endDTS,
  1144. partial
  1145. };
  1146. return;
  1147. }
  1148. info.startPTS = Math.min(info.startPTS, startPTS);
  1149. info.endPTS = Math.max(info.endPTS, endPTS);
  1150. info.startDTS = Math.min(info.startDTS, startDTS);
  1151. info.endDTS = Math.max(info.endDTS, endDTS);
  1152. }
  1153. }
  1154. /**
  1155. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  1156. */
  1157. class Part extends BaseSegment {
  1158. constructor(partAttrs, frag, base, index, previous) {
  1159. super(base);
  1160. this.fragOffset = 0;
  1161. this.duration = 0;
  1162. this.gap = false;
  1163. this.independent = false;
  1164. this.relurl = void 0;
  1165. this.fragment = void 0;
  1166. this.index = void 0;
  1167. this.duration = partAttrs.decimalFloatingPoint('DURATION');
  1168. this.gap = partAttrs.bool('GAP');
  1169. this.independent = partAttrs.bool('INDEPENDENT');
  1170. this.relurl = partAttrs.enumeratedString('URI');
  1171. this.fragment = frag;
  1172. this.index = index;
  1173. const byteRange = partAttrs.enumeratedString('BYTERANGE');
  1174. if (byteRange) {
  1175. this.setByteRange(byteRange, previous);
  1176. }
  1177. if (previous) {
  1178. this.fragOffset = previous.fragOffset + previous.duration;
  1179. }
  1180. }
  1181. get start() {
  1182. return this.fragment.start + this.fragOffset;
  1183. }
  1184. get end() {
  1185. return this.start + this.duration;
  1186. }
  1187. get loaded() {
  1188. const {
  1189. elementaryStreams
  1190. } = this;
  1191. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  1192. }
  1193. }
  1194. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  1195. const prototype = Object.getPrototypeOf(object);
  1196. if (prototype) {
  1197. const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  1198. if (propertyDescriptor) {
  1199. return propertyDescriptor;
  1200. }
  1201. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  1202. }
  1203. }
  1204. function makeEnumerable(object, property) {
  1205. const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  1206. if (d) {
  1207. d.enumerable = true;
  1208. Object.defineProperty(object, property, d);
  1209. }
  1210. }
  1211. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1212. const push = [].push;
  1213. // We are using fixed track IDs for driving the MP4 remuxer
  1214. // instead of following the TS PIDs.
  1215. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1216. // may not like if there are TrackID "switches"
  1217. // See https://github.com/video-dev/hls.js/issues/1331
  1218. // Here we are mapping our internal track types to constant MP4 track IDs
  1219. // With MSE currently one can only have one track of each, and we are muxing
  1220. // whatever video/audio rendition in them.
  1221. const RemuxerTrackIdConfig = {
  1222. video: 1,
  1223. audio: 2,
  1224. id3: 3,
  1225. text: 4
  1226. };
  1227. function bin2str(data) {
  1228. return String.fromCharCode.apply(null, data);
  1229. }
  1230. function readUint16(buffer, offset) {
  1231. const val = buffer[offset] << 8 | buffer[offset + 1];
  1232. return val < 0 ? 65536 + val : val;
  1233. }
  1234. function readUint32(buffer, offset) {
  1235. const val = readSint32(buffer, offset);
  1236. return val < 0 ? 4294967296 + val : val;
  1237. }
  1238. function readUint64(buffer, offset) {
  1239. let result = readUint32(buffer, offset);
  1240. result *= Math.pow(2, 32);
  1241. result += readUint32(buffer, offset + 4);
  1242. return result;
  1243. }
  1244. function readSint32(buffer, offset) {
  1245. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1246. }
  1247. // Find "moof" box
  1248. function hasMoofData(data) {
  1249. const end = data.byteLength;
  1250. for (let i = 0; i < end;) {
  1251. const size = readUint32(data, i);
  1252. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1253. return true;
  1254. }
  1255. i = size > 1 ? i + size : end;
  1256. }
  1257. return false;
  1258. }
  1259. // Find the data for a box specified by its path
  1260. function findBox(data, path) {
  1261. const results = [];
  1262. if (!path.length) {
  1263. // short-circuit the search for empty paths
  1264. return results;
  1265. }
  1266. const end = data.byteLength;
  1267. for (let i = 0; i < end;) {
  1268. const size = readUint32(data, i);
  1269. const type = bin2str(data.subarray(i + 4, i + 8));
  1270. const endbox = size > 1 ? i + size : end;
  1271. if (type === path[0]) {
  1272. if (path.length === 1) {
  1273. // this is the end of the path and we've found the box we were
  1274. // looking for
  1275. results.push(data.subarray(i + 8, endbox));
  1276. } else {
  1277. // recursively search for the next box along the path
  1278. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1279. if (subresults.length) {
  1280. push.apply(results, subresults);
  1281. }
  1282. }
  1283. }
  1284. i = endbox;
  1285. }
  1286. // we've finished searching all of data
  1287. return results;
  1288. }
  1289. function parseSegmentIndex(sidx) {
  1290. const references = [];
  1291. const version = sidx[0];
  1292. // set initial offset, we skip the reference ID (not needed)
  1293. let index = 8;
  1294. const timescale = readUint32(sidx, index);
  1295. index += 4;
  1296. let earliestPresentationTime = 0;
  1297. let firstOffset = 0;
  1298. if (version === 0) {
  1299. earliestPresentationTime = readUint32(sidx, index);
  1300. firstOffset = readUint32(sidx, index + 4);
  1301. index += 8;
  1302. } else {
  1303. earliestPresentationTime = readUint64(sidx, index);
  1304. firstOffset = readUint64(sidx, index + 8);
  1305. index += 16;
  1306. }
  1307. // skip reserved
  1308. index += 2;
  1309. let startByte = sidx.length + firstOffset;
  1310. const referencesCount = readUint16(sidx, index);
  1311. index += 2;
  1312. for (let i = 0; i < referencesCount; i++) {
  1313. let referenceIndex = index;
  1314. const referenceInfo = readUint32(sidx, referenceIndex);
  1315. referenceIndex += 4;
  1316. const referenceSize = referenceInfo & 0x7fffffff;
  1317. const referenceType = (referenceInfo & 0x80000000) >>> 31;
  1318. if (referenceType === 1) {
  1319. logger.warn('SIDX has hierarchical references (not supported)');
  1320. return null;
  1321. }
  1322. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1323. referenceIndex += 4;
  1324. references.push({
  1325. referenceSize,
  1326. subsegmentDuration,
  1327. // unscaled
  1328. info: {
  1329. duration: subsegmentDuration / timescale,
  1330. start: startByte,
  1331. end: startByte + referenceSize - 1
  1332. }
  1333. });
  1334. startByte += referenceSize;
  1335. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1336. // for |sapDelta|.
  1337. referenceIndex += 4;
  1338. // skip to next ref
  1339. index = referenceIndex;
  1340. }
  1341. return {
  1342. earliestPresentationTime,
  1343. timescale,
  1344. version,
  1345. referencesCount,
  1346. references
  1347. };
  1348. }
  1349. /**
  1350. * Parses an MP4 initialization segment and extracts stream type and
  1351. * timescale values for any declared tracks. Timescale values indicate the
  1352. * number of clock ticks per second to assume for time-based values
  1353. * elsewhere in the MP4.
  1354. *
  1355. * To determine the start time of an MP4, you need two pieces of
  1356. * information: the timescale unit and the earliest base media decode
  1357. * time. Multiple timescales can be specified within an MP4 but the
  1358. * base media decode time is always expressed in the timescale from
  1359. * the media header box for the track:
  1360. * ```
  1361. * moov > trak > mdia > mdhd.timescale
  1362. * moov > trak > mdia > hdlr
  1363. * ```
  1364. * @param initSegment the bytes of the init segment
  1365. * @returns a hash of track type to timescale values or null if
  1366. * the init segment is malformed.
  1367. */
  1368. function parseInitSegment(initSegment) {
  1369. const result = [];
  1370. const traks = findBox(initSegment, ['moov', 'trak']);
  1371. for (let i = 0; i < traks.length; i++) {
  1372. const trak = traks[i];
  1373. const tkhd = findBox(trak, ['tkhd'])[0];
  1374. if (tkhd) {
  1375. let version = tkhd[0];
  1376. const trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1377. const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1378. if (mdhd) {
  1379. version = mdhd[0];
  1380. const timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1381. const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1382. if (hdlr) {
  1383. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1384. const type = {
  1385. soun: ElementaryStreamTypes.AUDIO,
  1386. vide: ElementaryStreamTypes.VIDEO
  1387. }[hdlrType];
  1388. // Parse codec details
  1389. const stsdBox = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1390. const stsd = parseStsd(stsdBox);
  1391. if (type) {
  1392. // Add 'audio', 'video', and 'audiovideo' track records that will map to SourceBuffers
  1393. result[trackId] = {
  1394. timescale,
  1395. type,
  1396. stsd
  1397. };
  1398. result[type] = _objectSpread2({
  1399. timescale,
  1400. id: trackId
  1401. }, stsd);
  1402. } else {
  1403. // Add 'meta' and other track records
  1404. result[trackId] = {
  1405. timescale,
  1406. type: hdlrType,
  1407. stsd
  1408. };
  1409. }
  1410. }
  1411. }
  1412. }
  1413. }
  1414. const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1415. trex.forEach(trex => {
  1416. const trackId = readUint32(trex, 4);
  1417. const track = result[trackId];
  1418. if (track) {
  1419. track.default = {
  1420. duration: readUint32(trex, 12),
  1421. flags: readUint32(trex, 20)
  1422. };
  1423. }
  1424. });
  1425. return result;
  1426. }
  1427. function parseStsd(stsd) {
  1428. const sampleEntries = stsd.subarray(8);
  1429. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1430. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1431. let codec = fourCC;
  1432. let supplemental;
  1433. const encrypted = fourCC === 'enca' || fourCC === 'encv';
  1434. if (encrypted) {
  1435. const encBox = findBox(sampleEntries, [fourCC])[0];
  1436. const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1437. const sinfs = findBox(encBoxChildren, ['sinf']);
  1438. sinfs.forEach(sinf => {
  1439. const schm = findBox(sinf, ['schm'])[0];
  1440. if (schm) {
  1441. const scheme = bin2str(schm.subarray(4, 8));
  1442. if (scheme === 'cbcs' || scheme === 'cenc') {
  1443. const frma = findBox(sinf, ['frma'])[0];
  1444. if (frma) {
  1445. // for encrypted content codec fourCC will be in frma
  1446. codec = bin2str(frma);
  1447. }
  1448. }
  1449. }
  1450. });
  1451. }
  1452. const codecFourCC = codec;
  1453. switch (codec) {
  1454. case 'avc1':
  1455. case 'avc2':
  1456. case 'avc3':
  1457. case 'avc4':
  1458. {
  1459. // extract profile + compatibility + level out of avcC box
  1460. const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1461. if (avcCBox && avcCBox.length > 3) {
  1462. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1463. supplemental = parseSupplementalDoViCodec(codecFourCC === 'avc1' ? 'dva1' : 'dvav', sampleEntriesEnd);
  1464. }
  1465. break;
  1466. }
  1467. case 'mp4a':
  1468. {
  1469. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1470. const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1471. if (esdsBox && esdsBox.length > 7) {
  1472. let i = 4;
  1473. // ES Descriptor tag
  1474. if (esdsBox[i++] !== 0x03) {
  1475. break;
  1476. }
  1477. i = skipBERInteger(esdsBox, i);
  1478. i += 2; // skip es_id;
  1479. const flags = esdsBox[i++];
  1480. if (flags & 0x80) {
  1481. i += 2; // skip dependency es_id
  1482. }
  1483. if (flags & 0x40) {
  1484. i += esdsBox[i++]; // skip URL
  1485. }
  1486. // Decoder config descriptor
  1487. if (esdsBox[i++] !== 0x04) {
  1488. break;
  1489. }
  1490. i = skipBERInteger(esdsBox, i);
  1491. const objectType = esdsBox[i++];
  1492. if (objectType === 0x40) {
  1493. codec += '.' + toHex(objectType);
  1494. } else {
  1495. break;
  1496. }
  1497. i += 12;
  1498. // Decoder specific info
  1499. if (esdsBox[i++] !== 0x05) {
  1500. break;
  1501. }
  1502. i = skipBERInteger(esdsBox, i);
  1503. const firstByte = esdsBox[i++];
  1504. let audioObjectType = (firstByte & 0xf8) >> 3;
  1505. if (audioObjectType === 31) {
  1506. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1507. }
  1508. codec += '.' + audioObjectType;
  1509. }
  1510. break;
  1511. }
  1512. case 'hvc1':
  1513. case 'hev1':
  1514. {
  1515. const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1516. if (hvcCBox && hvcCBox.length > 12) {
  1517. const profileByte = hvcCBox[1];
  1518. const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1519. const generalProfileIdc = profileByte & 0x1f;
  1520. const profileCompat = readUint32(hvcCBox, 2);
  1521. const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1522. const levelIDC = hvcCBox[12];
  1523. const constraintIndicator = hvcCBox.subarray(6, 12);
  1524. codec += '.' + profileSpace + generalProfileIdc;
  1525. codec += '.' + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1526. codec += '.' + tierFlag + levelIDC;
  1527. let constraintString = '';
  1528. for (let i = constraintIndicator.length; i--;) {
  1529. const byte = constraintIndicator[i];
  1530. if (byte || constraintString) {
  1531. const encodedByte = byte.toString(16).toUpperCase();
  1532. constraintString = '.' + encodedByte + constraintString;
  1533. }
  1534. }
  1535. codec += constraintString;
  1536. }
  1537. supplemental = parseSupplementalDoViCodec(codecFourCC == 'hev1' ? 'dvhe' : 'dvh1', sampleEntriesEnd);
  1538. break;
  1539. }
  1540. case 'dvh1':
  1541. case 'dvhe':
  1542. case 'dvav':
  1543. case 'dva1':
  1544. case 'dav1':
  1545. {
  1546. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  1547. break;
  1548. }
  1549. case 'vp09':
  1550. {
  1551. const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1552. if (vpcCBox && vpcCBox.length > 6) {
  1553. const profile = vpcCBox[4];
  1554. const level = vpcCBox[5];
  1555. const bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1556. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  1557. }
  1558. break;
  1559. }
  1560. case 'av01':
  1561. {
  1562. const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1563. if (av1CBox && av1CBox.length > 2) {
  1564. const profile = av1CBox[1] >>> 5;
  1565. const level = av1CBox[1] & 0x1f;
  1566. const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1567. const highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1568. const twelveBit = (av1CBox[2] & 0x20) >> 5;
  1569. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1570. const monochrome = (av1CBox[2] & 0x10) >> 4;
  1571. const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1572. const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1573. const chromaSamplePosition = av1CBox[2] & 0x03;
  1574. // TODO: parse color_description_present_flag
  1575. // default it to BT.709/limited range for now
  1576. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1577. const colorPrimaries = 1;
  1578. const transferCharacteristics = 1;
  1579. const matrixCoefficients = 1;
  1580. const videoFullRangeFlag = 0;
  1581. codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1582. supplemental = parseSupplementalDoViCodec('dav1', sampleEntriesEnd);
  1583. }
  1584. break;
  1585. }
  1586. }
  1587. return {
  1588. codec,
  1589. encrypted,
  1590. supplemental
  1591. };
  1592. }
  1593. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  1594. const dvvCResult = findBox(sampleEntriesEnd, ['dvvC']); // used by DoVi Profile 8 to 10
  1595. const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ['dvcC'])[0]; // used by DoVi Profiles up to 7 and 20
  1596. if (dvXCBox) {
  1597. const doViProfile = dvXCBox[2] >> 1 & 0x7f;
  1598. const doViLevel = dvXCBox[2] << 5 & 0x20 | dvXCBox[3] >> 3 & 0x1f;
  1599. return fourCC + '.' + addLeadingZero(doViProfile) + '.' + addLeadingZero(doViLevel);
  1600. }
  1601. }
  1602. function reverse32BitInt(val) {
  1603. let result = 0;
  1604. for (let i = 0; i < 32; i++) {
  1605. result |= (val >> i & 1) << 32 - 1 - i;
  1606. }
  1607. return result >>> 0;
  1608. }
  1609. function skipBERInteger(bytes, i) {
  1610. const limit = i + 5;
  1611. while (bytes[i++] & 0x80 && i < limit) {
  1612. /* do nothing */
  1613. }
  1614. return i;
  1615. }
  1616. function toHex(x) {
  1617. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1618. }
  1619. function addLeadingZero(num) {
  1620. return (num < 10 ? '0' : '') + num;
  1621. }
  1622. function patchEncyptionData(initSegment, decryptdata) {
  1623. if (!initSegment || !decryptdata) {
  1624. return initSegment;
  1625. }
  1626. const keyId = decryptdata.keyId;
  1627. if (keyId && decryptdata.isCommonEncryption) {
  1628. const traks = findBox(initSegment, ['moov', 'trak']);
  1629. traks.forEach(trak => {
  1630. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1631. // skip the sample entry count
  1632. const sampleEntries = stsd.subarray(8);
  1633. let encBoxes = findBox(sampleEntries, ['enca']);
  1634. const isAudio = encBoxes.length > 0;
  1635. if (!isAudio) {
  1636. encBoxes = findBox(sampleEntries, ['encv']);
  1637. }
  1638. encBoxes.forEach(enc => {
  1639. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1640. const sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1641. sinfBoxes.forEach(sinf => {
  1642. const tenc = parseSinf(sinf);
  1643. if (tenc) {
  1644. // Look for default key id (keyID offset is always 8 within the tenc box):
  1645. const tencKeyId = tenc.subarray(8, 24);
  1646. if (!tencKeyId.some(b => b !== 0)) {
  1647. logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1648. tenc.set(keyId, 8);
  1649. }
  1650. }
  1651. });
  1652. });
  1653. });
  1654. }
  1655. return initSegment;
  1656. }
  1657. function parseSinf(sinf) {
  1658. const schm = findBox(sinf, ['schm'])[0];
  1659. if (schm) {
  1660. const scheme = bin2str(schm.subarray(4, 8));
  1661. if (scheme === 'cbcs' || scheme === 'cenc') {
  1662. return findBox(sinf, ['schi', 'tenc'])[0];
  1663. }
  1664. }
  1665. return null;
  1666. }
  1667. /*
  1668. For Reference:
  1669. aligned(8) class TrackFragmentHeaderBox
  1670. extends FullBox(‘tfhd’, 0, tf_flags){
  1671. unsigned int(32) track_ID;
  1672. // all the following are optional fields
  1673. unsigned int(64) base_data_offset;
  1674. unsigned int(32) sample_description_index;
  1675. unsigned int(32) default_sample_duration;
  1676. unsigned int(32) default_sample_size;
  1677. unsigned int(32) default_sample_flags
  1678. }
  1679. */
  1680. function getSampleData(data, initData, logger) {
  1681. const tracks = {};
  1682. const trafs = findBox(data, ['moof', 'traf']);
  1683. for (let i = 0; i < trafs.length; i++) {
  1684. const traf = trafs[i];
  1685. // There is only one tfhd & trun per traf
  1686. // This is true for CMAF style content, and we should perhaps check the ftyp
  1687. // and only look for a single trun then, but for ISOBMFF we should check
  1688. // for multiple track runs.
  1689. const tfhd = findBox(traf, ['tfhd'])[0];
  1690. // get the track id from the tfhd
  1691. const id = readUint32(tfhd, 4);
  1692. const track = initData[id];
  1693. if (!track) {
  1694. continue;
  1695. }
  1696. const trackTimes = tracks[id] || (tracks[id] = {
  1697. start: NaN,
  1698. duration: 0,
  1699. sampleCount: 0,
  1700. timescale: track.timescale,
  1701. type: track.type
  1702. });
  1703. // get start DTS
  1704. const tfdt = findBox(traf, ['tfdt'])[0];
  1705. if (tfdt) {
  1706. const version = tfdt[0];
  1707. let baseTime = readUint32(tfdt, 4);
  1708. if (version === 1) {
  1709. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1710. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1711. // https://github.com/video-dev/hls.js/issues/5303
  1712. if (baseTime === UINT32_MAX$1) {
  1713. logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1714. } else {
  1715. baseTime *= UINT32_MAX$1 + 1;
  1716. baseTime += readUint32(tfdt, 8);
  1717. }
  1718. }
  1719. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  1720. trackTimes.start = baseTime;
  1721. }
  1722. }
  1723. const trackDefault = track.default;
  1724. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1725. let defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  1726. if (tfhdFlags & 0x000008) {
  1727. // 0x000008 indicates the presence of the default_sample_duration field
  1728. if (tfhdFlags & 0x000002) {
  1729. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  1730. // If present, the default_sample_duration exists at byte offset 12
  1731. defaultSampleDuration = readUint32(tfhd, 12);
  1732. } else {
  1733. // Otherwise, the duration is at byte offset 8
  1734. defaultSampleDuration = readUint32(tfhd, 8);
  1735. }
  1736. }
  1737. const truns = findBox(traf, ['trun']);
  1738. let sampleDTS = trackTimes.start || 0;
  1739. let rawDuration = 0;
  1740. let sampleDuration = defaultSampleDuration;
  1741. for (let j = 0; j < truns.length; j++) {
  1742. const trun = truns[j];
  1743. const sampleCount = readUint32(trun, 4);
  1744. const sampleIndex = trackTimes.sampleCount;
  1745. trackTimes.sampleCount += sampleCount;
  1746. // Get duration from samples
  1747. const dataOffsetPresent = trun[3] & 0x01;
  1748. const firstSampleFlagsPresent = trun[3] & 0x04;
  1749. const sampleDurationPresent = trun[2] & 0x01;
  1750. const sampleSizePresent = trun[2] & 0x02;
  1751. const sampleFlagsPresent = trun[2] & 0x04;
  1752. const sampleCompositionTimeOffsetPresent = trun[2] & 0x08;
  1753. let offset = 8;
  1754. let remaining = sampleCount;
  1755. if (dataOffsetPresent) {
  1756. offset += 4;
  1757. }
  1758. if (firstSampleFlagsPresent && sampleCount) {
  1759. const isNonSyncSample = trun[offset + 1] & 0x01;
  1760. if (!isNonSyncSample && trackTimes.keyFrameIndex === undefined) {
  1761. trackTimes.keyFrameIndex = sampleIndex;
  1762. }
  1763. offset += 4;
  1764. if (sampleDurationPresent) {
  1765. sampleDuration = readUint32(trun, offset);
  1766. offset += 4;
  1767. } else {
  1768. sampleDuration = defaultSampleDuration;
  1769. }
  1770. if (sampleSizePresent) {
  1771. offset += 4;
  1772. }
  1773. if (sampleCompositionTimeOffsetPresent) {
  1774. offset += 4;
  1775. }
  1776. sampleDTS += sampleDuration;
  1777. rawDuration += sampleDuration;
  1778. remaining--;
  1779. }
  1780. while (remaining--) {
  1781. if (sampleDurationPresent) {
  1782. sampleDuration = readUint32(trun, offset);
  1783. offset += 4;
  1784. } else {
  1785. sampleDuration = defaultSampleDuration;
  1786. }
  1787. if (sampleSizePresent) {
  1788. offset += 4;
  1789. }
  1790. if (sampleFlagsPresent) {
  1791. const isNonSyncSample = trun[offset + 1] & 0x01;
  1792. if (!isNonSyncSample) {
  1793. if (trackTimes.keyFrameIndex === undefined) {
  1794. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  1795. trackTimes.keyFrameStart = sampleDTS;
  1796. }
  1797. }
  1798. offset += 4;
  1799. }
  1800. if (sampleCompositionTimeOffsetPresent) {
  1801. offset += 4;
  1802. }
  1803. sampleDTS += sampleDuration;
  1804. rawDuration += sampleDuration;
  1805. }
  1806. if (!rawDuration && defaultSampleDuration) {
  1807. rawDuration += defaultSampleDuration * sampleCount;
  1808. }
  1809. }
  1810. trackTimes.duration += rawDuration;
  1811. }
  1812. if (!Object.keys(tracks).some(trackId => tracks[trackId].duration)) {
  1813. // If duration samples are not available in the traf use sidx subsegment_duration
  1814. let sidxMinStart = Infinity;
  1815. let sidxMaxEnd = 0;
  1816. const sidxs = findBox(data, ['sidx']);
  1817. for (let i = 0; i < sidxs.length; i++) {
  1818. const sidx = parseSegmentIndex(sidxs[i]);
  1819. if (sidx != null && sidx.references) {
  1820. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  1821. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  1822. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  1823. }
  1824. }
  1825. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  1826. Object.keys(tracks).forEach(trackId => {
  1827. if (!tracks[trackId].duration) {
  1828. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  1829. }
  1830. });
  1831. }
  1832. }
  1833. return tracks;
  1834. }
  1835. // TODO: Check if the last moof+mdat pair is part of the valid range
  1836. function segmentValidRange(data) {
  1837. const segmentedRange = {
  1838. valid: null,
  1839. remainder: null
  1840. };
  1841. const moofs = findBox(data, ['moof']);
  1842. if (moofs.length < 2) {
  1843. segmentedRange.remainder = data;
  1844. return segmentedRange;
  1845. }
  1846. const last = moofs[moofs.length - 1];
  1847. // Offset by 8 bytes; findBox offsets the start by as much
  1848. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  1849. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  1850. return segmentedRange;
  1851. }
  1852. function appendUint8Array(data1, data2) {
  1853. const temp = new Uint8Array(data1.length + data2.length);
  1854. temp.set(data1);
  1855. temp.set(data2, data1.length);
  1856. return temp;
  1857. }
  1858. function parseSamples(timeOffset, track) {
  1859. const seiSamples = [];
  1860. const videoData = track.samples;
  1861. const timescale = track.timescale;
  1862. const trackId = track.id;
  1863. let isHEVCFlavor = false;
  1864. const moofs = findBox(videoData, ['moof']);
  1865. moofs.map(moof => {
  1866. const moofOffset = moof.byteOffset - 8;
  1867. const trafs = findBox(moof, ['traf']);
  1868. trafs.map(traf => {
  1869. // get the base media decode time from the tfdt
  1870. const baseTime = findBox(traf, ['tfdt']).map(tfdt => {
  1871. const version = tfdt[0];
  1872. let result = readUint32(tfdt, 4);
  1873. if (version === 1) {
  1874. result *= Math.pow(2, 32);
  1875. result += readUint32(tfdt, 8);
  1876. }
  1877. return result / timescale;
  1878. })[0];
  1879. if (baseTime !== undefined) {
  1880. timeOffset = baseTime;
  1881. }
  1882. return findBox(traf, ['tfhd']).map(tfhd => {
  1883. const id = readUint32(tfhd, 4);
  1884. const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  1885. const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  1886. const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  1887. const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  1888. let defaultSampleDuration = 0;
  1889. const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  1890. let defaultSampleSize = 0;
  1891. const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  1892. let tfhdOffset = 8;
  1893. if (id === trackId) {
  1894. if (baseDataOffsetPresent) {
  1895. tfhdOffset += 8;
  1896. }
  1897. if (sampleDescriptionIndexPresent) {
  1898. tfhdOffset += 4;
  1899. }
  1900. if (defaultSampleDurationPresent) {
  1901. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  1902. tfhdOffset += 4;
  1903. }
  1904. if (defaultSampleSizePresent) {
  1905. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  1906. tfhdOffset += 4;
  1907. }
  1908. if (defaultSampleFlagsPresent) {
  1909. tfhdOffset += 4;
  1910. }
  1911. if (track.type === 'video') {
  1912. isHEVCFlavor = isHEVC(track.codec);
  1913. }
  1914. findBox(traf, ['trun']).map(trun => {
  1915. const version = trun[0];
  1916. const flags = readUint32(trun, 0) & 0xffffff;
  1917. const dataOffsetPresent = (flags & 0x000001) !== 0;
  1918. let dataOffset = 0;
  1919. const firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  1920. const sampleDurationPresent = (flags & 0x000100) !== 0;
  1921. let sampleDuration = 0;
  1922. const sampleSizePresent = (flags & 0x000200) !== 0;
  1923. let sampleSize = 0;
  1924. const sampleFlagsPresent = (flags & 0x000400) !== 0;
  1925. const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  1926. let compositionOffset = 0;
  1927. const sampleCount = readUint32(trun, 4);
  1928. let trunOffset = 8; // past version, flags, and sample count
  1929. if (dataOffsetPresent) {
  1930. dataOffset = readUint32(trun, trunOffset);
  1931. trunOffset += 4;
  1932. }
  1933. if (firstSampleFlagsPresent) {
  1934. trunOffset += 4;
  1935. }
  1936. let sampleOffset = dataOffset + moofOffset;
  1937. for (let ix = 0; ix < sampleCount; ix++) {
  1938. if (sampleDurationPresent) {
  1939. sampleDuration = readUint32(trun, trunOffset);
  1940. trunOffset += 4;
  1941. } else {
  1942. sampleDuration = defaultSampleDuration;
  1943. }
  1944. if (sampleSizePresent) {
  1945. sampleSize = readUint32(trun, trunOffset);
  1946. trunOffset += 4;
  1947. } else {
  1948. sampleSize = defaultSampleSize;
  1949. }
  1950. if (sampleFlagsPresent) {
  1951. trunOffset += 4;
  1952. }
  1953. if (sampleCompositionOffsetsPresent) {
  1954. if (version === 0) {
  1955. compositionOffset = readUint32(trun, trunOffset);
  1956. } else {
  1957. compositionOffset = readSint32(trun, trunOffset);
  1958. }
  1959. trunOffset += 4;
  1960. }
  1961. if (track.type === ElementaryStreamTypes.VIDEO) {
  1962. let naluTotalSize = 0;
  1963. while (naluTotalSize < sampleSize) {
  1964. const naluSize = readUint32(videoData, sampleOffset);
  1965. sampleOffset += 4;
  1966. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  1967. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  1968. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  1969. }
  1970. sampleOffset += naluSize;
  1971. naluTotalSize += naluSize + 4;
  1972. }
  1973. }
  1974. timeOffset += sampleDuration / timescale;
  1975. }
  1976. });
  1977. }
  1978. });
  1979. });
  1980. });
  1981. return seiSamples;
  1982. }
  1983. function isHEVC(codec) {
  1984. if (!codec) {
  1985. return false;
  1986. }
  1987. const baseCodec = codec.substring(0, 4);
  1988. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  1989. // Dolby Vision
  1990. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  1991. }
  1992. function isSEIMessage(isHEVCFlavor, naluHeader) {
  1993. if (isHEVCFlavor) {
  1994. const naluType = naluHeader >> 1 & 0x3f;
  1995. return naluType === 39 || naluType === 40;
  1996. } else {
  1997. const naluType = naluHeader & 0x1f;
  1998. return naluType === 6;
  1999. }
  2000. }
  2001. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2002. const data = discardEPB(unescapedData);
  2003. let seiPtr = 0;
  2004. // skip nal header
  2005. seiPtr += headerSize;
  2006. let payloadType = 0;
  2007. let payloadSize = 0;
  2008. let b = 0;
  2009. while (seiPtr < data.length) {
  2010. payloadType = 0;
  2011. do {
  2012. if (seiPtr >= data.length) {
  2013. break;
  2014. }
  2015. b = data[seiPtr++];
  2016. payloadType += b;
  2017. } while (b === 0xff);
  2018. // Parse payload size.
  2019. payloadSize = 0;
  2020. do {
  2021. if (seiPtr >= data.length) {
  2022. break;
  2023. }
  2024. b = data[seiPtr++];
  2025. payloadSize += b;
  2026. } while (b === 0xff);
  2027. const leftOver = data.length - seiPtr;
  2028. // Create a variable to process the payload
  2029. let payPtr = seiPtr;
  2030. // Increment the seiPtr to the end of the payload
  2031. if (payloadSize < leftOver) {
  2032. seiPtr += payloadSize;
  2033. } else if (payloadSize > leftOver) {
  2034. // Some type of corruption has happened?
  2035. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  2036. // We might be able to parse some data, but let's be safe and ignore it.
  2037. break;
  2038. }
  2039. if (payloadType === 4) {
  2040. const countryCode = data[payPtr++];
  2041. if (countryCode === 181) {
  2042. const providerCode = readUint16(data, payPtr);
  2043. payPtr += 2;
  2044. if (providerCode === 49) {
  2045. const userStructure = readUint32(data, payPtr);
  2046. payPtr += 4;
  2047. if (userStructure === 0x47413934) {
  2048. const userDataType = data[payPtr++];
  2049. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2050. if (userDataType === 3) {
  2051. const firstByte = data[payPtr++];
  2052. const totalCCs = 0x1f & firstByte;
  2053. const enabled = 0x40 & firstByte;
  2054. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2055. const byteArray = new Uint8Array(totalBytes);
  2056. if (enabled) {
  2057. byteArray[0] = firstByte;
  2058. for (let i = 1; i < totalBytes; i++) {
  2059. byteArray[i] = data[payPtr++];
  2060. }
  2061. }
  2062. samples.push({
  2063. type: userDataType,
  2064. payloadType,
  2065. pts,
  2066. bytes: byteArray
  2067. });
  2068. }
  2069. }
  2070. }
  2071. }
  2072. } else if (payloadType === 5) {
  2073. if (payloadSize > 16) {
  2074. const uuidStrArray = [];
  2075. for (let i = 0; i < 16; i++) {
  2076. const _b = data[payPtr++].toString(16);
  2077. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2078. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2079. uuidStrArray.push('-');
  2080. }
  2081. }
  2082. const length = payloadSize - 16;
  2083. const userDataBytes = new Uint8Array(length);
  2084. for (let i = 0; i < length; i++) {
  2085. userDataBytes[i] = data[payPtr++];
  2086. }
  2087. samples.push({
  2088. payloadType,
  2089. pts,
  2090. uuid: uuidStrArray.join(''),
  2091. userData: utf8ArrayToStr(userDataBytes),
  2092. userDataBytes
  2093. });
  2094. }
  2095. }
  2096. }
  2097. }
  2098. /**
  2099. * remove Emulation Prevention bytes from a RBSP
  2100. */
  2101. function discardEPB(data) {
  2102. const length = data.byteLength;
  2103. const EPBPositions = [];
  2104. let i = 1;
  2105. // Find all `Emulation Prevention Bytes`
  2106. while (i < length - 2) {
  2107. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2108. EPBPositions.push(i + 2);
  2109. i += 2;
  2110. } else {
  2111. i++;
  2112. }
  2113. }
  2114. // If no Emulation Prevention Bytes were found just return the original
  2115. // array
  2116. if (EPBPositions.length === 0) {
  2117. return data;
  2118. }
  2119. // Create a new array to hold the NAL unit data
  2120. const newLength = length - EPBPositions.length;
  2121. const newData = new Uint8Array(newLength);
  2122. let sourceIndex = 0;
  2123. for (i = 0; i < newLength; sourceIndex++, i++) {
  2124. if (sourceIndex === EPBPositions[0]) {
  2125. // Skip this byte
  2126. sourceIndex++;
  2127. // Remove this position index
  2128. EPBPositions.shift();
  2129. }
  2130. newData[i] = data[sourceIndex];
  2131. }
  2132. return newData;
  2133. }
  2134. function parseEmsg(data) {
  2135. const version = data[0];
  2136. let schemeIdUri = '';
  2137. let value = '';
  2138. let timeScale = 0;
  2139. let presentationTimeDelta = 0;
  2140. let presentationTime = 0;
  2141. let eventDuration = 0;
  2142. let id = 0;
  2143. let offset = 0;
  2144. if (version === 0) {
  2145. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2146. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2147. offset += 1;
  2148. }
  2149. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2150. offset += 1;
  2151. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2152. value += bin2str(data.subarray(offset, offset + 1));
  2153. offset += 1;
  2154. }
  2155. value += bin2str(data.subarray(offset, offset + 1));
  2156. offset += 1;
  2157. timeScale = readUint32(data, 12);
  2158. presentationTimeDelta = readUint32(data, 16);
  2159. eventDuration = readUint32(data, 20);
  2160. id = readUint32(data, 24);
  2161. offset = 28;
  2162. } else if (version === 1) {
  2163. offset += 4;
  2164. timeScale = readUint32(data, offset);
  2165. offset += 4;
  2166. const leftPresentationTime = readUint32(data, offset);
  2167. offset += 4;
  2168. const rightPresentationTime = readUint32(data, offset);
  2169. offset += 4;
  2170. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  2171. if (!isSafeInteger(presentationTime)) {
  2172. presentationTime = Number.MAX_SAFE_INTEGER;
  2173. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2174. }
  2175. eventDuration = readUint32(data, offset);
  2176. offset += 4;
  2177. id = readUint32(data, offset);
  2178. offset += 4;
  2179. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2180. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2181. offset += 1;
  2182. }
  2183. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2184. offset += 1;
  2185. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2186. value += bin2str(data.subarray(offset, offset + 1));
  2187. offset += 1;
  2188. }
  2189. value += bin2str(data.subarray(offset, offset + 1));
  2190. offset += 1;
  2191. }
  2192. const payload = data.subarray(offset, data.byteLength);
  2193. return {
  2194. schemeIdUri,
  2195. value,
  2196. timeScale,
  2197. presentationTime,
  2198. presentationTimeDelta,
  2199. eventDuration,
  2200. id,
  2201. payload
  2202. };
  2203. }
  2204. function mp4Box(type, ...payload) {
  2205. const len = payload.length;
  2206. let size = 8;
  2207. let i = len;
  2208. while (i--) {
  2209. size += payload[i].byteLength;
  2210. }
  2211. const result = new Uint8Array(size);
  2212. result[0] = size >> 24 & 0xff;
  2213. result[1] = size >> 16 & 0xff;
  2214. result[2] = size >> 8 & 0xff;
  2215. result[3] = size & 0xff;
  2216. result.set(type, 4);
  2217. for (i = 0, size = 8; i < len; i++) {
  2218. result.set(payload[i], size);
  2219. size += payload[i].byteLength;
  2220. }
  2221. return result;
  2222. }
  2223. function mp4pssh(systemId, keyids, data) {
  2224. if (systemId.byteLength !== 16) {
  2225. throw new RangeError('Invalid system id');
  2226. }
  2227. let version;
  2228. let kids;
  2229. {
  2230. version = 0;
  2231. kids = new Uint8Array();
  2232. }
  2233. let kidCount;
  2234. if (version > 0) {
  2235. kidCount = new Uint8Array(4);
  2236. if (keyids.length > 0) {
  2237. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  2238. }
  2239. } else {
  2240. kidCount = new Uint8Array();
  2241. }
  2242. const dataSize = new Uint8Array(4);
  2243. if (data && data.byteLength > 0) {
  2244. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  2245. }
  2246. return mp4Box([112, 115, 115, 104], new Uint8Array([version, 0x00, 0x00, 0x00 // Flags
  2247. ]), systemId,
  2248. // 16 bytes
  2249. kidCount, kids, dataSize, data || new Uint8Array());
  2250. }
  2251. const userAgentHevcSupportIsInaccurate = () => {
  2252. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  2253. };
  2254. // from http://mp4ra.org/codecs.html
  2255. // values indicate codec selection preference (lower is higher priority)
  2256. const sampleEntryCodesISO = {
  2257. audio: {
  2258. a3ds: 1,
  2259. 'ac-3': 0.95,
  2260. 'ac-4': 1,
  2261. alac: 0.9,
  2262. alaw: 1,
  2263. dra1: 1,
  2264. 'dts+': 1,
  2265. 'dts-': 1,
  2266. dtsc: 1,
  2267. dtse: 1,
  2268. dtsh: 1,
  2269. 'ec-3': 0.9,
  2270. enca: 1,
  2271. fLaC: 0.9,
  2272. // MP4-RA listed codec entry for FLAC
  2273. flac: 0.9,
  2274. // legacy browser codec name for FLAC
  2275. FLAC: 0.9,
  2276. // some manifests may list "FLAC" with Apple's tools
  2277. g719: 1,
  2278. g726: 1,
  2279. m4ae: 1,
  2280. mha1: 1,
  2281. mha2: 1,
  2282. mhm1: 1,
  2283. mhm2: 1,
  2284. mlpa: 1,
  2285. mp4a: 1,
  2286. 'raw ': 1,
  2287. Opus: 1,
  2288. opus: 1,
  2289. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2290. samr: 1,
  2291. sawb: 1,
  2292. sawp: 1,
  2293. sevc: 1,
  2294. sqcp: 1,
  2295. ssmv: 1,
  2296. twos: 1,
  2297. ulaw: 1
  2298. },
  2299. video: {
  2300. avc1: 1,
  2301. avc2: 1,
  2302. avc3: 1,
  2303. avc4: 1,
  2304. avcp: 1,
  2305. av01: 0.8,
  2306. dav1: 0.8,
  2307. drac: 1,
  2308. dva1: 1,
  2309. dvav: 1,
  2310. dvh1: 0.7,
  2311. dvhe: 0.7,
  2312. encv: 1,
  2313. hev1: 0.75,
  2314. hvc1: 0.75,
  2315. mjp2: 1,
  2316. mp4v: 1,
  2317. mvc1: 1,
  2318. mvc2: 1,
  2319. mvc3: 1,
  2320. mvc4: 1,
  2321. resv: 1,
  2322. rv60: 1,
  2323. s263: 1,
  2324. svc1: 1,
  2325. svc2: 1,
  2326. 'vc-1': 1,
  2327. vp08: 1,
  2328. vp09: 0.9
  2329. },
  2330. text: {
  2331. stpp: 1,
  2332. wvtt: 1
  2333. }
  2334. };
  2335. function isCodecType(codec, type) {
  2336. const typeCodes = sampleEntryCodesISO[type];
  2337. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2338. }
  2339. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2340. return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2341. }
  2342. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2343. var _MediaSource$isTypeSu;
  2344. const MediaSource = getMediaSource(preferManagedMediaSource);
  2345. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2346. }
  2347. function mimeTypeForCodec(codec, type) {
  2348. return `${type}/mp4;codecs=${codec}`;
  2349. }
  2350. function videoCodecPreferenceValue(videoCodec) {
  2351. if (videoCodec) {
  2352. const fourCC = videoCodec.substring(0, 4);
  2353. return sampleEntryCodesISO.video[fourCC];
  2354. }
  2355. return 2;
  2356. }
  2357. function codecsSetSelectionPreferenceValue(codecSet) {
  2358. const limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  2359. return codecSet.split(',').reduce((num, fourCC) => {
  2360. const lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  2361. const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  2362. if (preferenceValue) {
  2363. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2364. }
  2365. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2366. }, 0);
  2367. }
  2368. const CODEC_COMPATIBLE_NAMES = {};
  2369. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2370. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2371. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2372. }
  2373. const codecsToCheck = {
  2374. // Idealy fLaC and Opus would be first (spec-compliant) but
  2375. // some browsers will report that fLaC is supported then fail.
  2376. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2377. flac: ['flac', 'fLaC', 'FLAC'],
  2378. opus: ['opus', 'Opus'],
  2379. // Replace audio codec info if browser does not support mp4a.40.34,
  2380. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2381. 'mp4a.40.34': ['mp3']
  2382. }[lowerCaseCodec];
  2383. for (let i = 0; i < codecsToCheck.length; i++) {
  2384. var _getMediaSource;
  2385. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2386. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2387. return codecsToCheck[i];
  2388. } else if (codecsToCheck[i] === 'mp3' && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported('audio/mpeg')) {
  2389. return '';
  2390. }
  2391. }
  2392. return lowerCaseCodec;
  2393. }
  2394. const AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2395. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2396. return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2397. }
  2398. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2399. const codecs = [];
  2400. if (originalCodecs) {
  2401. const allCodecs = originalCodecs.split(',');
  2402. for (let i = 0; i < allCodecs.length; i++) {
  2403. if (!isCodecType(allCodecs[i], 'video')) {
  2404. codecs.push(allCodecs[i]);
  2405. }
  2406. }
  2407. }
  2408. if (newVideoCodec) {
  2409. codecs.push(newVideoCodec);
  2410. }
  2411. return codecs.join(',');
  2412. }
  2413. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2414. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2415. // so use level codec is parsed codec is unavailable or incomplete
  2416. if (parsedCodec && (parsedCodec.length > 4 || ['ac-3', 'ec-3', 'alac', 'fLaC', 'Opus'].indexOf(parsedCodec) !== -1)) {
  2417. if (isCodecSupportedAsType(parsedCodec, 'audio') || isCodecSupportedAsType(parsedCodec, 'video')) {
  2418. return parsedCodec;
  2419. }
  2420. }
  2421. if (levelCodec) {
  2422. const levelCodecs = levelCodec.split(',');
  2423. if (levelCodecs.length > 1) {
  2424. if (parsedCodec) {
  2425. for (let i = levelCodecs.length; i--;) {
  2426. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2427. return levelCodecs[i];
  2428. }
  2429. }
  2430. }
  2431. return levelCodecs[0];
  2432. }
  2433. }
  2434. return levelCodec || parsedCodec;
  2435. }
  2436. function isCodecSupportedAsType(codec, type) {
  2437. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2438. }
  2439. function convertAVC1ToAVCOTI(videoCodecs) {
  2440. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2441. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2442. const codecs = videoCodecs.split(',');
  2443. for (let i = 0; i < codecs.length; i++) {
  2444. const avcdata = codecs[i].split('.');
  2445. // only convert codec strings starting with avc1 (Examples: avc1.64001f,dvh1.05.07)
  2446. if (avcdata.length > 2 && avcdata[0] === 'avc1') {
  2447. codecs[i] = `avc1.${parseInt(avcdata[1]).toString(16)}${('000' + parseInt(avcdata[2]).toString(16)).slice(-4)}`;
  2448. }
  2449. }
  2450. return codecs.join(',');
  2451. }
  2452. function fillInMissingAV01Params(videoCodec) {
  2453. // Used to fill in incomplete AV1 playlist CODECS strings for mediaCapabilities.decodingInfo queries
  2454. if (videoCodec.startsWith('av01.')) {
  2455. const av1params = videoCodec.split('.');
  2456. const placeholders = ['0', '111', '01', '01', '01', '0'];
  2457. for (let i = av1params.length; i > 4 && i < 10; i++) {
  2458. av1params[i] = placeholders[i - 4];
  2459. }
  2460. return av1params.join('.');
  2461. }
  2462. return videoCodec;
  2463. }
  2464. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2465. const MediaSource = getMediaSource(preferManagedMediaSource) || {
  2466. isTypeSupported: () => false
  2467. };
  2468. return {
  2469. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  2470. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2471. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  2472. };
  2473. }
  2474. function getCodecsForMimeType(mimeType) {
  2475. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, '$1');
  2476. }
  2477. const SUPPORTED_INFO_DEFAULT = {
  2478. supported: true,
  2479. configurations: [],
  2480. decodingInfoResults: [{
  2481. supported: true,
  2482. powerEfficient: true,
  2483. smooth: true
  2484. }]
  2485. };
  2486. function getUnsupportedResult(error, configurations) {
  2487. return {
  2488. supported: false,
  2489. configurations,
  2490. decodingInfoResults: [{
  2491. supported: false,
  2492. smooth: false,
  2493. powerEfficient: false
  2494. }],
  2495. error
  2496. };
  2497. }
  2498. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  2499. // Only test support when configuration is exceeds minimum options
  2500. const videoCodecs = level.videoCodec;
  2501. const audioGroups = level.audioCodec ? level.audioGroups : null;
  2502. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2503. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2504. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  2505. let audioChannels = null;
  2506. if (audioGroups != null && audioGroups.length) {
  2507. try {
  2508. if (audioGroups.length === 1 && audioGroups[0]) {
  2509. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  2510. } else {
  2511. audioChannels = audioGroups.reduce((acc, groupId) => {
  2512. if (groupId) {
  2513. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  2514. if (!audioTrackGroup) {
  2515. throw new Error(`Audio track group ${groupId} not found`);
  2516. }
  2517. // Sum all channel key values
  2518. Object.keys(audioTrackGroup.channels).forEach(key => {
  2519. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  2520. });
  2521. }
  2522. return acc;
  2523. }, {
  2524. 2: 0
  2525. });
  2526. }
  2527. } catch (error) {
  2528. return true;
  2529. }
  2530. }
  2531. return videoCodecs !== undefined && (
  2532. // Force media capabilities check for HEVC to avoid failure on Windows
  2533. videoCodecs.split(',').some(videoCodec => isHEVC(videoCodec)) || level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== 'SDR' && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some(channels => parseInt(channels) > maxChannels);
  2534. }
  2535. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache = {}) {
  2536. const videoCodecs = level.videoCodec;
  2537. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  2538. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  2539. }
  2540. const configurations = [];
  2541. const videoDecodeList = makeVideoConfigurations(level);
  2542. const videoCount = videoDecodeList.length;
  2543. const audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  2544. const audioCount = audioDecodeList.length;
  2545. for (let i = videoCount || 1 * audioCount || 1; i--;) {
  2546. const configuration = {
  2547. type: 'media-source'
  2548. };
  2549. if (videoCount) {
  2550. configuration.video = videoDecodeList[i % videoCount];
  2551. }
  2552. if (audioCount) {
  2553. configuration.audio = audioDecodeList[i % audioCount];
  2554. const audioBitrate = configuration.audio.bitrate;
  2555. if (configuration.video && audioBitrate) {
  2556. configuration.video.bitrate -= audioBitrate;
  2557. }
  2558. }
  2559. configurations.push(configuration);
  2560. }
  2561. if (videoCodecs) {
  2562. // Override Windows Firefox HEVC MediaCapabilities result (https://github.com/video-dev/hls.js/issues/7046)
  2563. const ua = navigator.userAgent;
  2564. if (videoCodecs.split(',').some(videoCodec => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {
  2565. return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${ua})`), configurations));
  2566. }
  2567. }
  2568. return Promise.all(configurations.map(configuration => {
  2569. // Cache MediaCapabilities promises
  2570. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  2571. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  2572. })).then(decodingInfoResults => ({
  2573. supported: !decodingInfoResults.some(info => !info.supported),
  2574. configurations,
  2575. decodingInfoResults
  2576. })).catch(error => ({
  2577. supported: false,
  2578. configurations,
  2579. decodingInfoResults: [],
  2580. error
  2581. }));
  2582. }
  2583. function makeVideoConfigurations(level) {
  2584. var _level$videoCodec;
  2585. const videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(',');
  2586. const bitrate = getVariantDecodingBitrate(level);
  2587. const width = level.width || 640;
  2588. const height = level.height || 480;
  2589. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  2590. const framerate = level.frameRate || 30;
  2591. const videoRange = level.videoRange.toLowerCase();
  2592. return videoCodecs ? videoCodecs.map(videoCodec => {
  2593. const videoConfiguration = {
  2594. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), 'video'),
  2595. width,
  2596. height,
  2597. bitrate,
  2598. framerate
  2599. };
  2600. if (videoRange !== 'sdr') {
  2601. videoConfiguration.transferFunction = videoRange;
  2602. }
  2603. return videoConfiguration;
  2604. }) : [];
  2605. }
  2606. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  2607. var _level$audioCodec;
  2608. const audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(',');
  2609. const combinedBitrate = getVariantDecodingBitrate(level);
  2610. if (audioCodecs && level.audioGroups) {
  2611. return level.audioGroups.reduce((configurations, audioGroupId) => {
  2612. var _audioTracksByGroup$g;
  2613. const tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  2614. if (tracks) {
  2615. return tracks.reduce((configs, audioTrack) => {
  2616. if (audioTrack.groupId === audioGroupId) {
  2617. const channelsNumber = parseFloat(audioTrack.channels || '');
  2618. audioCodecs.forEach(audioCodec => {
  2619. const audioConfiguration = {
  2620. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  2621. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  2622. };
  2623. if (channelsNumber) {
  2624. audioConfiguration.channels = '' + channelsNumber;
  2625. }
  2626. configs.push(audioConfiguration);
  2627. });
  2628. }
  2629. return configs;
  2630. }, configurations);
  2631. }
  2632. return configurations;
  2633. }, []);
  2634. }
  2635. return [];
  2636. }
  2637. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  2638. if (levelBitrate <= 1) {
  2639. return 1;
  2640. }
  2641. let audioBitrate = 128000;
  2642. if (audioCodec === 'ec-3') {
  2643. audioBitrate = 768000;
  2644. } else if (audioCodec === 'ac-3') {
  2645. audioBitrate = 640000;
  2646. }
  2647. return Math.min(levelBitrate / 2, audioBitrate); // Don't exceed some % of level bitrate
  2648. }
  2649. function getVariantDecodingBitrate(level) {
  2650. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1000) * 1000 || 1;
  2651. }
  2652. function getMediaDecodingInfoKey(config) {
  2653. let key = '';
  2654. const {
  2655. audio,
  2656. video
  2657. } = config;
  2658. if (video) {
  2659. const codec = getCodecsForMimeType(video.contentType);
  2660. key += `${codec}_r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || 'sd'}_${Math.ceil(video.bitrate / 1e5)}`;
  2661. }
  2662. if (audio) {
  2663. const codec = getCodecsForMimeType(audio.contentType);
  2664. key += `${video ? '_' : ''}${codec}_c${audio.channels}`;
  2665. }
  2666. return key;
  2667. }
  2668. const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  2669. function isHdcpLevel(value) {
  2670. return HdcpLevels.indexOf(value) > -1;
  2671. }
  2672. const VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  2673. function isVideoRange(value) {
  2674. return !!value && VideoRangeValues.indexOf(value) > -1;
  2675. }
  2676. var HlsSkip = {
  2677. No: "",
  2678. Yes: "YES",
  2679. v2: "v2"
  2680. };
  2681. function getSkipValue(details) {
  2682. const {
  2683. canSkipUntil,
  2684. canSkipDateRanges,
  2685. age
  2686. } = details;
  2687. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  2688. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  2689. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  2690. const playlistRecentEnough = age < canSkipUntil / 2;
  2691. if (canSkipUntil && playlistRecentEnough) {
  2692. if (canSkipDateRanges) {
  2693. return HlsSkip.v2;
  2694. }
  2695. return HlsSkip.Yes;
  2696. }
  2697. return HlsSkip.No;
  2698. }
  2699. class HlsUrlParameters {
  2700. constructor(msn, part, skip) {
  2701. this.msn = void 0;
  2702. this.part = void 0;
  2703. this.skip = void 0;
  2704. this.msn = msn;
  2705. this.part = part;
  2706. this.skip = skip;
  2707. }
  2708. addDirectives(uri) {
  2709. const url = new self.URL(uri);
  2710. if (this.msn !== undefined) {
  2711. url.searchParams.set('_HLS_msn', this.msn.toString());
  2712. }
  2713. if (this.part !== undefined) {
  2714. url.searchParams.set('_HLS_part', this.part.toString());
  2715. }
  2716. if (this.skip) {
  2717. url.searchParams.set('_HLS_skip', this.skip);
  2718. }
  2719. return url.href;
  2720. }
  2721. }
  2722. class Level {
  2723. constructor(data) {
  2724. this._attrs = void 0;
  2725. this.audioCodec = void 0;
  2726. this.bitrate = void 0;
  2727. this.codecSet = void 0;
  2728. this.url = void 0;
  2729. this.frameRate = void 0;
  2730. this.height = void 0;
  2731. this.id = void 0;
  2732. this.name = void 0;
  2733. this.supplemental = void 0;
  2734. this.videoCodec = void 0;
  2735. this.width = void 0;
  2736. this.details = void 0;
  2737. this.fragmentError = 0;
  2738. this.loadError = 0;
  2739. this.loaded = void 0;
  2740. this.realBitrate = 0;
  2741. this.supportedPromise = void 0;
  2742. this.supportedResult = void 0;
  2743. this._avgBitrate = 0;
  2744. this._audioGroups = void 0;
  2745. this._subtitleGroups = void 0;
  2746. // Deprecated (retained for backwards compatibility)
  2747. this._urlId = 0;
  2748. this.url = [data.url];
  2749. this._attrs = [data.attrs];
  2750. this.bitrate = data.bitrate;
  2751. if (data.details) {
  2752. this.details = data.details;
  2753. }
  2754. this.id = data.id || 0;
  2755. this.name = data.name;
  2756. this.width = data.width || 0;
  2757. this.height = data.height || 0;
  2758. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  2759. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  2760. this.audioCodec = data.audioCodec;
  2761. this.videoCodec = data.videoCodec;
  2762. this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');
  2763. if ('supplemental' in data) {
  2764. var _data$supplemental;
  2765. this.supplemental = data.supplemental;
  2766. const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  2767. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  2768. this.codecSet += `,${supplementalVideo.substring(0, 4)}`;
  2769. }
  2770. }
  2771. this.addGroupId('audio', data.attrs.AUDIO);
  2772. this.addGroupId('text', data.attrs.SUBTITLES);
  2773. }
  2774. get maxBitrate() {
  2775. return Math.max(this.realBitrate, this.bitrate);
  2776. }
  2777. get averageBitrate() {
  2778. return this._avgBitrate || this.realBitrate || this.bitrate;
  2779. }
  2780. get attrs() {
  2781. return this._attrs[0];
  2782. }
  2783. get codecs() {
  2784. return this.attrs.CODECS || '';
  2785. }
  2786. get pathwayId() {
  2787. return this.attrs['PATHWAY-ID'] || '.';
  2788. }
  2789. get videoRange() {
  2790. return this.attrs['VIDEO-RANGE'] || 'SDR';
  2791. }
  2792. get score() {
  2793. return this.attrs.optionalFloat('SCORE', 0);
  2794. }
  2795. get uri() {
  2796. return this.url[0] || '';
  2797. }
  2798. hasAudioGroup(groupId) {
  2799. return hasGroup(this._audioGroups, groupId);
  2800. }
  2801. hasSubtitleGroup(groupId) {
  2802. return hasGroup(this._subtitleGroups, groupId);
  2803. }
  2804. get audioGroups() {
  2805. return this._audioGroups;
  2806. }
  2807. get subtitleGroups() {
  2808. return this._subtitleGroups;
  2809. }
  2810. addGroupId(type, groupId) {
  2811. if (!groupId) {
  2812. return;
  2813. }
  2814. if (type === 'audio') {
  2815. let audioGroups = this._audioGroups;
  2816. if (!audioGroups) {
  2817. audioGroups = this._audioGroups = [];
  2818. }
  2819. if (audioGroups.indexOf(groupId) === -1) {
  2820. audioGroups.push(groupId);
  2821. }
  2822. } else if (type === 'text') {
  2823. let subtitleGroups = this._subtitleGroups;
  2824. if (!subtitleGroups) {
  2825. subtitleGroups = this._subtitleGroups = [];
  2826. }
  2827. if (subtitleGroups.indexOf(groupId) === -1) {
  2828. subtitleGroups.push(groupId);
  2829. }
  2830. }
  2831. }
  2832. // Deprecated methods (retained for backwards compatibility)
  2833. get urlId() {
  2834. return 0;
  2835. }
  2836. set urlId(value) {}
  2837. get audioGroupIds() {
  2838. return this.audioGroups ? [this.audioGroupId] : undefined;
  2839. }
  2840. get textGroupIds() {
  2841. return this.subtitleGroups ? [this.textGroupId] : undefined;
  2842. }
  2843. get audioGroupId() {
  2844. var _this$audioGroups;
  2845. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  2846. }
  2847. get textGroupId() {
  2848. var _this$subtitleGroups;
  2849. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  2850. }
  2851. addFallback() {}
  2852. }
  2853. function hasGroup(groups, groupId) {
  2854. if (!groupId || !groups) {
  2855. return false;
  2856. }
  2857. return groups.indexOf(groupId) !== -1;
  2858. }
  2859. /**
  2860. * @returns Whether we can detect and validate HDR capability within the window context
  2861. */
  2862. function isHdrSupported() {
  2863. if (typeof matchMedia === 'function') {
  2864. const mediaQueryList = matchMedia('(dynamic-range: high)');
  2865. const badQuery = matchMedia('bad query');
  2866. if (mediaQueryList.media !== badQuery.media) {
  2867. return mediaQueryList.matches === true;
  2868. }
  2869. }
  2870. return false;
  2871. }
  2872. /**
  2873. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  2874. * When both inputs are null:
  2875. *
  2876. * `{ preferHDR: false, allowedVideoRanges: [] }`
  2877. *
  2878. * When `currentVideoRange` non-null, maintain the active range:
  2879. *
  2880. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  2881. *
  2882. * When VideoSelectionOption non-null:
  2883. *
  2884. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  2885. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  2886. * - Else check window for HDR support and set `preferHDR` to the result.
  2887. *
  2888. * @param currentVideoRange
  2889. * @param videoPreference
  2890. */
  2891. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  2892. let preferHDR = false;
  2893. let allowedVideoRanges = [];
  2894. if (currentVideoRange) {
  2895. preferHDR = currentVideoRange !== 'SDR';
  2896. allowedVideoRanges = [currentVideoRange];
  2897. }
  2898. if (videoPreference) {
  2899. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  2900. const allowAutoPreferHDR = allowedVideoRanges.join('') !== 'SDR' && !videoPreference.videoCodec;
  2901. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  2902. if (!preferHDR) {
  2903. allowedVideoRanges = ['SDR'];
  2904. }
  2905. }
  2906. return {
  2907. preferHDR,
  2908. allowedVideoRanges
  2909. };
  2910. }
  2911. const omitCircularRefsReplacer = replacer => {
  2912. const known = new WeakSet();
  2913. return (_, value) => {
  2914. if (replacer) {
  2915. value = replacer(_, value);
  2916. }
  2917. if (typeof value === 'object' && value !== null) {
  2918. if (known.has(value)) {
  2919. return;
  2920. }
  2921. known.add(value);
  2922. }
  2923. return value;
  2924. };
  2925. };
  2926. const stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));
  2927. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  2928. const codecSets = Object.keys(codecTiers);
  2929. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2930. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2931. const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  2932. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  2933. // Use first level set to determine stereo, and minimum resolution and framerate
  2934. let hasStereo = false;
  2935. let hasCurrentVideoRange = false;
  2936. let minHeight = Infinity;
  2937. let minFramerate = Infinity;
  2938. let minBitrate = Infinity;
  2939. let minIndex = Infinity;
  2940. let selectedScore = 0;
  2941. let videoRanges = [];
  2942. const {
  2943. preferHDR,
  2944. allowedVideoRanges
  2945. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  2946. for (let i = codecSets.length; i--;) {
  2947. const tier = codecTiers[codecSets[i]];
  2948. hasStereo || (hasStereo = tier.channels[2] > 0);
  2949. minHeight = Math.min(minHeight, tier.minHeight);
  2950. minFramerate = Math.min(minFramerate, tier.minFramerate);
  2951. minBitrate = Math.min(minBitrate, tier.minBitrate);
  2952. const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);
  2953. if (matchingVideoRanges.length > 0) {
  2954. hasCurrentVideoRange = true;
  2955. }
  2956. }
  2957. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  2958. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  2959. const maxHeight = Math.max(1080, minHeight);
  2960. const maxFramerate = Math.max(30, minFramerate);
  2961. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  2962. currentBw = Math.max(minBitrate, currentBw);
  2963. // If there are no variants with matching preference, set currentVideoRange to undefined
  2964. if (!hasCurrentVideoRange) {
  2965. currentVideoRange = undefined;
  2966. }
  2967. const hasMultipleSets = codecSets.length > 1;
  2968. const codecSet = codecSets.reduce((selected, candidate) => {
  2969. // 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
  2970. const candidateTier = codecTiers[candidate];
  2971. if (candidate === selected) {
  2972. return selected;
  2973. }
  2974. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter(range => candidateTier.videoRanges[range] > 0) : [];
  2975. if (hasMultipleSets) {
  2976. if (candidateTier.minBitrate > currentBw) {
  2977. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  2978. return selected;
  2979. }
  2980. if (!candidateTier.hasDefaultAudio) {
  2981. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  2982. return selected;
  2983. }
  2984. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  2985. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  2986. return selected;
  2987. }
  2988. if (channelsPreference && !preferStereo) {
  2989. if (!candidateTier.channels[channelsPreference]) {
  2990. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  2991. return selected;
  2992. }
  2993. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  2994. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  2995. return selected;
  2996. }
  2997. if (candidateTier.minHeight > maxHeight) {
  2998. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  2999. return selected;
  3000. }
  3001. if (candidateTier.minFramerate > maxFramerate) {
  3002. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  3003. return selected;
  3004. }
  3005. if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {
  3006. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);
  3007. return selected;
  3008. }
  3009. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  3010. logStartCodecCandidateIgnored(candidate, `video codec preference "${videoCodecPreference}" not found`);
  3011. return selected;
  3012. }
  3013. if (candidateTier.maxScore < selectedScore) {
  3014. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  3015. return selected;
  3016. }
  3017. }
  3018. // Remove candiates with less preferred codecs or more errors
  3019. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  3020. return selected;
  3021. }
  3022. minIndex = candidateTier.minIndex;
  3023. selectedScore = candidateTier.maxScore;
  3024. return candidate;
  3025. }, undefined);
  3026. return {
  3027. codecSet,
  3028. videoRanges,
  3029. preferHDR,
  3030. minFramerate,
  3031. minBitrate,
  3032. minIndex
  3033. };
  3034. }
  3035. function logStartCodecCandidateIgnored(codeSet, reason) {
  3036. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  3037. }
  3038. function getAudioTracksByGroup(allAudioTracks) {
  3039. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  3040. let trackGroup = audioTracksByGroup.groups[track.groupId];
  3041. if (!trackGroup) {
  3042. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  3043. tracks: [],
  3044. channels: {
  3045. 2: 0
  3046. },
  3047. hasDefault: false,
  3048. hasAutoSelect: false
  3049. };
  3050. }
  3051. trackGroup.tracks.push(track);
  3052. const channelsKey = track.channels || '2';
  3053. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  3054. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  3055. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  3056. if (trackGroup.hasDefault) {
  3057. audioTracksByGroup.hasDefaultAudio = true;
  3058. }
  3059. if (trackGroup.hasAutoSelect) {
  3060. audioTracksByGroup.hasAutoSelectAudio = true;
  3061. }
  3062. return audioTracksByGroup;
  3063. }, {
  3064. hasDefaultAudio: false,
  3065. hasAutoSelectAudio: false,
  3066. groups: {}
  3067. });
  3068. }
  3069. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  3070. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {
  3071. if (!level.codecSet) {
  3072. return tiers;
  3073. }
  3074. const audioGroups = level.audioGroups;
  3075. let tier = tiers[level.codecSet];
  3076. if (!tier) {
  3077. tiers[level.codecSet] = tier = {
  3078. minBitrate: Infinity,
  3079. minHeight: Infinity,
  3080. minFramerate: Infinity,
  3081. minIndex: index,
  3082. maxScore: 0,
  3083. videoRanges: {
  3084. SDR: 0
  3085. },
  3086. channels: {
  3087. '2': 0
  3088. },
  3089. hasDefaultAudio: !audioGroups,
  3090. fragmentError: 0
  3091. };
  3092. }
  3093. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  3094. const lesserWidthOrHeight = Math.min(level.height, level.width);
  3095. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  3096. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  3097. tier.minIndex = Math.min(tier.minIndex, index);
  3098. tier.maxScore = Math.max(tier.maxScore, level.score);
  3099. tier.fragmentError += level.fragmentError;
  3100. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  3101. if (audioGroups) {
  3102. audioGroups.forEach(audioGroupId => {
  3103. if (!audioGroupId) {
  3104. return;
  3105. }
  3106. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  3107. if (!audioGroup) {
  3108. return;
  3109. }
  3110. // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants
  3111. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  3112. Object.keys(audioGroup.channels).forEach(channels => {
  3113. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  3114. });
  3115. });
  3116. }
  3117. return tiers;
  3118. }, {});
  3119. }
  3120. function getBasicSelectionOption(option) {
  3121. if (!option) {
  3122. return option;
  3123. }
  3124. const {
  3125. lang,
  3126. assocLang,
  3127. characteristics,
  3128. channels,
  3129. audioCodec
  3130. } = option;
  3131. return {
  3132. lang,
  3133. assocLang,
  3134. characteristics,
  3135. channels,
  3136. audioCodec
  3137. };
  3138. }
  3139. function findMatchingOption(option, tracks, matchPredicate) {
  3140. if ('attrs' in option) {
  3141. const index = tracks.indexOf(option);
  3142. if (index !== -1) {
  3143. return index;
  3144. }
  3145. }
  3146. for (let i = 0; i < tracks.length; i++) {
  3147. const track = tracks[i];
  3148. if (matchesOption(option, track, matchPredicate)) {
  3149. return i;
  3150. }
  3151. }
  3152. return -1;
  3153. }
  3154. function matchesOption(option, track, matchPredicate) {
  3155. const {
  3156. groupId,
  3157. name,
  3158. lang,
  3159. assocLang,
  3160. default: isDefault
  3161. } = option;
  3162. const forced = option.forced;
  3163. return (groupId === undefined || track.groupId === groupId) && (name === undefined || track.name === name) && (lang === undefined || languagesMatch(lang, track.lang)) && (lang === undefined || track.assocLang === assocLang) && (isDefault === undefined || track.default === isDefault) && (forced === undefined || track.forced === forced) && (!('characteristics' in option) || characteristicsMatch(option.characteristics || '', track.characteristics)) && (matchPredicate === undefined || matchPredicate(option, track));
  3164. }
  3165. function languagesMatch(languageA, languageB = '--') {
  3166. if (languageA.length === languageB.length) {
  3167. return languageA === languageB;
  3168. }
  3169. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  3170. }
  3171. function characteristicsMatch(characteristicsA, characteristicsB = '') {
  3172. const arrA = characteristicsA.split(',');
  3173. const arrB = characteristicsB.split(',');
  3174. // Expects each item to be unique:
  3175. return arrA.length === arrB.length && !arrA.some(el => arrB.indexOf(el) === -1);
  3176. }
  3177. function audioMatchPredicate(option, track) {
  3178. const {
  3179. audioCodec,
  3180. channels
  3181. } = option;
  3182. return (audioCodec === undefined || (track.audioCodec || '').substring(0, 4) === audioCodec.substring(0, 4)) && (channels === undefined || channels === (track.channels || '2'));
  3183. }
  3184. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  3185. const currentLevel = levels[searchIndex];
  3186. // Are there variants with same URI as current level?
  3187. // If so, find a match that does not require any level URI change
  3188. const variants = levels.reduce((variantMap, level, index) => {
  3189. const uri = level.uri;
  3190. const renditions = variantMap[uri] || (variantMap[uri] = []);
  3191. renditions.push(index);
  3192. return variantMap;
  3193. }, {});
  3194. const renditions = variants[currentLevel.uri];
  3195. if (renditions.length > 1) {
  3196. searchIndex = Math.max.apply(Math, renditions);
  3197. }
  3198. // Find best match
  3199. const currentVideoRange = currentLevel.videoRange;
  3200. const currentFrameRate = currentLevel.frameRate;
  3201. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  3202. const matchingVideo = searchDownAndUpList(levels, searchIndex, level => {
  3203. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  3204. return false;
  3205. }
  3206. const audioGroups = level.audioGroups;
  3207. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  3208. return findMatchingOption(option, tracks, matchPredicate) > -1;
  3209. });
  3210. if (matchingVideo > -1) {
  3211. return matchingVideo;
  3212. }
  3213. return searchDownAndUpList(levels, searchIndex, level => {
  3214. const audioGroups = level.audioGroups;
  3215. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  3216. return findMatchingOption(option, tracks, matchPredicate) > -1;
  3217. });
  3218. }
  3219. function searchDownAndUpList(arr, searchIndex, predicate) {
  3220. for (let i = searchIndex; i > -1; i--) {
  3221. if (predicate(arr[i])) {
  3222. return i;
  3223. }
  3224. }
  3225. for (let i = searchIndex + 1; i < arr.length; i++) {
  3226. if (predicate(arr[i])) {
  3227. return i;
  3228. }
  3229. }
  3230. return -1;
  3231. }
  3232. function useAlternateAudio(audioTrackUrl, hls) {
  3233. var _hls$loadLevelObj;
  3234. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  3235. }
  3236. class AbrController extends Logger {
  3237. constructor(_hls) {
  3238. super('abr', _hls.logger);
  3239. this.hls = void 0;
  3240. this.lastLevelLoadSec = 0;
  3241. this.lastLoadedFragLevel = -1;
  3242. this.firstSelection = -1;
  3243. this._nextAutoLevel = -1;
  3244. this.nextAutoLevelKey = '';
  3245. this.audioTracksByGroup = null;
  3246. this.codecTiers = null;
  3247. this.timer = -1;
  3248. this.fragCurrent = null;
  3249. this.partCurrent = null;
  3250. this.bitrateTestDelay = 0;
  3251. this.rebufferNotice = -1;
  3252. this.supportedCache = {};
  3253. this.bwEstimator = void 0;
  3254. /*
  3255. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  3256. quickly enough to prevent underbuffering
  3257. */
  3258. this._abandonRulesCheck = levelLoaded => {
  3259. var _ref;
  3260. const {
  3261. fragCurrent: frag,
  3262. partCurrent: part,
  3263. hls
  3264. } = this;
  3265. const {
  3266. autoLevelEnabled,
  3267. media
  3268. } = hls;
  3269. if (!frag || !media) {
  3270. return;
  3271. }
  3272. const now = performance.now();
  3273. const stats = part ? part.stats : frag.stats;
  3274. const duration = part ? part.duration : frag.duration;
  3275. const timeLoading = now - stats.loading.start;
  3276. const minAutoLevel = hls.minAutoLevel;
  3277. const loadingFragForLevel = frag.level;
  3278. const currentAutoLevel = this._nextAutoLevel;
  3279. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  3280. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  3281. this.clearTimer();
  3282. // reset forced auto level value so that next level will be selected
  3283. this._nextAutoLevel = -1;
  3284. return;
  3285. }
  3286. // This check only runs if we're in ABR mode
  3287. if (!autoLevelEnabled) {
  3288. return;
  3289. }
  3290. // Must be loading/loaded a new level or be in a playing state
  3291. const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  3292. const levelChange = !!levelLoaded || fragBlockingSwitch;
  3293. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  3294. return;
  3295. }
  3296. const bufferInfo = hls.mainForwardBufferInfo;
  3297. if (!levelChange && bufferInfo === null) {
  3298. return;
  3299. }
  3300. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3301. const playbackRate = Math.abs(media.playbackRate);
  3302. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  3303. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  3304. return;
  3305. }
  3306. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  3307. const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  3308. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3309. const loadedFirstByte = stats.loaded && ttfb > -1;
  3310. const bwEstimate = this.getBwEstimate();
  3311. const levels = hls.levels;
  3312. const level = levels[loadingFragForLevel];
  3313. const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  3314. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  3315. if (timeStreaming < 1 && loadedFirstByte) {
  3316. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  3317. }
  3318. const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  3319. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  3320. const ttfbSeconds = ttfbEstimate / 1000;
  3321. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  3322. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  3323. if (fragLoadedDelay <= bufferStarvationDelay) {
  3324. return;
  3325. }
  3326. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  3327. const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  3328. const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;
  3329. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  3330. let nextLoadLevel;
  3331. // Iterate through lower level and try to find the largest one that avoids rebuffering
  3332. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  3333. // compute time to load next fragment at lower level
  3334. // 8 = bits per byte (bps/Bps)
  3335. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  3336. const requiresLevelLoad = !levels[nextLoadLevel].details || live;
  3337. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  3338. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  3339. break;
  3340. }
  3341. }
  3342. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  3343. // to load the current one
  3344. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  3345. return;
  3346. }
  3347. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  3348. if (fragLevelNextLoadedDelay > duration * 10) {
  3349. return;
  3350. }
  3351. if (loadedFirstByte) {
  3352. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  3353. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3354. } else {
  3355. // If there has been no loading progress, sample TTFB
  3356. this.bwEstimator.sampleTTFB(timeLoading);
  3357. }
  3358. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  3359. if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  3360. this.resetEstimator(nextLoadLevelBitrate);
  3361. }
  3362. const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3363. if (bestSwitchLevel > -1) {
  3364. nextLoadLevel = bestSwitchLevel;
  3365. }
  3366. this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${loadingFragForLevel} is loading too slowly;
  3367. Fragment duration: ${frag.duration.toFixed(3)}
  3368. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  3369. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  3370. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  3371. TTFB estimate: ${ttfb | 0} ms
  3372. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps
  3373. New BW estimate: ${this.getBwEstimate() | 0} bps
  3374. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  3375. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  3376. this.clearTimer();
  3377. const abortAndSwitch = () => {
  3378. // Are nextLoadLevel details available or is stream-controller still in "WAITING_LEVEL" state?
  3379. this.clearTimer();
  3380. if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  3381. const bufferStarvationDelay = this.getStarvationDelay();
  3382. this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? 'and switching down' : ''}
  3383. Fragment duration: ${frag.duration.toFixed(3)} s
  3384. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s`);
  3385. frag.abortRequests();
  3386. this.fragCurrent = this.partCurrent = null;
  3387. if (nextLoadLevel > minAutoLevel) {
  3388. let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3389. if (lowestSwitchLevel === -1) {
  3390. lowestSwitchLevel = minAutoLevel;
  3391. }
  3392. this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;
  3393. this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);
  3394. }
  3395. }
  3396. };
  3397. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  3398. abortAndSwitch();
  3399. } else {
  3400. this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1000);
  3401. }
  3402. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  3403. frag,
  3404. part,
  3405. stats
  3406. });
  3407. };
  3408. this.hls = _hls;
  3409. this.bwEstimator = this.initEstimator();
  3410. this.registerListeners();
  3411. }
  3412. resetEstimator(abrEwmaDefaultEstimate) {
  3413. if (abrEwmaDefaultEstimate) {
  3414. this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  3415. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  3416. }
  3417. this.firstSelection = -1;
  3418. this.bwEstimator = this.initEstimator();
  3419. }
  3420. initEstimator() {
  3421. const config = this.hls.config;
  3422. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  3423. }
  3424. registerListeners() {
  3425. const {
  3426. hls
  3427. } = this;
  3428. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3429. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3430. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3431. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3432. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3433. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3434. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3435. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3436. hls.on(Events.ERROR, this.onError, this);
  3437. }
  3438. unregisterListeners() {
  3439. const {
  3440. hls
  3441. } = this;
  3442. if (!hls) {
  3443. return;
  3444. }
  3445. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3446. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3447. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3448. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3449. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3450. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3451. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3452. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3453. hls.off(Events.ERROR, this.onError, this);
  3454. }
  3455. destroy() {
  3456. this.unregisterListeners();
  3457. this.clearTimer();
  3458. // @ts-ignore
  3459. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3460. this.fragCurrent = this.partCurrent = null;
  3461. }
  3462. onManifestLoading(event, data) {
  3463. this.lastLoadedFragLevel = -1;
  3464. this.firstSelection = -1;
  3465. this.lastLevelLoadSec = 0;
  3466. this.supportedCache = {};
  3467. this.fragCurrent = this.partCurrent = null;
  3468. this.onLevelsUpdated();
  3469. this.clearTimer();
  3470. }
  3471. onLevelsUpdated() {
  3472. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3473. this.lastLoadedFragLevel = this.fragCurrent.level;
  3474. }
  3475. this._nextAutoLevel = -1;
  3476. this.onMaxAutoLevelUpdated();
  3477. this.codecTiers = null;
  3478. this.audioTracksByGroup = null;
  3479. }
  3480. onMaxAutoLevelUpdated() {
  3481. this.firstSelection = -1;
  3482. this.nextAutoLevelKey = '';
  3483. }
  3484. onFragLoading(event, data) {
  3485. const frag = data.frag;
  3486. if (this.ignoreFragment(frag)) {
  3487. return;
  3488. }
  3489. if (!frag.bitrateTest) {
  3490. var _data$part;
  3491. this.fragCurrent = frag;
  3492. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3493. }
  3494. this.clearTimer();
  3495. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3496. }
  3497. onLevelSwitching(event, data) {
  3498. this.clearTimer();
  3499. }
  3500. onError(event, data) {
  3501. if (data.fatal) {
  3502. return;
  3503. }
  3504. switch (data.details) {
  3505. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3506. case ErrorDetails.BUFFER_APPEND_ERROR:
  3507. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  3508. this.lastLoadedFragLevel = -1;
  3509. this.firstSelection = -1;
  3510. break;
  3511. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3512. {
  3513. const frag = data.frag;
  3514. const {
  3515. fragCurrent,
  3516. partCurrent: part
  3517. } = this;
  3518. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3519. const now = performance.now();
  3520. const stats = part ? part.stats : frag.stats;
  3521. const timeLoading = now - stats.loading.start;
  3522. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3523. const loadedFirstByte = stats.loaded && ttfb > -1;
  3524. if (loadedFirstByte) {
  3525. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3526. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3527. } else {
  3528. this.bwEstimator.sampleTTFB(timeLoading);
  3529. }
  3530. }
  3531. break;
  3532. }
  3533. }
  3534. }
  3535. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3536. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3537. const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3538. return fragLoadSec + playlistLoadSec;
  3539. }
  3540. onLevelLoaded(event, data) {
  3541. const config = this.hls.config;
  3542. const {
  3543. loading
  3544. } = data.stats;
  3545. const timeLoadingMs = loading.end - loading.first;
  3546. if (isFiniteNumber(timeLoadingMs)) {
  3547. this.lastLevelLoadSec = timeLoadingMs / 1000;
  3548. }
  3549. if (data.details.live) {
  3550. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3551. } else {
  3552. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3553. }
  3554. if (this.timer > -1) {
  3555. this._abandonRulesCheck(data.levelInfo);
  3556. }
  3557. }
  3558. onFragLoaded(event, {
  3559. frag,
  3560. part
  3561. }) {
  3562. const stats = part ? part.stats : frag.stats;
  3563. if (frag.type === PlaylistLevelType.MAIN) {
  3564. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3565. }
  3566. if (this.ignoreFragment(frag)) {
  3567. return;
  3568. }
  3569. // stop monitoring bw once frag loaded
  3570. this.clearTimer();
  3571. // reset forced auto level value so that next level will be selected
  3572. if (frag.level === this._nextAutoLevel) {
  3573. this._nextAutoLevel = -1;
  3574. }
  3575. this.firstSelection = -1;
  3576. // compute level average bitrate
  3577. if (this.hls.config.abrMaxWithRealBitrate) {
  3578. const duration = part ? part.duration : frag.duration;
  3579. const level = this.hls.levels[frag.level];
  3580. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3581. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3582. level.loaded = {
  3583. bytes: loadedBytes,
  3584. duration: loadedDuration
  3585. };
  3586. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3587. }
  3588. if (frag.bitrateTest) {
  3589. const fragBufferedData = {
  3590. stats,
  3591. frag,
  3592. part,
  3593. id: frag.type
  3594. };
  3595. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3596. frag.bitrateTest = false;
  3597. } else {
  3598. // store level id after successful fragment load for playback
  3599. this.lastLoadedFragLevel = frag.level;
  3600. }
  3601. }
  3602. onFragBuffered(event, data) {
  3603. const {
  3604. frag,
  3605. part
  3606. } = data;
  3607. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3608. if (stats.aborted) {
  3609. return;
  3610. }
  3611. if (this.ignoreFragment(frag)) {
  3612. return;
  3613. }
  3614. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  3615. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  3616. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  3617. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3618. this.bwEstimator.sample(processingMs, stats.loaded);
  3619. stats.bwEstimate = this.getBwEstimate();
  3620. if (frag.bitrateTest) {
  3621. this.bitrateTestDelay = processingMs / 1000;
  3622. } else {
  3623. this.bitrateTestDelay = 0;
  3624. }
  3625. }
  3626. ignoreFragment(frag) {
  3627. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  3628. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  3629. }
  3630. clearTimer() {
  3631. if (this.timer > -1) {
  3632. self.clearInterval(this.timer);
  3633. this.timer = -1;
  3634. }
  3635. }
  3636. get firstAutoLevel() {
  3637. const {
  3638. maxAutoLevel,
  3639. minAutoLevel
  3640. } = this.hls;
  3641. const bwEstimate = this.getBwEstimate();
  3642. const maxStartDelay = this.hls.config.maxStarvationDelay;
  3643. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3644. if (abrAutoLevel > -1) {
  3645. return abrAutoLevel;
  3646. }
  3647. const firstLevel = this.hls.firstLevel;
  3648. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  3649. this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  3650. return clamped;
  3651. }
  3652. get forcedAutoLevel() {
  3653. if (this.nextAutoLevelKey) {
  3654. return -1;
  3655. }
  3656. return this._nextAutoLevel;
  3657. }
  3658. // return next auto level
  3659. get nextAutoLevel() {
  3660. const forcedAutoLevel = this.forcedAutoLevel;
  3661. const bwEstimator = this.bwEstimator;
  3662. const useEstimate = bwEstimator.canEstimate();
  3663. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  3664. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  3665. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  3666. return forcedAutoLevel;
  3667. }
  3668. // compute next level using ABR logic
  3669. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  3670. // use forced auto level while it hasn't errored more than ABR selection
  3671. if (forcedAutoLevel !== -1) {
  3672. const levels = this.hls.levels;
  3673. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  3674. return forcedAutoLevel;
  3675. }
  3676. }
  3677. // save result until state has changed
  3678. this._nextAutoLevel = nextABRAutoLevel;
  3679. this.nextAutoLevelKey = this.getAutoLevelKey();
  3680. return nextABRAutoLevel;
  3681. }
  3682. getAutoLevelKey() {
  3683. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  3684. }
  3685. getNextABRAutoLevel() {
  3686. const {
  3687. fragCurrent,
  3688. partCurrent,
  3689. hls
  3690. } = this;
  3691. if (hls.levels.length <= 1) {
  3692. return hls.loadLevel;
  3693. }
  3694. const {
  3695. maxAutoLevel,
  3696. config,
  3697. minAutoLevel
  3698. } = hls;
  3699. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3700. const avgbw = this.getBwEstimate();
  3701. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  3702. const bufferStarvationDelay = this.getStarvationDelay();
  3703. let bwFactor = config.abrBandWidthFactor;
  3704. let bwUpFactor = config.abrBandWidthUpFactor;
  3705. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  3706. if (bufferStarvationDelay) {
  3707. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3708. if (_bestLevel >= 0) {
  3709. this.rebufferNotice = -1;
  3710. return _bestLevel;
  3711. }
  3712. }
  3713. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  3714. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3715. if (!bufferStarvationDelay) {
  3716. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  3717. const bitrateTestDelay = this.bitrateTestDelay;
  3718. if (bitrateTestDelay) {
  3719. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  3720. // max video loading delay used in automatic start level selection :
  3721. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  3722. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  3723. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  3724. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3725. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3726. this.info(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);
  3727. // don't use conservative factor on bitrate test
  3728. bwFactor = bwUpFactor = 1;
  3729. }
  3730. }
  3731. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3732. if (this.rebufferNotice !== bestLevel) {
  3733. this.rebufferNotice = bestLevel;
  3734. this.info(`${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);
  3735. }
  3736. if (bestLevel > -1) {
  3737. return bestLevel;
  3738. }
  3739. // If no matching level found, see if min auto level would be a better option
  3740. const minLevel = hls.levels[minAutoLevel];
  3741. const autoLevel = hls.loadLevelObj;
  3742. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  3743. return minAutoLevel;
  3744. }
  3745. // or if bitrate is not lower, continue to use loadLevel
  3746. return hls.loadLevel;
  3747. }
  3748. getStarvationDelay() {
  3749. const hls = this.hls;
  3750. const media = hls.media;
  3751. if (!media) {
  3752. return Infinity;
  3753. }
  3754. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  3755. // if we're playing back at the normal rate.
  3756. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  3757. const bufferInfo = hls.mainForwardBufferInfo;
  3758. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3759. }
  3760. getBwEstimate() {
  3761. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3762. }
  3763. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3764. var _this$hls$latestLevel;
  3765. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3766. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  3767. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3768. const {
  3769. fragCurrent,
  3770. partCurrent
  3771. } = this;
  3772. const {
  3773. levels,
  3774. allAudioTracks,
  3775. loadLevel,
  3776. config
  3777. } = this.hls;
  3778. if (levels.length === 1) {
  3779. return 0;
  3780. }
  3781. const level = levels[selectionBaseLevel];
  3782. const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3783. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3784. let currentCodecSet;
  3785. let currentVideoRange = 'SDR';
  3786. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3787. const {
  3788. audioPreference,
  3789. videoPreference
  3790. } = config;
  3791. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3792. let minStartIndex = -1;
  3793. if (firstSelection) {
  3794. if (this.firstSelection !== -1) {
  3795. return this.firstSelection;
  3796. }
  3797. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3798. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3799. const {
  3800. codecSet,
  3801. videoRanges,
  3802. minFramerate,
  3803. minBitrate,
  3804. minIndex,
  3805. preferHDR
  3806. } = startTier;
  3807. minStartIndex = minIndex;
  3808. currentCodecSet = codecSet;
  3809. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3810. currentFrameRate = minFramerate;
  3811. currentBw = Math.max(currentBw, minBitrate);
  3812. this.log(`picked start tier ${stringify(startTier)}`);
  3813. } else {
  3814. currentCodecSet = level == null ? void 0 : level.codecSet;
  3815. currentVideoRange = level == null ? void 0 : level.videoRange;
  3816. }
  3817. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3818. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  3819. const levelsSkipped = [];
  3820. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  3821. var _levelInfo$supportedR, _levelInfo$supportedR2;
  3822. const levelInfo = levels[i];
  3823. const upSwitch = i > selectionBaseLevel;
  3824. if (!levelInfo) {
  3825. continue;
  3826. }
  3827. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  3828. const mediaCapabilities = navigator.mediaCapabilities;
  3829. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === 'function' && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  3830. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, this.supportedCache);
  3831. levelInfo.supportedPromise.then(decodingInfo => {
  3832. if (!this.hls) {
  3833. return;
  3834. }
  3835. levelInfo.supportedResult = decodingInfo;
  3836. const levels = this.hls.levels;
  3837. const index = levels.indexOf(levelInfo);
  3838. if (decodingInfo.error) {
  3839. this.warn(`MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${stringify(decodingInfo)}`);
  3840. } else if (!decodingInfo.supported) {
  3841. this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);
  3842. if (index > -1 && levels.length > 1) {
  3843. this.log(`Removing unsupported level ${index}`);
  3844. this.hls.removeLevel(index);
  3845. if (this.hls.loadLevel === -1) {
  3846. this.hls.nextLoadLevel = 0;
  3847. }
  3848. }
  3849. } else if (decodingInfo.decodingInfoResults.some(info => info.smooth === false || info.powerEfficient === false)) {
  3850. this.log(`MediaCapabilities decodingInfo for level ${index} not smooth or powerEfficient: ${stringify(decodingInfo)}`);
  3851. }
  3852. });
  3853. } else {
  3854. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  3855. }
  3856. }
  3857. // skip candidates which change codec-family or video-range,
  3858. // and which decrease or increase frame-rate for up and down-switch respectfully
  3859. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some(info => info.smooth === false)) {
  3860. if (!firstSelection || i !== minStartIndex) {
  3861. levelsSkipped.push(i);
  3862. continue;
  3863. }
  3864. }
  3865. const levelDetails = levelInfo.details;
  3866. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3867. let adjustedbw;
  3868. // follow algorithm captured from stagefright :
  3869. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  3870. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  3871. // consider only 80% of the available bandwidth, but if we are switching up,
  3872. // be even more conservative (70%) to avoid overestimating and immediately
  3873. // switching back.
  3874. if (!upSwitch) {
  3875. adjustedbw = bwFactor * currentBw;
  3876. } else {
  3877. adjustedbw = bwUpFactor * currentBw;
  3878. }
  3879. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  3880. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3881. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  3882. const canSwitchWithinTolerance =
  3883. // if adjusted bw is greater than level bitrate AND
  3884. adjustedbw >= bitrate && (
  3885. // no level change, or new level has no error history
  3886. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  3887. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  3888. // 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 ...
  3889. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  3890. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  3891. if (canSwitchWithinTolerance) {
  3892. const forcedAutoLevel = this.forcedAutoLevel;
  3893. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3894. if (levelsSkipped.length) {
  3895. this.trace(`Skipped level(s) ${levelsSkipped.join(',')} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${currentCodecSet}" ${currentVideoRange}`);
  3896. }
  3897. this.info(`switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${levelInfo.codecSet} videoRange:${levelInfo.videoRange} hls.loadLevel:${loadLevel}`);
  3898. }
  3899. if (firstSelection) {
  3900. this.firstSelection = i;
  3901. }
  3902. // as we are looping from highest to lowest, this will return the best achievable quality level
  3903. return i;
  3904. }
  3905. }
  3906. // not enough time budget even with quality level 0 ... rebuffering might happen
  3907. return -1;
  3908. }
  3909. set nextAutoLevel(nextLevel) {
  3910. const value = this.deriveNextAutoLevel(nextLevel);
  3911. if (this._nextAutoLevel !== value) {
  3912. this.nextAutoLevelKey = '';
  3913. this._nextAutoLevel = value;
  3914. }
  3915. }
  3916. deriveNextAutoLevel(nextLevel) {
  3917. const {
  3918. maxAutoLevel,
  3919. minAutoLevel
  3920. } = this.hls;
  3921. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3922. }
  3923. }
  3924. const BinarySearch = {
  3925. /**
  3926. * Searches for an item in an array which matches a certain condition.
  3927. * This requires the condition to only match one item in the array,
  3928. * and for the array to be ordered.
  3929. *
  3930. * @param list The array to search.
  3931. * @param comparisonFn
  3932. * Called and provided a candidate item as the first argument.
  3933. * Should return:
  3934. * > -1 if the item should be located at a lower index than the provided item.
  3935. * > 1 if the item should be located at a higher index than the provided item.
  3936. * > 0 if the item is the item you're looking for.
  3937. *
  3938. * @returns the object if found, otherwise returns null
  3939. */
  3940. search: function (list, comparisonFn) {
  3941. let minIndex = 0;
  3942. let maxIndex = list.length - 1;
  3943. let currentIndex = null;
  3944. let currentElement = null;
  3945. while (minIndex <= maxIndex) {
  3946. currentIndex = (minIndex + maxIndex) / 2 | 0;
  3947. currentElement = list[currentIndex];
  3948. const comparisonResult = comparisonFn(currentElement);
  3949. if (comparisonResult > 0) {
  3950. minIndex = currentIndex + 1;
  3951. } else if (comparisonResult < 0) {
  3952. maxIndex = currentIndex - 1;
  3953. } else {
  3954. return currentElement;
  3955. }
  3956. }
  3957. return null;
  3958. }
  3959. };
  3960. /**
  3961. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  3962. * @param fragments - The array of candidate fragments
  3963. * @param PDTValue - The PDT value which must be exceeded
  3964. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3965. */
  3966. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3967. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  3968. return null;
  3969. }
  3970. // if less than start
  3971. const startPDT = fragments[0].programDateTime;
  3972. if (PDTValue < (startPDT || 0)) {
  3973. return null;
  3974. }
  3975. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3976. if (PDTValue >= (endPDT || 0)) {
  3977. return null;
  3978. }
  3979. for (let seg = 0; seg < fragments.length; ++seg) {
  3980. const frag = fragments[seg];
  3981. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3982. return frag;
  3983. }
  3984. }
  3985. return null;
  3986. }
  3987. /**
  3988. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  3989. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  3990. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  3991. * @param fragPrevious - The last frag successfully appended
  3992. * @param fragments - The array of candidate fragments
  3993. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  3994. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3995. * @returns a matching fragment or null
  3996. */
  3997. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {
  3998. let fragNext = null;
  3999. if (fragPrevious) {
  4000. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  4001. // check for buffer-end rounding error
  4002. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  4003. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  4004. bufferEnd += 0.0000015;
  4005. }
  4006. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  4007. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  4008. }
  4009. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  4010. fragNext = fragments[0];
  4011. }
  4012. // Prefer the next fragment if it's within tolerance
  4013. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  4014. return fragNext;
  4015. }
  4016. // We might be seeking past the tolerance so find the best match
  4017. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  4018. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  4019. return foundFragment;
  4020. }
  4021. // If no match was found return the next fragment after fragPrevious, or null
  4022. return fragNext;
  4023. }
  4024. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  4025. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  4026. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  4027. if (tag[0] === 'INF') {
  4028. duration += parseFloat(tag[1]);
  4029. }
  4030. return duration;
  4031. }, nextFragLookupTolerance);
  4032. return fragNext.start <= firstDuration;
  4033. }
  4034. return false;
  4035. }
  4036. /**
  4037. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  4038. * @param candidate - The fragment to test
  4039. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  4040. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4041. * @returns 0 if it matches, 1 if too low, -1 if too high
  4042. */
  4043. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  4044. // eagerly accept an accurate match (no tolerance)
  4045. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  4046. return 0;
  4047. }
  4048. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  4049. // this is to cope with situations like
  4050. // bufferEnd = 9.991
  4051. // frag[Ø] : [0,10]
  4052. // frag[1] : [10,20]
  4053. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  4054. // frag start frag start+duration
  4055. // |-----------------------------|
  4056. // <---> <--->
  4057. // ...--------><-----------------------------><---------....
  4058. // previous frag matching fragment next frag
  4059. // return -1 return 0 return 1
  4060. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  4061. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  4062. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  4063. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  4064. return 1;
  4065. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  4066. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  4067. return -1;
  4068. }
  4069. return 0;
  4070. }
  4071. /**
  4072. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  4073. * This function tests the candidate's program date time values, as represented in Unix time
  4074. * @param candidate - The fragment to test
  4075. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  4076. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4077. * @returns true if contiguous, false otherwise
  4078. */
  4079. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  4080. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  4081. // endProgramDateTime can be null, default to zero
  4082. const endProgramDateTime = candidate.endProgramDateTime || 0;
  4083. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  4084. }
  4085. function findNearestWithCC(details, cc, pos) {
  4086. if (details) {
  4087. if (details.startCC <= cc && details.endCC >= cc) {
  4088. let fragments = details.fragments;
  4089. const {
  4090. fragmentHint
  4091. } = details;
  4092. if (fragmentHint) {
  4093. fragments = fragments.concat(fragmentHint);
  4094. }
  4095. let closest;
  4096. BinarySearch.search(fragments, candidate => {
  4097. if (candidate.cc < cc) {
  4098. return 1;
  4099. }
  4100. if (candidate.cc > cc) {
  4101. return -1;
  4102. }
  4103. closest = candidate;
  4104. if (candidate.end <= pos) {
  4105. return 1;
  4106. }
  4107. if (candidate.start > pos) {
  4108. return -1;
  4109. }
  4110. return 0;
  4111. });
  4112. return closest || null;
  4113. }
  4114. }
  4115. return null;
  4116. }
  4117. function isTimeoutError(error) {
  4118. switch (error.details) {
  4119. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4120. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4121. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4122. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  4123. return true;
  4124. }
  4125. return false;
  4126. }
  4127. function getRetryConfig(loadPolicy, error) {
  4128. const isTimeout = isTimeoutError(error);
  4129. return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];
  4130. }
  4131. function getRetryDelay(retryConfig, retryCount) {
  4132. // exponential backoff capped to max retry delay
  4133. const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  4134. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  4135. }
  4136. function getLoaderConfigWithoutReties(loderConfig) {
  4137. return _objectSpread2(_objectSpread2({}, loderConfig), {
  4138. errorRetry: null,
  4139. timeoutRetry: null
  4140. });
  4141. }
  4142. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  4143. if (!retryConfig) {
  4144. return false;
  4145. }
  4146. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  4147. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  4148. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  4149. }
  4150. function retryForHttpStatus(httpStatus) {
  4151. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  4152. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  4153. }
  4154. var NetworkErrorAction = {
  4155. DoNothing: 0,
  4156. SendEndCallback: 1,
  4157. SendAlternateToPenaltyBox: 2,
  4158. RemoveAlternatePermanently: 3,
  4159. InsertDiscontinuity: 4,
  4160. RetryRequest: 5
  4161. };
  4162. var ErrorActionFlags = {
  4163. None: 0,
  4164. MoveAllAlternatesMatchingHost: 1,
  4165. MoveAllAlternatesMatchingHDCP: 2,
  4166. SwitchToSDR: 4
  4167. };
  4168. class ErrorController extends Logger {
  4169. constructor(hls) {
  4170. super('error-controller', hls.logger);
  4171. this.hls = void 0;
  4172. this.playlistError = 0;
  4173. this.penalizedRenditions = {};
  4174. this.hls = hls;
  4175. this.registerListeners();
  4176. }
  4177. registerListeners() {
  4178. const hls = this.hls;
  4179. hls.on(Events.ERROR, this.onError, this);
  4180. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4181. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4182. }
  4183. unregisterListeners() {
  4184. const hls = this.hls;
  4185. if (!hls) {
  4186. return;
  4187. }
  4188. hls.off(Events.ERROR, this.onError, this);
  4189. hls.off(Events.ERROR, this.onErrorOut, this);
  4190. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4191. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4192. }
  4193. destroy() {
  4194. this.unregisterListeners();
  4195. // @ts-ignore
  4196. this.hls = null;
  4197. this.penalizedRenditions = {};
  4198. }
  4199. startLoad(startPosition) {}
  4200. stopLoad() {
  4201. this.playlistError = 0;
  4202. }
  4203. getVariantLevelIndex(frag) {
  4204. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  4205. }
  4206. onManifestLoading() {
  4207. this.playlistError = 0;
  4208. this.penalizedRenditions = {};
  4209. }
  4210. onLevelUpdated() {
  4211. this.playlistError = 0;
  4212. }
  4213. onError(event, data) {
  4214. var _data$frag;
  4215. if (data.fatal) {
  4216. return;
  4217. }
  4218. const hls = this.hls;
  4219. const context = data.context;
  4220. switch (data.details) {
  4221. case ErrorDetails.FRAG_LOAD_ERROR:
  4222. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4223. case ErrorDetails.KEY_LOAD_ERROR:
  4224. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4225. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4226. return;
  4227. case ErrorDetails.FRAG_PARSING_ERROR:
  4228. // ignore empty segment errors marked as gap
  4229. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  4230. data.errorAction = createDoNothingErrorAction();
  4231. return;
  4232. }
  4233. // falls through
  4234. case ErrorDetails.FRAG_GAP:
  4235. case ErrorDetails.FRAG_DECRYPT_ERROR:
  4236. {
  4237. // Switch level if possible, otherwise allow retry count to reach max error retries
  4238. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4239. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4240. return;
  4241. }
  4242. case ErrorDetails.LEVEL_EMPTY_ERROR:
  4243. case ErrorDetails.LEVEL_PARSING_ERROR:
  4244. {
  4245. var _data$context, _data$context$levelDe;
  4246. // Only retry when empty and live
  4247. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  4248. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  4249. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  4250. } else {
  4251. // Escalate to fatal if not retrying or switching
  4252. data.levelRetry = false;
  4253. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4254. }
  4255. }
  4256. return;
  4257. case ErrorDetails.LEVEL_LOAD_ERROR:
  4258. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4259. if (typeof (context == null ? void 0 : context.level) === 'number') {
  4260. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  4261. }
  4262. return;
  4263. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  4264. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  4265. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  4266. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  4267. if (context) {
  4268. const level = hls.loadLevelObj;
  4269. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  4270. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  4271. // otherwise allow playlist retry count to reach max error retries
  4272. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  4273. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4274. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  4275. return;
  4276. }
  4277. }
  4278. return;
  4279. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  4280. {
  4281. const level = hls.loadLevelObj;
  4282. const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];
  4283. if (restrictedHdcpLevel) {
  4284. data.errorAction = {
  4285. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4286. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  4287. hdcpLevel: restrictedHdcpLevel
  4288. };
  4289. } else {
  4290. this.keySystemError(data);
  4291. }
  4292. }
  4293. return;
  4294. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  4295. case ErrorDetails.REMUX_ALLOC_ERROR:
  4296. case ErrorDetails.BUFFER_APPEND_ERROR:
  4297. // Buffer-controller can set errorAction when append errors can be ignored or resolved locally
  4298. if (!data.errorAction) {
  4299. var _data$level;
  4300. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  4301. }
  4302. return;
  4303. case ErrorDetails.INTERNAL_EXCEPTION:
  4304. case ErrorDetails.BUFFER_APPENDING_ERROR:
  4305. case ErrorDetails.BUFFER_FULL_ERROR:
  4306. case ErrorDetails.LEVEL_SWITCH_ERROR:
  4307. case ErrorDetails.BUFFER_STALLED_ERROR:
  4308. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  4309. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  4310. data.errorAction = createDoNothingErrorAction();
  4311. return;
  4312. }
  4313. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  4314. this.keySystemError(data);
  4315. }
  4316. }
  4317. keySystemError(data) {
  4318. const levelIndex = this.getVariantLevelIndex(data.frag);
  4319. // Do not retry level. Escalate to fatal if switching levels fails.
  4320. data.levelRetry = false;
  4321. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4322. }
  4323. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  4324. const hls = this.hls;
  4325. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  4326. const retryCount = this.playlistError++;
  4327. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  4328. if (retry) {
  4329. return {
  4330. action: NetworkErrorAction.RetryRequest,
  4331. flags: ErrorActionFlags.None,
  4332. retryConfig,
  4333. retryCount
  4334. };
  4335. }
  4336. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  4337. if (retryConfig) {
  4338. errorAction.retryConfig = retryConfig;
  4339. errorAction.retryCount = retryCount;
  4340. }
  4341. return errorAction;
  4342. }
  4343. getFragRetryOrSwitchAction(data) {
  4344. const hls = this.hls;
  4345. // Share fragment error count accross media options (main, audio, subs)
  4346. // This allows for level based rendition switching when media option assets fail
  4347. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  4348. const level = hls.levels[variantLevelIndex];
  4349. const {
  4350. fragLoadPolicy,
  4351. keyLoadPolicy
  4352. } = hls.config;
  4353. const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  4354. const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);
  4355. // Switch levels when out of retried or level index out of bounds
  4356. if (level) {
  4357. if (data.details !== ErrorDetails.FRAG_GAP) {
  4358. level.fragmentError++;
  4359. }
  4360. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  4361. if (retry) {
  4362. return {
  4363. action: NetworkErrorAction.RetryRequest,
  4364. flags: ErrorActionFlags.None,
  4365. retryConfig,
  4366. retryCount: fragmentErrors
  4367. };
  4368. }
  4369. }
  4370. // Reach max retry count, or Missing level reference
  4371. // Switch to valid index
  4372. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  4373. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  4374. if (retryConfig) {
  4375. errorAction.retryConfig = retryConfig;
  4376. errorAction.retryCount = fragmentErrors;
  4377. }
  4378. return errorAction;
  4379. }
  4380. getLevelSwitchAction(data, levelIndex) {
  4381. const hls = this.hls;
  4382. if (levelIndex === null || levelIndex === undefined) {
  4383. levelIndex = hls.loadLevel;
  4384. }
  4385. const level = this.hls.levels[levelIndex];
  4386. if (level) {
  4387. var _data$frag2, _data$context2;
  4388. const errorDetails = data.details;
  4389. level.loadError++;
  4390. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  4391. level.fragmentError++;
  4392. }
  4393. // Search for next level to retry
  4394. let nextLevel = -1;
  4395. const {
  4396. levels,
  4397. loadLevel,
  4398. minAutoLevel,
  4399. maxAutoLevel
  4400. } = hls;
  4401. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  4402. hls.loadLevel = -1;
  4403. }
  4404. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  4405. // Find alternate audio codec if available on audio codec error
  4406. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4407. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  4408. audioCodec
  4409. }) => level.audioCodec !== audioCodec);
  4410. // Find alternate video codec if available on video codec error
  4411. const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4412. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  4413. codecSet,
  4414. audioCodec
  4415. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  4416. const {
  4417. type: playlistErrorType,
  4418. groupId: playlistErrorGroupId
  4419. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  4420. for (let i = levels.length; i--;) {
  4421. const candidate = (i + loadLevel) % levels.length;
  4422. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  4423. var _level$audioGroups, _level$subtitleGroups;
  4424. const levelCandidate = levels[candidate];
  4425. // Skip level switch if GAP tag is found in next level at same position
  4426. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  4427. const levelDetails = levels[candidate].details;
  4428. if (levelDetails) {
  4429. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  4430. if (fragCandidate != null && fragCandidate.gap) {
  4431. continue;
  4432. }
  4433. }
  4434. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  4435. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  4436. continue;
  4437. } 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) {
  4438. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  4439. continue;
  4440. }
  4441. nextLevel = candidate;
  4442. break;
  4443. }
  4444. }
  4445. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  4446. data.levelRetry = true;
  4447. this.playlistError = 0;
  4448. return {
  4449. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4450. flags: ErrorActionFlags.None,
  4451. nextAutoLevel: nextLevel
  4452. };
  4453. }
  4454. }
  4455. // No levels to switch / Manual level selection / Level not found
  4456. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  4457. return {
  4458. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4459. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  4460. };
  4461. }
  4462. onErrorOut(event, data) {
  4463. var _data$errorAction;
  4464. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  4465. case NetworkErrorAction.DoNothing:
  4466. break;
  4467. case NetworkErrorAction.SendAlternateToPenaltyBox:
  4468. this.sendAlternateToPenaltyBox(data);
  4469. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  4470. data.fatal = true;
  4471. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  4472. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  4473. this.hls.recoverMediaError();
  4474. }
  4475. break;
  4476. case NetworkErrorAction.RetryRequest:
  4477. // handled by stream and playlist/level controllers
  4478. break;
  4479. }
  4480. if (data.fatal) {
  4481. this.hls.stopLoad();
  4482. return;
  4483. }
  4484. }
  4485. sendAlternateToPenaltyBox(data) {
  4486. const hls = this.hls;
  4487. const errorAction = data.errorAction;
  4488. if (!errorAction) {
  4489. return;
  4490. }
  4491. const {
  4492. flags,
  4493. hdcpLevel,
  4494. nextAutoLevel
  4495. } = errorAction;
  4496. switch (flags) {
  4497. case ErrorActionFlags.None:
  4498. this.switchLevel(data, nextAutoLevel);
  4499. break;
  4500. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  4501. if (hdcpLevel) {
  4502. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  4503. errorAction.resolved = true;
  4504. }
  4505. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  4506. break;
  4507. }
  4508. // If not resolved by previous actions try to switch to next level
  4509. if (!errorAction.resolved) {
  4510. this.switchLevel(data, nextAutoLevel);
  4511. }
  4512. }
  4513. switchLevel(data, levelIndex) {
  4514. if (levelIndex !== undefined && data.errorAction) {
  4515. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  4516. this.hls.nextAutoLevel = levelIndex;
  4517. data.errorAction.resolved = true;
  4518. // Stream controller is responsible for this but won't switch on false start
  4519. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  4520. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== 'audiovideo') {
  4521. const codec = getCodecsForMimeType(data.mimeType);
  4522. const levels = this.hls.levels;
  4523. for (let i = levels.length; i--;) {
  4524. if (levels[i][`${data.sourceBufferName}Codec`] === codec) {
  4525. this.hls.removeLevel(i);
  4526. }
  4527. }
  4528. }
  4529. }
  4530. }
  4531. }
  4532. function createDoNothingErrorAction(resolved) {
  4533. const errorAction = {
  4534. action: NetworkErrorAction.DoNothing,
  4535. flags: ErrorActionFlags.None
  4536. };
  4537. if (resolved) {
  4538. errorAction.resolved = true;
  4539. }
  4540. return errorAction;
  4541. }
  4542. var FragmentState = {
  4543. NOT_LOADED: "NOT_LOADED",
  4544. APPENDING: "APPENDING",
  4545. PARTIAL: "PARTIAL",
  4546. OK: "OK"
  4547. };
  4548. class FragmentTracker {
  4549. constructor(hls) {
  4550. this.activePartLists = Object.create(null);
  4551. this.endListFragments = Object.create(null);
  4552. this.fragments = Object.create(null);
  4553. this.timeRanges = Object.create(null);
  4554. this.bufferPadding = 0.2;
  4555. this.hls = void 0;
  4556. this.hasGaps = false;
  4557. this.hls = hls;
  4558. this._registerListeners();
  4559. }
  4560. _registerListeners() {
  4561. const {
  4562. hls
  4563. } = this;
  4564. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4565. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4566. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4567. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  4568. }
  4569. _unregisterListeners() {
  4570. const {
  4571. hls
  4572. } = this;
  4573. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4574. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  4575. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  4576. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  4577. }
  4578. destroy() {
  4579. this._unregisterListeners();
  4580. // @ts-ignore
  4581. this.fragments =
  4582. // @ts-ignore
  4583. this.activePartLists =
  4584. // @ts-ignore
  4585. this.endListFragments = this.timeRanges = null;
  4586. }
  4587. /**
  4588. * Return a Fragment or Part with an appended range that matches the position and levelType
  4589. * Otherwise, return null
  4590. */
  4591. getAppendedFrag(position, levelType) {
  4592. const activeParts = this.activePartLists[levelType];
  4593. if (activeParts) {
  4594. for (let i = activeParts.length; i--;) {
  4595. const activePart = activeParts[i];
  4596. if (!activePart) {
  4597. break;
  4598. }
  4599. const appendedPTS = activePart.end;
  4600. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  4601. return activePart;
  4602. }
  4603. }
  4604. }
  4605. return this.getBufferedFrag(position, levelType);
  4606. }
  4607. /**
  4608. * Return a buffered Fragment that matches the position and levelType.
  4609. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  4610. * If not found any Fragment, return null
  4611. */
  4612. getBufferedFrag(position, levelType) {
  4613. return this.getFragAtPos(position, levelType, true);
  4614. }
  4615. getFragAtPos(position, levelType, buffered) {
  4616. const {
  4617. fragments
  4618. } = this;
  4619. const keys = Object.keys(fragments);
  4620. for (let i = keys.length; i--;) {
  4621. const fragmentEntity = fragments[keys[i]];
  4622. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  4623. const frag = fragmentEntity.body;
  4624. if (frag.start <= position && position <= frag.end) {
  4625. return frag;
  4626. }
  4627. }
  4628. }
  4629. return null;
  4630. }
  4631. /**
  4632. * Partial fragments effected by coded frame eviction will be removed
  4633. * The browser will unload parts of the buffer to free up memory for new buffer data
  4634. * 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)
  4635. */
  4636. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  4637. if (this.timeRanges) {
  4638. this.timeRanges[elementaryStream] = timeRange;
  4639. }
  4640. // Check if any flagged fragments have been unloaded
  4641. // excluding anything newer than appendedPartSn
  4642. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  4643. Object.keys(this.fragments).forEach(key => {
  4644. const fragmentEntity = this.fragments[key];
  4645. if (!fragmentEntity) {
  4646. return;
  4647. }
  4648. if (appendedPartSn >= fragmentEntity.body.sn) {
  4649. return;
  4650. }
  4651. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  4652. if (fragmentEntity.body.type === playlistType) {
  4653. this.removeFragment(fragmentEntity.body);
  4654. }
  4655. return;
  4656. }
  4657. const esData = fragmentEntity.range[elementaryStream];
  4658. if (!esData) {
  4659. return;
  4660. }
  4661. if (esData.time.length === 0) {
  4662. this.removeFragment(fragmentEntity.body);
  4663. return;
  4664. }
  4665. esData.time.some(time => {
  4666. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  4667. if (isNotBuffered) {
  4668. // Unregister partial fragment as it needs to load again to be reused
  4669. this.removeFragment(fragmentEntity.body);
  4670. }
  4671. return isNotBuffered;
  4672. });
  4673. });
  4674. }
  4675. /**
  4676. * Checks if the fragment passed in is loaded in the buffer properly
  4677. * Partially loaded fragments will be registered as a partial fragment
  4678. */
  4679. detectPartialFragments(data) {
  4680. const timeRanges = this.timeRanges;
  4681. if (!timeRanges || data.frag.sn === 'initSegment') {
  4682. return;
  4683. }
  4684. const frag = data.frag;
  4685. const fragKey = getFragmentKey(frag);
  4686. const fragmentEntity = this.fragments[fragKey];
  4687. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  4688. return;
  4689. }
  4690. const isFragHint = !frag.relurl;
  4691. Object.keys(timeRanges).forEach(elementaryStream => {
  4692. const streamInfo = frag.elementaryStreams[elementaryStream];
  4693. if (!streamInfo) {
  4694. return;
  4695. }
  4696. const timeRange = timeRanges[elementaryStream];
  4697. const partial = isFragHint || streamInfo.partial === true;
  4698. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);
  4699. });
  4700. fragmentEntity.loaded = null;
  4701. if (Object.keys(fragmentEntity.range).length) {
  4702. fragmentEntity.buffered = true;
  4703. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  4704. if (endList) {
  4705. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  4706. }
  4707. if (!isPartial(fragmentEntity)) {
  4708. // Remove older fragment parts from lookup after frag is tracked as buffered
  4709. this.removeParts(frag.sn - 1, frag.type);
  4710. }
  4711. } else {
  4712. // remove fragment if nothing was appended
  4713. this.removeFragment(fragmentEntity.body);
  4714. }
  4715. }
  4716. removeParts(snToKeep, levelType) {
  4717. const activeParts = this.activePartLists[levelType];
  4718. if (!activeParts) {
  4719. return;
  4720. }
  4721. this.activePartLists[levelType] = filterParts(activeParts, part => part.fragment.sn >= snToKeep);
  4722. }
  4723. fragBuffered(frag, force) {
  4724. const fragKey = getFragmentKey(frag);
  4725. let fragmentEntity = this.fragments[fragKey];
  4726. if (!fragmentEntity && force) {
  4727. fragmentEntity = this.fragments[fragKey] = {
  4728. body: frag,
  4729. appendedPTS: null,
  4730. loaded: null,
  4731. buffered: false,
  4732. range: Object.create(null)
  4733. };
  4734. if (frag.gap) {
  4735. this.hasGaps = true;
  4736. }
  4737. }
  4738. if (fragmentEntity) {
  4739. fragmentEntity.loaded = null;
  4740. fragmentEntity.buffered = true;
  4741. }
  4742. }
  4743. getBufferedTimes(fragment, part, partial, timeRange) {
  4744. const buffered = {
  4745. time: [],
  4746. partial
  4747. };
  4748. const startPTS = fragment.start;
  4749. const endPTS = fragment.end;
  4750. const minEndPTS = fragment.minEndPTS || endPTS;
  4751. const maxStartPTS = fragment.maxStartPTS || startPTS;
  4752. for (let i = 0; i < timeRange.length; i++) {
  4753. const startTime = timeRange.start(i) - this.bufferPadding;
  4754. const endTime = timeRange.end(i) + this.bufferPadding;
  4755. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  4756. // Fragment is entirely contained in buffer
  4757. // No need to check the other timeRange times since it's completely playable
  4758. buffered.time.push({
  4759. startPTS: Math.max(startPTS, timeRange.start(i)),
  4760. endPTS: Math.min(endPTS, timeRange.end(i))
  4761. });
  4762. break;
  4763. } else if (startPTS < endTime && endPTS > startTime) {
  4764. const start = Math.max(startPTS, timeRange.start(i));
  4765. const end = Math.min(endPTS, timeRange.end(i));
  4766. if (end > start) {
  4767. buffered.partial = true;
  4768. // Check for intersection with buffer
  4769. // Get playable sections of the fragment
  4770. buffered.time.push({
  4771. startPTS: start,
  4772. endPTS: end
  4773. });
  4774. }
  4775. } else if (endPTS <= startTime) {
  4776. // No need to check the rest of the timeRange as it is in order
  4777. break;
  4778. }
  4779. }
  4780. return buffered;
  4781. }
  4782. /**
  4783. * Gets the partial fragment for a certain time
  4784. */
  4785. getPartialFragment(time) {
  4786. let bestFragment = null;
  4787. let timePadding;
  4788. let startTime;
  4789. let endTime;
  4790. let bestOverlap = 0;
  4791. const {
  4792. bufferPadding,
  4793. fragments
  4794. } = this;
  4795. Object.keys(fragments).forEach(key => {
  4796. const fragmentEntity = fragments[key];
  4797. if (!fragmentEntity) {
  4798. return;
  4799. }
  4800. if (isPartial(fragmentEntity)) {
  4801. startTime = fragmentEntity.body.start - bufferPadding;
  4802. endTime = fragmentEntity.body.end + bufferPadding;
  4803. if (time >= startTime && time <= endTime) {
  4804. // Use the fragment that has the most padding from start and end time
  4805. timePadding = Math.min(time - startTime, endTime - time);
  4806. if (bestOverlap <= timePadding) {
  4807. bestFragment = fragmentEntity.body;
  4808. bestOverlap = timePadding;
  4809. }
  4810. }
  4811. }
  4812. });
  4813. return bestFragment;
  4814. }
  4815. isEndListAppended(type) {
  4816. const lastFragmentEntity = this.endListFragments[type];
  4817. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  4818. }
  4819. getState(fragment) {
  4820. const fragKey = getFragmentKey(fragment);
  4821. const fragmentEntity = this.fragments[fragKey];
  4822. if (fragmentEntity) {
  4823. if (!fragmentEntity.buffered) {
  4824. return FragmentState.APPENDING;
  4825. } else if (isPartial(fragmentEntity)) {
  4826. return FragmentState.PARTIAL;
  4827. } else {
  4828. return FragmentState.OK;
  4829. }
  4830. }
  4831. return FragmentState.NOT_LOADED;
  4832. }
  4833. isTimeBuffered(startPTS, endPTS, timeRange) {
  4834. let startTime;
  4835. let endTime;
  4836. for (let i = 0; i < timeRange.length; i++) {
  4837. startTime = timeRange.start(i) - this.bufferPadding;
  4838. endTime = timeRange.end(i) + this.bufferPadding;
  4839. if (startPTS >= startTime && endPTS <= endTime) {
  4840. return true;
  4841. }
  4842. if (endPTS <= startTime) {
  4843. // No need to check the rest of the timeRange as it is in order
  4844. return false;
  4845. }
  4846. }
  4847. return false;
  4848. }
  4849. onManifestLoading() {
  4850. this.removeAllFragments();
  4851. }
  4852. onFragLoaded(event, data) {
  4853. // don't track initsegment (for which sn is not a number)
  4854. // don't track frags used for bitrateTest, they're irrelevant.
  4855. if (data.frag.sn === 'initSegment' || data.frag.bitrateTest) {
  4856. return;
  4857. }
  4858. const frag = data.frag;
  4859. // Fragment entity `loaded` FragLoadedData is null when loading parts
  4860. const loaded = data.part ? null : data;
  4861. const fragKey = getFragmentKey(frag);
  4862. this.fragments[fragKey] = {
  4863. body: frag,
  4864. appendedPTS: null,
  4865. loaded,
  4866. buffered: false,
  4867. range: Object.create(null)
  4868. };
  4869. }
  4870. onBufferAppended(event, data) {
  4871. const {
  4872. frag,
  4873. part,
  4874. timeRanges,
  4875. type
  4876. } = data;
  4877. if (frag.sn === 'initSegment') {
  4878. return;
  4879. }
  4880. const playlistType = frag.type;
  4881. if (part) {
  4882. let activeParts = this.activePartLists[playlistType];
  4883. if (!activeParts) {
  4884. this.activePartLists[playlistType] = activeParts = [];
  4885. }
  4886. activeParts.push(part);
  4887. }
  4888. // Store the latest timeRanges loaded in the buffer
  4889. this.timeRanges = timeRanges;
  4890. const timeRange = timeRanges[type];
  4891. this.detectEvictedFragments(type, timeRange, playlistType, part);
  4892. }
  4893. onFragBuffered(event, data) {
  4894. this.detectPartialFragments(data);
  4895. }
  4896. hasFragment(fragment) {
  4897. const fragKey = getFragmentKey(fragment);
  4898. return !!this.fragments[fragKey];
  4899. }
  4900. hasFragments(type) {
  4901. const {
  4902. fragments
  4903. } = this;
  4904. const keys = Object.keys(fragments);
  4905. if (!type) {
  4906. return keys.length > 0;
  4907. }
  4908. for (let i = keys.length; i--;) {
  4909. const fragmentEntity = fragments[keys[i]];
  4910. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  4911. return true;
  4912. }
  4913. }
  4914. return false;
  4915. }
  4916. hasParts(type) {
  4917. var _this$activePartLists;
  4918. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  4919. }
  4920. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  4921. if (withGapOnly && !this.hasGaps) {
  4922. return;
  4923. }
  4924. Object.keys(this.fragments).forEach(key => {
  4925. const fragmentEntity = this.fragments[key];
  4926. if (!fragmentEntity) {
  4927. return;
  4928. }
  4929. const frag = fragmentEntity.body;
  4930. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  4931. return;
  4932. }
  4933. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  4934. this.removeFragment(frag);
  4935. }
  4936. });
  4937. }
  4938. removeFragment(fragment) {
  4939. const fragKey = getFragmentKey(fragment);
  4940. fragment.clearElementaryStreamInfo();
  4941. const activeParts = this.activePartLists[fragment.type];
  4942. if (activeParts) {
  4943. const snToRemove = fragment.sn;
  4944. this.activePartLists[fragment.type] = filterParts(activeParts, part => part.fragment.sn !== snToRemove);
  4945. }
  4946. delete this.fragments[fragKey];
  4947. if (fragment.endList) {
  4948. delete this.endListFragments[fragment.type];
  4949. }
  4950. }
  4951. removeAllFragments() {
  4952. var _this$hls, _this$hls$latestLevel;
  4953. this.fragments = Object.create(null);
  4954. this.endListFragments = Object.create(null);
  4955. this.activePartLists = Object.create(null);
  4956. this.hasGaps = false;
  4957. const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  4958. if (partlist) {
  4959. partlist.forEach(part => part.clearElementaryStreamInfo());
  4960. }
  4961. }
  4962. }
  4963. function isPartial(fragmentEntity) {
  4964. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  4965. 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));
  4966. }
  4967. function getFragmentKey(fragment) {
  4968. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  4969. }
  4970. function filterParts(partList, predicate) {
  4971. return partList.filter(part => {
  4972. const keep = predicate(part);
  4973. if (!keep) {
  4974. part.clearElementaryStreamInfo();
  4975. }
  4976. return keep;
  4977. });
  4978. }
  4979. var DecrypterAesMode = {
  4980. cbc: 0,
  4981. ctr: 1
  4982. };
  4983. class AESCrypto {
  4984. constructor(subtle, iv, aesMode) {
  4985. this.subtle = void 0;
  4986. this.aesIV = void 0;
  4987. this.aesMode = void 0;
  4988. this.subtle = subtle;
  4989. this.aesIV = iv;
  4990. this.aesMode = aesMode;
  4991. }
  4992. decrypt(data, key) {
  4993. switch (this.aesMode) {
  4994. case DecrypterAesMode.cbc:
  4995. return this.subtle.decrypt({
  4996. name: 'AES-CBC',
  4997. iv: this.aesIV
  4998. }, key, data);
  4999. case DecrypterAesMode.ctr:
  5000. return this.subtle.decrypt({
  5001. name: 'AES-CTR',
  5002. counter: this.aesIV,
  5003. length: 64
  5004. },
  5005. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  5006. key, data);
  5007. default:
  5008. throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);
  5009. }
  5010. }
  5011. }
  5012. // PKCS7
  5013. function removePadding(array) {
  5014. const outputBytes = array.byteLength;
  5015. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  5016. if (paddingBytes) {
  5017. return array.slice(0, outputBytes - paddingBytes);
  5018. }
  5019. return array;
  5020. }
  5021. class AESDecryptor {
  5022. constructor() {
  5023. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  5024. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5025. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5026. this.sBox = new Uint32Array(256);
  5027. this.invSBox = new Uint32Array(256);
  5028. this.key = new Uint32Array(0);
  5029. this.ksRows = 0;
  5030. this.keySize = 0;
  5031. this.keySchedule = void 0;
  5032. this.invKeySchedule = void 0;
  5033. this.initTable();
  5034. }
  5035. // Using view.getUint32() also swaps the byte order.
  5036. uint8ArrayToUint32Array_(arrayBuffer) {
  5037. const view = new DataView(arrayBuffer);
  5038. const newArray = new Uint32Array(4);
  5039. for (let i = 0; i < 4; i++) {
  5040. newArray[i] = view.getUint32(i * 4);
  5041. }
  5042. return newArray;
  5043. }
  5044. initTable() {
  5045. const sBox = this.sBox;
  5046. const invSBox = this.invSBox;
  5047. const subMix = this.subMix;
  5048. const subMix0 = subMix[0];
  5049. const subMix1 = subMix[1];
  5050. const subMix2 = subMix[2];
  5051. const subMix3 = subMix[3];
  5052. const invSubMix = this.invSubMix;
  5053. const invSubMix0 = invSubMix[0];
  5054. const invSubMix1 = invSubMix[1];
  5055. const invSubMix2 = invSubMix[2];
  5056. const invSubMix3 = invSubMix[3];
  5057. const d = new Uint32Array(256);
  5058. let x = 0;
  5059. let xi = 0;
  5060. let i = 0;
  5061. for (i = 0; i < 256; i++) {
  5062. if (i < 128) {
  5063. d[i] = i << 1;
  5064. } else {
  5065. d[i] = i << 1 ^ 0x11b;
  5066. }
  5067. }
  5068. for (i = 0; i < 256; i++) {
  5069. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  5070. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  5071. sBox[x] = sx;
  5072. invSBox[sx] = x;
  5073. // Compute multiplication
  5074. const x2 = d[x];
  5075. const x4 = d[x2];
  5076. const x8 = d[x4];
  5077. // Compute sub/invSub bytes, mix columns tables
  5078. let t = d[sx] * 0x101 ^ sx * 0x1010100;
  5079. subMix0[x] = t << 24 | t >>> 8;
  5080. subMix1[x] = t << 16 | t >>> 16;
  5081. subMix2[x] = t << 8 | t >>> 24;
  5082. subMix3[x] = t;
  5083. // Compute inv sub bytes, inv mix columns tables
  5084. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  5085. invSubMix0[sx] = t << 24 | t >>> 8;
  5086. invSubMix1[sx] = t << 16 | t >>> 16;
  5087. invSubMix2[sx] = t << 8 | t >>> 24;
  5088. invSubMix3[sx] = t;
  5089. // Compute next counter
  5090. if (!x) {
  5091. x = xi = 1;
  5092. } else {
  5093. x = x2 ^ d[d[d[x8 ^ x2]]];
  5094. xi ^= d[d[xi]];
  5095. }
  5096. }
  5097. }
  5098. expandKey(keyBuffer) {
  5099. // convert keyBuffer to Uint32Array
  5100. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  5101. let sameKey = true;
  5102. let offset = 0;
  5103. while (offset < key.length && sameKey) {
  5104. sameKey = key[offset] === this.key[offset];
  5105. offset++;
  5106. }
  5107. if (sameKey) {
  5108. return;
  5109. }
  5110. this.key = key;
  5111. const keySize = this.keySize = key.length;
  5112. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  5113. throw new Error('Invalid aes key size=' + keySize);
  5114. }
  5115. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  5116. let ksRow;
  5117. let invKsRow;
  5118. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  5119. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  5120. const sbox = this.sBox;
  5121. const rcon = this.rcon;
  5122. const invSubMix = this.invSubMix;
  5123. const invSubMix0 = invSubMix[0];
  5124. const invSubMix1 = invSubMix[1];
  5125. const invSubMix2 = invSubMix[2];
  5126. const invSubMix3 = invSubMix[3];
  5127. let prev;
  5128. let t;
  5129. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  5130. if (ksRow < keySize) {
  5131. prev = keySchedule[ksRow] = key[ksRow];
  5132. continue;
  5133. }
  5134. t = prev;
  5135. if (ksRow % keySize === 0) {
  5136. // Rot word
  5137. t = t << 8 | t >>> 24;
  5138. // Sub word
  5139. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5140. // Mix Rcon
  5141. t ^= rcon[ksRow / keySize | 0] << 24;
  5142. } else if (keySize > 6 && ksRow % keySize === 4) {
  5143. // Sub word
  5144. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5145. }
  5146. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  5147. }
  5148. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  5149. ksRow = ksRows - invKsRow;
  5150. if (invKsRow & 3) {
  5151. t = keySchedule[ksRow];
  5152. } else {
  5153. t = keySchedule[ksRow - 4];
  5154. }
  5155. if (invKsRow < 4 || ksRow <= 4) {
  5156. invKeySchedule[invKsRow] = t;
  5157. } else {
  5158. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  5159. }
  5160. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  5161. }
  5162. }
  5163. // Adding this as a method greatly improves performance.
  5164. networkToHostOrderSwap(word) {
  5165. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  5166. }
  5167. decrypt(inputArrayBuffer, offset, aesIV) {
  5168. const nRounds = this.keySize + 6;
  5169. const invKeySchedule = this.invKeySchedule;
  5170. const invSBOX = this.invSBox;
  5171. const invSubMix = this.invSubMix;
  5172. const invSubMix0 = invSubMix[0];
  5173. const invSubMix1 = invSubMix[1];
  5174. const invSubMix2 = invSubMix[2];
  5175. const invSubMix3 = invSubMix[3];
  5176. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  5177. let initVector0 = initVector[0];
  5178. let initVector1 = initVector[1];
  5179. let initVector2 = initVector[2];
  5180. let initVector3 = initVector[3];
  5181. const inputInt32 = new Int32Array(inputArrayBuffer);
  5182. const outputInt32 = new Int32Array(inputInt32.length);
  5183. let t0, t1, t2, t3;
  5184. let s0, s1, s2, s3;
  5185. let inputWords0, inputWords1, inputWords2, inputWords3;
  5186. let ksRow, i;
  5187. const swapWord = this.networkToHostOrderSwap;
  5188. while (offset < inputInt32.length) {
  5189. inputWords0 = swapWord(inputInt32[offset]);
  5190. inputWords1 = swapWord(inputInt32[offset + 1]);
  5191. inputWords2 = swapWord(inputInt32[offset + 2]);
  5192. inputWords3 = swapWord(inputInt32[offset + 3]);
  5193. s0 = inputWords0 ^ invKeySchedule[0];
  5194. s1 = inputWords3 ^ invKeySchedule[1];
  5195. s2 = inputWords2 ^ invKeySchedule[2];
  5196. s3 = inputWords1 ^ invKeySchedule[3];
  5197. ksRow = 4;
  5198. // Iterate through the rounds of decryption
  5199. for (i = 1; i < nRounds; i++) {
  5200. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  5201. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5202. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5203. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5204. // Update state
  5205. s0 = t0;
  5206. s1 = t1;
  5207. s2 = t2;
  5208. s3 = t3;
  5209. ksRow = ksRow + 4;
  5210. }
  5211. // Shift rows, sub bytes, add round key
  5212. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  5213. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5214. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5215. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5216. // Write
  5217. outputInt32[offset] = swapWord(t0 ^ initVector0);
  5218. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  5219. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  5220. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  5221. // reset initVector to last 4 unsigned int
  5222. initVector0 = inputWords0;
  5223. initVector1 = inputWords1;
  5224. initVector2 = inputWords2;
  5225. initVector3 = inputWords3;
  5226. offset = offset + 4;
  5227. }
  5228. return outputInt32.buffer;
  5229. }
  5230. }
  5231. class FastAESKey {
  5232. constructor(subtle, key, aesMode) {
  5233. this.subtle = void 0;
  5234. this.key = void 0;
  5235. this.aesMode = void 0;
  5236. this.subtle = subtle;
  5237. this.key = key;
  5238. this.aesMode = aesMode;
  5239. }
  5240. expandKey() {
  5241. const subtleAlgoName = getSubtleAlgoName(this.aesMode);
  5242. return this.subtle.importKey('raw', this.key, {
  5243. name: subtleAlgoName
  5244. }, false, ['encrypt', 'decrypt']);
  5245. }
  5246. }
  5247. function getSubtleAlgoName(aesMode) {
  5248. switch (aesMode) {
  5249. case DecrypterAesMode.cbc:
  5250. return 'AES-CBC';
  5251. case DecrypterAesMode.ctr:
  5252. return 'AES-CTR';
  5253. default:
  5254. throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);
  5255. }
  5256. }
  5257. const CHUNK_SIZE = 16; // 16 bytes, 128 bits
  5258. class Decrypter {
  5259. constructor(config, {
  5260. removePKCS7Padding = true
  5261. } = {}) {
  5262. this.logEnabled = true;
  5263. this.removePKCS7Padding = void 0;
  5264. this.subtle = null;
  5265. this.softwareDecrypter = null;
  5266. this.key = null;
  5267. this.fastAesKey = null;
  5268. this.remainderData = null;
  5269. this.currentIV = null;
  5270. this.currentResult = null;
  5271. this.useSoftware = void 0;
  5272. this.enableSoftwareAES = void 0;
  5273. this.enableSoftwareAES = config.enableSoftwareAES;
  5274. this.removePKCS7Padding = removePKCS7Padding;
  5275. // built in decryptor expects PKCS7 padding
  5276. if (removePKCS7Padding) {
  5277. try {
  5278. const browserCrypto = self.crypto;
  5279. if (browserCrypto) {
  5280. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  5281. }
  5282. } catch (e) {
  5283. /* no-op */
  5284. }
  5285. }
  5286. this.useSoftware = !this.subtle;
  5287. }
  5288. destroy() {
  5289. this.subtle = null;
  5290. this.softwareDecrypter = null;
  5291. this.key = null;
  5292. this.fastAesKey = null;
  5293. this.remainderData = null;
  5294. this.currentIV = null;
  5295. this.currentResult = null;
  5296. }
  5297. isSync() {
  5298. return this.useSoftware;
  5299. }
  5300. flush() {
  5301. const {
  5302. currentResult,
  5303. remainderData
  5304. } = this;
  5305. if (!currentResult || remainderData) {
  5306. this.reset();
  5307. return null;
  5308. }
  5309. const data = new Uint8Array(currentResult);
  5310. this.reset();
  5311. if (this.removePKCS7Padding) {
  5312. return removePadding(data);
  5313. }
  5314. return data;
  5315. }
  5316. reset() {
  5317. this.currentResult = null;
  5318. this.currentIV = null;
  5319. this.remainderData = null;
  5320. if (this.softwareDecrypter) {
  5321. this.softwareDecrypter = null;
  5322. }
  5323. }
  5324. decrypt(data, key, iv, aesMode) {
  5325. if (this.useSoftware) {
  5326. return new Promise((resolve, reject) => {
  5327. const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  5328. this.softwareDecrypt(dataView, key, iv, aesMode);
  5329. const decryptResult = this.flush();
  5330. if (decryptResult) {
  5331. resolve(decryptResult.buffer);
  5332. } else {
  5333. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  5334. }
  5335. });
  5336. }
  5337. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  5338. }
  5339. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  5340. // data is handled in the flush() call
  5341. softwareDecrypt(data, key, iv, aesMode) {
  5342. const {
  5343. currentIV,
  5344. currentResult,
  5345. remainderData
  5346. } = this;
  5347. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  5348. logger.warn('SoftwareDecrypt: can only handle AES-128-CBC');
  5349. return null;
  5350. }
  5351. this.logOnce('JS AES decrypt');
  5352. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  5353. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  5354. // the end on flush(), but by that time we have already received all bytes for the segment.
  5355. // Progressive decryption does not work with WebCrypto
  5356. if (remainderData) {
  5357. data = appendUint8Array(remainderData, data);
  5358. this.remainderData = null;
  5359. }
  5360. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  5361. const currentChunk = this.getValidChunk(data);
  5362. if (!currentChunk.length) {
  5363. return null;
  5364. }
  5365. if (currentIV) {
  5366. iv = currentIV;
  5367. }
  5368. let softwareDecrypter = this.softwareDecrypter;
  5369. if (!softwareDecrypter) {
  5370. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  5371. }
  5372. softwareDecrypter.expandKey(key);
  5373. const result = currentResult;
  5374. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  5375. this.currentIV = currentChunk.slice(-16).buffer;
  5376. if (!result) {
  5377. return null;
  5378. }
  5379. return result;
  5380. }
  5381. webCryptoDecrypt(data, key, iv, aesMode) {
  5382. if (this.key !== key || !this.fastAesKey) {
  5383. if (!this.subtle) {
  5384. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  5385. }
  5386. this.key = key;
  5387. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  5388. }
  5389. return this.fastAesKey.expandKey().then(aesKey => {
  5390. // decrypt using web crypto
  5391. if (!this.subtle) {
  5392. return Promise.reject(new Error('web crypto not initialized'));
  5393. }
  5394. this.logOnce('WebCrypto AES decrypt');
  5395. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);
  5396. return crypto.decrypt(data.buffer, aesKey);
  5397. }).catch(err => {
  5398. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  5399. return this.onWebCryptoError(data, key, iv, aesMode);
  5400. });
  5401. }
  5402. onWebCryptoError(data, key, iv, aesMode) {
  5403. const enableSoftwareAES = this.enableSoftwareAES;
  5404. if (enableSoftwareAES) {
  5405. this.useSoftware = true;
  5406. this.logEnabled = true;
  5407. this.softwareDecrypt(data, key, iv, aesMode);
  5408. const decryptResult = this.flush();
  5409. if (decryptResult) {
  5410. return decryptResult.buffer;
  5411. }
  5412. }
  5413. throw new Error('WebCrypto' + (enableSoftwareAES ? ' and softwareDecrypt' : '') + ': failed to decrypt data');
  5414. }
  5415. getValidChunk(data) {
  5416. let currentChunk = data;
  5417. const splitPoint = data.length - data.length % CHUNK_SIZE;
  5418. if (splitPoint !== data.length) {
  5419. currentChunk = data.slice(0, splitPoint);
  5420. this.remainderData = data.slice(splitPoint);
  5421. }
  5422. return currentChunk;
  5423. }
  5424. logOnce(msg) {
  5425. if (!this.logEnabled) {
  5426. return;
  5427. }
  5428. logger.log(`[decrypter]: ${msg}`);
  5429. this.logEnabled = false;
  5430. }
  5431. }
  5432. const MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  5433. class FragmentLoader {
  5434. constructor(config) {
  5435. this.config = void 0;
  5436. this.loader = null;
  5437. this.partLoadTimeout = -1;
  5438. this.config = config;
  5439. }
  5440. destroy() {
  5441. if (this.loader) {
  5442. this.loader.destroy();
  5443. this.loader = null;
  5444. }
  5445. }
  5446. abort() {
  5447. if (this.loader) {
  5448. // Abort the loader for current fragment. Only one may load at any given time
  5449. this.loader.abort();
  5450. }
  5451. }
  5452. load(frag, onProgress) {
  5453. const url = frag.url;
  5454. if (!url) {
  5455. return Promise.reject(new LoadError({
  5456. type: ErrorTypes.NETWORK_ERROR,
  5457. details: ErrorDetails.FRAG_LOAD_ERROR,
  5458. fatal: false,
  5459. frag,
  5460. error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),
  5461. networkDetails: null
  5462. }));
  5463. }
  5464. this.abort();
  5465. const config = this.config;
  5466. const FragmentILoader = config.fLoader;
  5467. const DefaultILoader = config.loader;
  5468. return new Promise((resolve, reject) => {
  5469. if (this.loader) {
  5470. this.loader.destroy();
  5471. }
  5472. if (frag.gap) {
  5473. if (frag.tagList.some(tags => tags[0] === 'GAP')) {
  5474. reject(createGapLoadError(frag));
  5475. return;
  5476. } else {
  5477. // Reset temporary treatment as GAP tag
  5478. frag.gap = false;
  5479. }
  5480. }
  5481. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  5482. const loaderContext = createLoaderContext(frag);
  5483. frag.loader = loader;
  5484. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  5485. const loaderConfig = {
  5486. loadPolicy,
  5487. timeout: loadPolicy.maxLoadTimeMs,
  5488. maxRetry: 0,
  5489. retryDelay: 0,
  5490. maxRetryDelay: 0,
  5491. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  5492. };
  5493. // Assign frag stats to the loader's stats reference
  5494. frag.stats = loader.stats;
  5495. const callbacks = {
  5496. onSuccess: (response, stats, context, networkDetails) => {
  5497. this.resetLoader(frag, loader);
  5498. let payload = response.data;
  5499. if (context.resetIV && frag.decryptdata) {
  5500. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  5501. payload = payload.slice(16);
  5502. }
  5503. resolve({
  5504. frag,
  5505. part: null,
  5506. payload,
  5507. networkDetails
  5508. });
  5509. },
  5510. onError: (response, context, networkDetails, stats) => {
  5511. this.resetLoader(frag, loader);
  5512. reject(new LoadError({
  5513. type: ErrorTypes.NETWORK_ERROR,
  5514. details: ErrorDetails.FRAG_LOAD_ERROR,
  5515. fatal: false,
  5516. frag,
  5517. response: _objectSpread2({
  5518. url,
  5519. data: undefined
  5520. }, response),
  5521. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  5522. networkDetails,
  5523. stats
  5524. }));
  5525. },
  5526. onAbort: (stats, context, networkDetails) => {
  5527. this.resetLoader(frag, loader);
  5528. reject(new LoadError({
  5529. type: ErrorTypes.NETWORK_ERROR,
  5530. details: ErrorDetails.INTERNAL_ABORTED,
  5531. fatal: false,
  5532. frag,
  5533. error: new Error('Aborted'),
  5534. networkDetails,
  5535. stats
  5536. }));
  5537. },
  5538. onTimeout: (stats, context, networkDetails) => {
  5539. this.resetLoader(frag, loader);
  5540. reject(new LoadError({
  5541. type: ErrorTypes.NETWORK_ERROR,
  5542. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  5543. fatal: false,
  5544. frag,
  5545. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  5546. networkDetails,
  5547. stats
  5548. }));
  5549. }
  5550. };
  5551. if (onProgress) {
  5552. callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({
  5553. frag,
  5554. part: null,
  5555. payload: data,
  5556. networkDetails
  5557. });
  5558. }
  5559. loader.load(loaderContext, loaderConfig, callbacks);
  5560. });
  5561. }
  5562. loadPart(frag, part, onProgress) {
  5563. this.abort();
  5564. const config = this.config;
  5565. const FragmentILoader = config.fLoader;
  5566. const DefaultILoader = config.loader;
  5567. return new Promise((resolve, reject) => {
  5568. if (this.loader) {
  5569. this.loader.destroy();
  5570. }
  5571. if (frag.gap || part.gap) {
  5572. reject(createGapLoadError(frag, part));
  5573. return;
  5574. }
  5575. const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  5576. const loaderContext = createLoaderContext(frag, part);
  5577. frag.loader = loader;
  5578. // Should we define another load policy for parts?
  5579. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  5580. const loaderConfig = {
  5581. loadPolicy,
  5582. timeout: loadPolicy.maxLoadTimeMs,
  5583. maxRetry: 0,
  5584. retryDelay: 0,
  5585. maxRetryDelay: 0,
  5586. highWaterMark: MIN_CHUNK_SIZE
  5587. };
  5588. // Assign part stats to the loader's stats reference
  5589. part.stats = loader.stats;
  5590. loader.load(loaderContext, loaderConfig, {
  5591. onSuccess: (response, stats, context, networkDetails) => {
  5592. this.resetLoader(frag, loader);
  5593. this.updateStatsFromPart(frag, part);
  5594. const partLoadedData = {
  5595. frag,
  5596. part,
  5597. payload: response.data,
  5598. networkDetails
  5599. };
  5600. onProgress(partLoadedData);
  5601. resolve(partLoadedData);
  5602. },
  5603. onError: (response, context, networkDetails, stats) => {
  5604. this.resetLoader(frag, loader);
  5605. reject(new LoadError({
  5606. type: ErrorTypes.NETWORK_ERROR,
  5607. details: ErrorDetails.FRAG_LOAD_ERROR,
  5608. fatal: false,
  5609. frag,
  5610. part,
  5611. response: _objectSpread2({
  5612. url: loaderContext.url,
  5613. data: undefined
  5614. }, response),
  5615. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  5616. networkDetails,
  5617. stats
  5618. }));
  5619. },
  5620. onAbort: (stats, context, networkDetails) => {
  5621. frag.stats.aborted = part.stats.aborted;
  5622. this.resetLoader(frag, loader);
  5623. reject(new LoadError({
  5624. type: ErrorTypes.NETWORK_ERROR,
  5625. details: ErrorDetails.INTERNAL_ABORTED,
  5626. fatal: false,
  5627. frag,
  5628. part,
  5629. error: new Error('Aborted'),
  5630. networkDetails,
  5631. stats
  5632. }));
  5633. },
  5634. onTimeout: (stats, context, networkDetails) => {
  5635. this.resetLoader(frag, loader);
  5636. reject(new LoadError({
  5637. type: ErrorTypes.NETWORK_ERROR,
  5638. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  5639. fatal: false,
  5640. frag,
  5641. part,
  5642. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  5643. networkDetails,
  5644. stats
  5645. }));
  5646. }
  5647. });
  5648. });
  5649. }
  5650. updateStatsFromPart(frag, part) {
  5651. const fragStats = frag.stats;
  5652. const partStats = part.stats;
  5653. const partTotal = partStats.total;
  5654. fragStats.loaded += partStats.loaded;
  5655. if (partTotal) {
  5656. const estTotalParts = Math.round(frag.duration / part.duration);
  5657. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  5658. const estRemainingParts = estTotalParts - estLoadedParts;
  5659. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  5660. fragStats.total = fragStats.loaded + estRemainingBytes;
  5661. } else {
  5662. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  5663. }
  5664. const fragLoading = fragStats.loading;
  5665. const partLoading = partStats.loading;
  5666. if (fragLoading.start) {
  5667. // add to fragment loader latency
  5668. fragLoading.first += partLoading.first - partLoading.start;
  5669. } else {
  5670. fragLoading.start = partLoading.start;
  5671. fragLoading.first = partLoading.first;
  5672. }
  5673. fragLoading.end = partLoading.end;
  5674. }
  5675. resetLoader(frag, loader) {
  5676. frag.loader = null;
  5677. if (this.loader === loader) {
  5678. self.clearTimeout(this.partLoadTimeout);
  5679. this.loader = null;
  5680. }
  5681. loader.destroy();
  5682. }
  5683. }
  5684. function createLoaderContext(frag, part = null) {
  5685. const segment = part || frag;
  5686. const loaderContext = {
  5687. frag,
  5688. part,
  5689. responseType: 'arraybuffer',
  5690. url: segment.url,
  5691. headers: {},
  5692. rangeStart: 0,
  5693. rangeEnd: 0
  5694. };
  5695. const start = segment.byteRangeStartOffset;
  5696. const end = segment.byteRangeEndOffset;
  5697. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  5698. var _frag$decryptdata;
  5699. let byteRangeStart = start;
  5700. let byteRangeEnd = end;
  5701. if (frag.sn === 'initSegment' && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  5702. // MAP segment encrypted with method 'AES-128' or 'AES-256' (cbc), when served with HTTP Range,
  5703. // has the unencrypted size specified in the range.
  5704. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  5705. const fragmentLen = end - start;
  5706. if (fragmentLen % 16) {
  5707. byteRangeEnd = end + (16 - fragmentLen % 16);
  5708. }
  5709. if (start !== 0) {
  5710. loaderContext.resetIV = true;
  5711. byteRangeStart = start - 16;
  5712. }
  5713. }
  5714. loaderContext.rangeStart = byteRangeStart;
  5715. loaderContext.rangeEnd = byteRangeEnd;
  5716. }
  5717. return loaderContext;
  5718. }
  5719. function createGapLoadError(frag, part) {
  5720. const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);
  5721. const errorData = {
  5722. type: ErrorTypes.MEDIA_ERROR,
  5723. details: ErrorDetails.FRAG_GAP,
  5724. fatal: false,
  5725. frag,
  5726. error,
  5727. networkDetails: null
  5728. };
  5729. if (part) {
  5730. errorData.part = part;
  5731. }
  5732. (part ? part : frag).stats.aborted = true;
  5733. return new LoadError(errorData);
  5734. }
  5735. function isMethodFullSegmentAesCbc(method) {
  5736. return method === 'AES-128' || method === 'AES-256';
  5737. }
  5738. class LoadError extends Error {
  5739. constructor(data) {
  5740. super(data.error.message);
  5741. this.data = void 0;
  5742. this.data = data;
  5743. }
  5744. }
  5745. /**
  5746. * @ignore
  5747. * Sub-class specialization of EventHandler base class.
  5748. *
  5749. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  5750. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  5751. *
  5752. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  5753. * using the `tick` method.
  5754. *
  5755. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  5756. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  5757. *
  5758. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  5759. * and cancelled with `clearNextTick`.
  5760. *
  5761. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  5762. *
  5763. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  5764. *
  5765. * Further explanations:
  5766. *
  5767. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  5768. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  5769. *
  5770. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  5771. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  5772. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  5773. */
  5774. class TaskLoop extends Logger {
  5775. constructor(label, logger) {
  5776. super(label, logger);
  5777. this._boundTick = void 0;
  5778. this._tickTimer = null;
  5779. this._tickInterval = null;
  5780. this._tickCallCount = 0;
  5781. this._boundTick = this.tick.bind(this);
  5782. }
  5783. destroy() {
  5784. this.onHandlerDestroying();
  5785. this.onHandlerDestroyed();
  5786. }
  5787. onHandlerDestroying() {
  5788. // clear all timers before unregistering from event bus
  5789. this.clearNextTick();
  5790. this.clearInterval();
  5791. }
  5792. onHandlerDestroyed() {}
  5793. hasInterval() {
  5794. return !!this._tickInterval;
  5795. }
  5796. hasNextTick() {
  5797. return !!this._tickTimer;
  5798. }
  5799. /**
  5800. * @param millis - Interval time (ms)
  5801. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  5802. */
  5803. setInterval(millis) {
  5804. if (!this._tickInterval) {
  5805. this._tickCallCount = 0;
  5806. this._tickInterval = self.setInterval(this._boundTick, millis);
  5807. return true;
  5808. }
  5809. return false;
  5810. }
  5811. /**
  5812. * @returns True when interval was cleared, false when none was set (no effect)
  5813. */
  5814. clearInterval() {
  5815. if (this._tickInterval) {
  5816. self.clearInterval(this._tickInterval);
  5817. this._tickInterval = null;
  5818. return true;
  5819. }
  5820. return false;
  5821. }
  5822. /**
  5823. * @returns True when timeout was cleared, false when none was set (no effect)
  5824. */
  5825. clearNextTick() {
  5826. if (this._tickTimer) {
  5827. self.clearTimeout(this._tickTimer);
  5828. this._tickTimer = null;
  5829. return true;
  5830. }
  5831. return false;
  5832. }
  5833. /**
  5834. * Will call the subclass doTick implementation in this main loop tick
  5835. * or in the next one (via setTimeout(,0)) in case it has already been called
  5836. * in this tick (in case this is a re-entrant call).
  5837. */
  5838. tick() {
  5839. this._tickCallCount++;
  5840. if (this._tickCallCount === 1) {
  5841. this.doTick();
  5842. // re-entrant call to tick from previous doTick call stack
  5843. // -> schedule a call on the next main loop iteration to process this task processing request
  5844. if (this._tickCallCount > 1) {
  5845. // make sure only one timer exists at any time at max
  5846. this.tickImmediate();
  5847. }
  5848. this._tickCallCount = 0;
  5849. }
  5850. }
  5851. tickImmediate() {
  5852. this.clearNextTick();
  5853. this._tickTimer = self.setTimeout(this._boundTick, 0);
  5854. }
  5855. /**
  5856. * For subclass to implement task logic
  5857. * @abstract
  5858. */
  5859. doTick() {}
  5860. }
  5861. class ChunkMetadata {
  5862. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  5863. this.level = void 0;
  5864. this.sn = void 0;
  5865. this.part = void 0;
  5866. this.id = void 0;
  5867. this.size = void 0;
  5868. this.partial = void 0;
  5869. this.transmuxing = getNewPerformanceTiming();
  5870. this.buffering = {
  5871. audio: getNewPerformanceTiming(),
  5872. video: getNewPerformanceTiming(),
  5873. audiovideo: getNewPerformanceTiming()
  5874. };
  5875. this.level = level;
  5876. this.sn = sn;
  5877. this.id = id;
  5878. this.size = size;
  5879. this.part = part;
  5880. this.partial = partial;
  5881. }
  5882. }
  5883. function getNewPerformanceTiming() {
  5884. return {
  5885. start: 0,
  5886. executeStart: 0,
  5887. executeEnd: 0,
  5888. end: 0
  5889. };
  5890. }
  5891. /**
  5892. * Provides methods dealing with buffer length retrieval for example.
  5893. *
  5894. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  5895. *
  5896. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  5897. */
  5898. const noopBuffered = {
  5899. length: 0,
  5900. start: () => 0,
  5901. end: () => 0
  5902. };
  5903. class BufferHelper {
  5904. /**
  5905. * Return true if `media`'s buffered include `position`
  5906. */
  5907. static isBuffered(media, position) {
  5908. if (media) {
  5909. const buffered = BufferHelper.getBuffered(media);
  5910. for (let i = buffered.length; i--;) {
  5911. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  5912. return true;
  5913. }
  5914. }
  5915. }
  5916. return false;
  5917. }
  5918. static bufferedRanges(media) {
  5919. if (media) {
  5920. const timeRanges = BufferHelper.getBuffered(media);
  5921. return BufferHelper.timeRangesToArray(timeRanges);
  5922. }
  5923. return [];
  5924. }
  5925. static timeRangesToArray(timeRanges) {
  5926. const buffered = [];
  5927. for (let i = 0; i < timeRanges.length; i++) {
  5928. buffered.push({
  5929. start: timeRanges.start(i),
  5930. end: timeRanges.end(i)
  5931. });
  5932. }
  5933. return buffered;
  5934. }
  5935. static bufferInfo(media, pos, maxHoleDuration) {
  5936. if (media) {
  5937. const buffered = BufferHelper.bufferedRanges(media);
  5938. if (buffered.length) {
  5939. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  5940. }
  5941. }
  5942. return {
  5943. len: 0,
  5944. start: pos,
  5945. end: pos,
  5946. bufferedIndex: -1
  5947. };
  5948. }
  5949. static bufferedInfo(buffered, pos, maxHoleDuration) {
  5950. pos = Math.max(0, pos);
  5951. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  5952. if (buffered.length > 1) {
  5953. buffered.sort((a, b) => a.start - b.start || b.end - a.end);
  5954. }
  5955. let bufferedIndex = -1;
  5956. let buffered2 = [];
  5957. if (maxHoleDuration) {
  5958. // there might be some small holes between buffer time range
  5959. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  5960. // buffer time range representations that discards those holes
  5961. for (let i = 0; i < buffered.length; i++) {
  5962. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  5963. bufferedIndex = i;
  5964. }
  5965. const buf2len = buffered2.length;
  5966. if (buf2len) {
  5967. const buf2end = buffered2[buf2len - 1].end;
  5968. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  5969. if (buffered[i].start - buf2end < maxHoleDuration) {
  5970. // merge overlapping time ranges
  5971. // update lastRange.end only if smaller than item.end
  5972. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  5973. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  5974. if (buffered[i].end > buf2end) {
  5975. buffered2[buf2len - 1].end = buffered[i].end;
  5976. }
  5977. } else {
  5978. // big hole
  5979. buffered2.push(buffered[i]);
  5980. }
  5981. } else {
  5982. // first value
  5983. buffered2.push(buffered[i]);
  5984. }
  5985. }
  5986. } else {
  5987. buffered2 = buffered;
  5988. }
  5989. let bufferLen = 0;
  5990. let nextStart;
  5991. // bufferStart and bufferEnd are buffer boundaries around current playback position (pos)
  5992. let bufferStart = pos;
  5993. let bufferEnd = pos;
  5994. for (let i = 0; i < buffered2.length; i++) {
  5995. const start = buffered2[i].start;
  5996. const end = buffered2[i].end;
  5997. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  5998. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  5999. bufferedIndex = i;
  6000. }
  6001. if (pos + maxHoleDuration >= start && pos < end) {
  6002. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  6003. bufferStart = start;
  6004. bufferEnd = end;
  6005. bufferLen = bufferEnd - pos;
  6006. } else if (pos + maxHoleDuration < start) {
  6007. nextStart = start;
  6008. break;
  6009. }
  6010. }
  6011. return {
  6012. len: bufferLen,
  6013. start: bufferStart || 0,
  6014. end: bufferEnd || 0,
  6015. nextStart,
  6016. buffered,
  6017. bufferedIndex
  6018. };
  6019. }
  6020. /**
  6021. * Safe method to get buffered property.
  6022. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  6023. */
  6024. static getBuffered(media) {
  6025. try {
  6026. return media.buffered || noopBuffered;
  6027. } catch (e) {
  6028. logger.log('failed to get media.buffered', e);
  6029. return noopBuffered;
  6030. }
  6031. }
  6032. }
  6033. const VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  6034. function hasVariableReferences(str) {
  6035. return VARIABLE_REPLACEMENT_REGEX.test(str);
  6036. }
  6037. function substituteVariables(parsed, value) {
  6038. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  6039. const variableList = parsed.variableList;
  6040. return value.replace(VARIABLE_REPLACEMENT_REGEX, variableReference => {
  6041. const variableName = variableReference.substring(2, variableReference.length - 1);
  6042. const variableValue = variableList == null ? void 0 : variableList[variableName];
  6043. if (variableValue === undefined) {
  6044. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  6045. return variableReference;
  6046. }
  6047. return variableValue;
  6048. });
  6049. }
  6050. return value;
  6051. }
  6052. function addVariableDefinition(parsed, attr, parentUrl) {
  6053. let variableList = parsed.variableList;
  6054. if (!variableList) {
  6055. parsed.variableList = variableList = {};
  6056. }
  6057. let NAME;
  6058. let VALUE;
  6059. if ('QUERYPARAM' in attr) {
  6060. NAME = attr.QUERYPARAM;
  6061. try {
  6062. const searchParams = new self.URL(parentUrl).searchParams;
  6063. if (searchParams.has(NAME)) {
  6064. VALUE = searchParams.get(NAME);
  6065. } else {
  6066. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  6067. }
  6068. } catch (error) {
  6069. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  6070. }
  6071. } else {
  6072. NAME = attr.NAME;
  6073. VALUE = attr.VALUE;
  6074. }
  6075. if (NAME in variableList) {
  6076. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  6077. } else {
  6078. variableList[NAME] = VALUE || '';
  6079. }
  6080. }
  6081. function importVariableDefinition(parsed, attr, sourceVariableList) {
  6082. const IMPORT = attr.IMPORT;
  6083. if (sourceVariableList && IMPORT in sourceVariableList) {
  6084. let variableList = parsed.variableList;
  6085. if (!variableList) {
  6086. parsed.variableList = variableList = {};
  6087. }
  6088. variableList[IMPORT] = sourceVariableList[IMPORT];
  6089. } else {
  6090. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  6091. }
  6092. }
  6093. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  6094. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  6095. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  6096. class AttrList {
  6097. constructor(attrs, parsed) {
  6098. if (typeof attrs === 'string') {
  6099. attrs = AttrList.parseAttrList(attrs, parsed);
  6100. }
  6101. _extends(this, attrs);
  6102. }
  6103. get clientAttrs() {
  6104. return Object.keys(this).filter(attr => attr.substring(0, 2) === 'X-');
  6105. }
  6106. decimalInteger(attrName) {
  6107. const intValue = parseInt(this[attrName], 10);
  6108. if (intValue > Number.MAX_SAFE_INTEGER) {
  6109. return Infinity;
  6110. }
  6111. return intValue;
  6112. }
  6113. hexadecimalInteger(attrName) {
  6114. if (this[attrName]) {
  6115. let stringValue = (this[attrName] || '0x').slice(2);
  6116. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  6117. const value = new Uint8Array(stringValue.length / 2);
  6118. for (let i = 0; i < stringValue.length / 2; i++) {
  6119. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  6120. }
  6121. return value;
  6122. }
  6123. return null;
  6124. }
  6125. hexadecimalIntegerAsNumber(attrName) {
  6126. const intValue = parseInt(this[attrName], 16);
  6127. if (intValue > Number.MAX_SAFE_INTEGER) {
  6128. return Infinity;
  6129. }
  6130. return intValue;
  6131. }
  6132. decimalFloatingPoint(attrName) {
  6133. return parseFloat(this[attrName]);
  6134. }
  6135. optionalFloat(attrName, defaultValue) {
  6136. const value = this[attrName];
  6137. return value ? parseFloat(value) : defaultValue;
  6138. }
  6139. enumeratedString(attrName) {
  6140. return this[attrName];
  6141. }
  6142. enumeratedStringList(attrName, dict) {
  6143. const attrValue = this[attrName];
  6144. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {
  6145. result[identifier.toLowerCase()] = true;
  6146. return result;
  6147. }, dict);
  6148. }
  6149. bool(attrName) {
  6150. return this[attrName] === 'YES';
  6151. }
  6152. decimalResolution(attrName) {
  6153. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  6154. if (res === null) {
  6155. return undefined;
  6156. }
  6157. return {
  6158. width: parseInt(res[1], 10),
  6159. height: parseInt(res[2], 10)
  6160. };
  6161. }
  6162. static parseAttrList(input, parsed) {
  6163. let match;
  6164. const attrs = {};
  6165. const quote = '"';
  6166. ATTR_LIST_REGEX.lastIndex = 0;
  6167. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  6168. const name = match[1].trim();
  6169. let value = match[2];
  6170. const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  6171. let hexadecimalSequence = false;
  6172. if (quotedString) {
  6173. value = value.slice(1, -1);
  6174. } else {
  6175. switch (name) {
  6176. case 'IV':
  6177. case 'SCTE35-CMD':
  6178. case 'SCTE35-IN':
  6179. case 'SCTE35-OUT':
  6180. hexadecimalSequence = true;
  6181. }
  6182. }
  6183. if (parsed && (quotedString || hexadecimalSequence)) {
  6184. {
  6185. value = substituteVariables(parsed, value);
  6186. }
  6187. } else if (!hexadecimalSequence && !quotedString) {
  6188. switch (name) {
  6189. case 'CLOSED-CAPTIONS':
  6190. if (value === 'NONE') {
  6191. break;
  6192. }
  6193. // falls through
  6194. case 'ALLOWED-CPC':
  6195. case 'CLASS':
  6196. case 'ASSOC-LANGUAGE':
  6197. case 'AUDIO':
  6198. case 'BYTERANGE':
  6199. case 'CHANNELS':
  6200. case 'CHARACTERISTICS':
  6201. case 'CODECS':
  6202. case 'DATA-ID':
  6203. case 'END-DATE':
  6204. case 'GROUP-ID':
  6205. case 'ID':
  6206. case 'IMPORT':
  6207. case 'INSTREAM-ID':
  6208. case 'KEYFORMAT':
  6209. case 'KEYFORMATVERSIONS':
  6210. case 'LANGUAGE':
  6211. case 'NAME':
  6212. case 'PATHWAY-ID':
  6213. case 'QUERYPARAM':
  6214. case 'RECENTLY-REMOVED-DATERANGES':
  6215. case 'SERVER-URI':
  6216. case 'STABLE-RENDITION-ID':
  6217. case 'STABLE-VARIANT-ID':
  6218. case 'START-DATE':
  6219. case 'SUBTITLES':
  6220. case 'SUPPLEMENTAL-CODECS':
  6221. case 'URI':
  6222. case 'VALUE':
  6223. case 'VIDEO':
  6224. case 'X-ASSET-LIST':
  6225. case 'X-ASSET-URI':
  6226. // Since we are not checking tag:attribute combination, just warn rather than ignoring attribute
  6227. logger.warn(`${input}: attribute ${name} is missing quotes`);
  6228. // continue;
  6229. }
  6230. }
  6231. attrs[name] = value;
  6232. }
  6233. return attrs;
  6234. }
  6235. }
  6236. // Avoid exporting const enum so that these values can be inlined
  6237. const CLASS_INTERSTITIAL = 'com.apple.hls.interstitial';
  6238. function isDateRangeCueAttribute(attrName) {
  6239. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  6240. }
  6241. function isSCTE35Attribute(attrName) {
  6242. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  6243. }
  6244. class DateRange {
  6245. constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {
  6246. var _dateRangeWithSameId$;
  6247. this.attr = void 0;
  6248. this.tagAnchor = void 0;
  6249. this.tagOrder = void 0;
  6250. this._startDate = void 0;
  6251. this._endDate = void 0;
  6252. this._dateAtEnd = void 0;
  6253. this._cue = void 0;
  6254. this._badValueForSameId = void 0;
  6255. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  6256. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  6257. if (dateRangeWithSameId) {
  6258. const previousAttr = dateRangeWithSameId.attr;
  6259. for (const key in previousAttr) {
  6260. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  6261. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  6262. this._badValueForSameId = key;
  6263. break;
  6264. }
  6265. }
  6266. // Merge DateRange tags with the same ID
  6267. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  6268. }
  6269. this.attr = dateRangeAttr;
  6270. if (dateRangeWithSameId) {
  6271. this._startDate = dateRangeWithSameId._startDate;
  6272. this._cue = dateRangeWithSameId._cue;
  6273. this._endDate = dateRangeWithSameId._endDate;
  6274. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  6275. } else {
  6276. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  6277. }
  6278. if ("END-DATE" in this.attr) {
  6279. const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  6280. if (isFiniteNumber(endDate.getTime())) {
  6281. this._endDate = endDate;
  6282. }
  6283. }
  6284. }
  6285. get id() {
  6286. return this.attr.ID;
  6287. }
  6288. get class() {
  6289. return this.attr.CLASS;
  6290. }
  6291. get cue() {
  6292. const _cue = this._cue;
  6293. if (_cue === undefined) {
  6294. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? 'CUE' : 'X-CUE', {
  6295. pre: false,
  6296. post: false,
  6297. once: false
  6298. });
  6299. }
  6300. return _cue;
  6301. }
  6302. get startTime() {
  6303. const {
  6304. tagAnchor
  6305. } = this;
  6306. // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
  6307. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  6308. logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${tagAnchor}`);
  6309. return NaN;
  6310. }
  6311. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1000;
  6312. }
  6313. get startDate() {
  6314. return this._startDate;
  6315. }
  6316. get endDate() {
  6317. const dateAtEnd = this._endDate || this._dateAtEnd;
  6318. if (dateAtEnd) {
  6319. return dateAtEnd;
  6320. }
  6321. const duration = this.duration;
  6322. if (duration !== null) {
  6323. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1000);
  6324. }
  6325. return null;
  6326. }
  6327. get duration() {
  6328. if ("DURATION" in this.attr) {
  6329. const duration = this.attr.decimalFloatingPoint("DURATION");
  6330. if (isFiniteNumber(duration)) {
  6331. return duration;
  6332. }
  6333. } else if (this._endDate) {
  6334. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  6335. }
  6336. return null;
  6337. }
  6338. get plannedDuration() {
  6339. if ("PLANNED-DURATION" in this.attr) {
  6340. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  6341. }
  6342. return null;
  6343. }
  6344. get endOnNext() {
  6345. return this.attr.bool("END-ON-NEXT");
  6346. }
  6347. get isInterstitial() {
  6348. return this.class === CLASS_INTERSTITIAL;
  6349. }
  6350. get isValid() {
  6351. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || 'X-ASSET-URI' in this.attr || 'X-ASSET-LIST' in this.attr);
  6352. }
  6353. }
  6354. const DEFAULT_TARGET_DURATION = 10;
  6355. /**
  6356. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  6357. */
  6358. class LevelDetails {
  6359. constructor(baseUrl) {
  6360. this.PTSKnown = false;
  6361. this.alignedSliding = false;
  6362. this.averagetargetduration = void 0;
  6363. this.endCC = 0;
  6364. this.endSN = 0;
  6365. this.fragments = void 0;
  6366. this.fragmentHint = void 0;
  6367. this.partList = null;
  6368. this.dateRanges = void 0;
  6369. this.dateRangeTagCount = 0;
  6370. this.live = true;
  6371. this.requestScheduled = -1;
  6372. this.ageHeader = 0;
  6373. this.advancedDateTime = void 0;
  6374. this.updated = true;
  6375. this.advanced = true;
  6376. this.misses = 0;
  6377. this.startCC = 0;
  6378. this.startSN = 0;
  6379. this.startTimeOffset = null;
  6380. this.targetduration = 0;
  6381. this.totalduration = 0;
  6382. this.type = null;
  6383. this.url = void 0;
  6384. this.m3u8 = '';
  6385. this.version = null;
  6386. this.canBlockReload = false;
  6387. this.canSkipUntil = 0;
  6388. this.canSkipDateRanges = false;
  6389. this.skippedSegments = 0;
  6390. this.recentlyRemovedDateranges = void 0;
  6391. this.partHoldBack = 0;
  6392. this.holdBack = 0;
  6393. this.partTarget = 0;
  6394. this.preloadHint = void 0;
  6395. this.renditionReports = void 0;
  6396. this.tuneInGoal = 0;
  6397. this.deltaUpdateFailed = void 0;
  6398. this.driftStartTime = 0;
  6399. this.driftEndTime = 0;
  6400. this.driftStart = 0;
  6401. this.driftEnd = 0;
  6402. this.encryptedFragments = void 0;
  6403. this.playlistParsingError = null;
  6404. this.variableList = null;
  6405. this.hasVariableRefs = false;
  6406. this.appliedTimelineOffset = void 0;
  6407. this.fragments = [];
  6408. this.encryptedFragments = [];
  6409. this.dateRanges = {};
  6410. this.url = baseUrl;
  6411. }
  6412. reloaded(previous) {
  6413. if (!previous) {
  6414. this.advanced = true;
  6415. this.updated = true;
  6416. return;
  6417. }
  6418. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  6419. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  6420. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  6421. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  6422. if (this.updated || this.advanced) {
  6423. this.misses = Math.floor(previous.misses * 0.6);
  6424. } else {
  6425. this.misses = previous.misses + 1;
  6426. }
  6427. }
  6428. get hasProgramDateTime() {
  6429. if (this.fragments.length) {
  6430. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  6431. }
  6432. return false;
  6433. }
  6434. get levelTargetDuration() {
  6435. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  6436. }
  6437. get drift() {
  6438. const runTime = this.driftEndTime - this.driftStartTime;
  6439. if (runTime > 0) {
  6440. const runDuration = this.driftEnd - this.driftStart;
  6441. return runDuration * 1000 / runTime;
  6442. }
  6443. return 1;
  6444. }
  6445. get edge() {
  6446. return this.partEnd || this.fragmentEnd;
  6447. }
  6448. get partEnd() {
  6449. var _this$partList;
  6450. if ((_this$partList = this.partList) != null && _this$partList.length) {
  6451. return this.partList[this.partList.length - 1].end;
  6452. }
  6453. return this.fragmentEnd;
  6454. }
  6455. get fragmentEnd() {
  6456. var _this$fragments;
  6457. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  6458. return this.fragments[this.fragments.length - 1].end;
  6459. }
  6460. return 0;
  6461. }
  6462. get fragmentStart() {
  6463. var _this$fragments2;
  6464. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  6465. return this.fragments[0].start;
  6466. }
  6467. return 0;
  6468. }
  6469. get age() {
  6470. if (this.advancedDateTime) {
  6471. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  6472. }
  6473. return 0;
  6474. }
  6475. get lastPartIndex() {
  6476. var _this$partList2;
  6477. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  6478. return this.partList[this.partList.length - 1].index;
  6479. }
  6480. return -1;
  6481. }
  6482. get maxPartIndex() {
  6483. const partList = this.partList;
  6484. if (partList) {
  6485. const lastIndex = this.lastPartIndex;
  6486. if (lastIndex !== -1) {
  6487. for (let i = partList.length; i--;) {
  6488. if (partList[i].index > lastIndex) {
  6489. return partList[i].index;
  6490. }
  6491. }
  6492. return lastIndex;
  6493. }
  6494. }
  6495. return 0;
  6496. }
  6497. get lastPartSn() {
  6498. var _this$partList3;
  6499. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  6500. return this.partList[this.partList.length - 1].fragment.sn;
  6501. }
  6502. return this.endSN;
  6503. }
  6504. get expired() {
  6505. if (this.live && this.age && this.misses < 3) {
  6506. const playlistWindowDuration = this.partEnd - this.fragmentStart;
  6507. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  6508. }
  6509. return false;
  6510. }
  6511. }
  6512. function isFullSegmentEncryption(method) {
  6513. return method === 'AES-128' || method === 'AES-256' || method === 'AES-256-CTR';
  6514. }
  6515. function getAesModeFromFullSegmentMethod(method) {
  6516. switch (method) {
  6517. case 'AES-128':
  6518. case 'AES-256':
  6519. return DecrypterAesMode.cbc;
  6520. case 'AES-256-CTR':
  6521. return DecrypterAesMode.ctr;
  6522. default:
  6523. throw new Error(`invalid full segment method ${method}`);
  6524. }
  6525. }
  6526. function base64Decode(base64encodedStr) {
  6527. return Uint8Array.from(atob(base64encodedStr), c => c.charCodeAt(0));
  6528. }
  6529. // breaking up those two types in order to clarify what is happening in the decoding path.
  6530. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  6531. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  6532. /* utf.js - UTF-8 <=> UTF-16 convertion
  6533. *
  6534. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  6535. * Version: 1.0
  6536. * LastModified: Dec 25 1999
  6537. * This library is free. You can redistribute it and/or modify it.
  6538. */
  6539. function strToUtf8array(str) {
  6540. return Uint8Array.from(unescape(encodeURIComponent(str)), c => c.charCodeAt(0));
  6541. }
  6542. function getKeyIdBytes(str) {
  6543. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  6544. const paddedkeyIdbytes = new Uint8Array(16);
  6545. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  6546. return paddedkeyIdbytes;
  6547. }
  6548. function changeEndianness(keyId) {
  6549. const swap = function swap(array, from, to) {
  6550. const cur = array[from];
  6551. array[from] = array[to];
  6552. array[to] = cur;
  6553. };
  6554. swap(keyId, 0, 3);
  6555. swap(keyId, 1, 2);
  6556. swap(keyId, 4, 5);
  6557. swap(keyId, 6, 7);
  6558. }
  6559. function convertDataUriToArrayBytes(uri) {
  6560. // data:[<media type][;attribute=value][;base64],<data>
  6561. const colonsplit = uri.split(':');
  6562. let keydata = null;
  6563. if (colonsplit[0] === 'data' && colonsplit.length === 2) {
  6564. const semicolonsplit = colonsplit[1].split(';');
  6565. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');
  6566. if (commasplit.length === 2) {
  6567. const isbase64 = commasplit[0] === 'base64';
  6568. const data = commasplit[1];
  6569. if (isbase64) {
  6570. semicolonsplit.splice(-1, 1); // remove from processing
  6571. keydata = base64Decode(data);
  6572. } else {
  6573. keydata = getKeyIdBytes(data);
  6574. }
  6575. }
  6576. }
  6577. return keydata;
  6578. }
  6579. /** returns `undefined` is `self` is missing, e.g. in node */
  6580. const optionalSelf = typeof self !== 'undefined' ? self : undefined;
  6581. /**
  6582. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  6583. */
  6584. var KeySystems = {
  6585. CLEARKEY: "org.w3.clearkey",
  6586. FAIRPLAY: "com.apple.fps",
  6587. PLAYREADY: "com.microsoft.playready",
  6588. WIDEVINE: "com.widevine.alpha"
  6589. };
  6590. // Playlist #EXT-X-KEY KEYFORMAT values
  6591. var KeySystemFormats = {
  6592. CLEARKEY: "org.w3.clearkey",
  6593. FAIRPLAY: "com.apple.streamingkeydelivery",
  6594. PLAYREADY: "com.microsoft.playready",
  6595. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  6596. };
  6597. function keySystemFormatToKeySystemDomain(format) {
  6598. switch (format) {
  6599. case KeySystemFormats.FAIRPLAY:
  6600. return KeySystems.FAIRPLAY;
  6601. case KeySystemFormats.PLAYREADY:
  6602. return KeySystems.PLAYREADY;
  6603. case KeySystemFormats.WIDEVINE:
  6604. return KeySystems.WIDEVINE;
  6605. case KeySystemFormats.CLEARKEY:
  6606. return KeySystems.CLEARKEY;
  6607. }
  6608. }
  6609. function keySystemDomainToKeySystemFormat(keySystem) {
  6610. switch (keySystem) {
  6611. case KeySystems.FAIRPLAY:
  6612. return KeySystemFormats.FAIRPLAY;
  6613. case KeySystems.PLAYREADY:
  6614. return KeySystemFormats.PLAYREADY;
  6615. case KeySystems.WIDEVINE:
  6616. return KeySystemFormats.WIDEVINE;
  6617. case KeySystems.CLEARKEY:
  6618. return KeySystemFormats.CLEARKEY;
  6619. }
  6620. }
  6621. function getKeySystemsForConfig(config) {
  6622. const {
  6623. drmSystems,
  6624. widevineLicenseUrl
  6625. } = config;
  6626. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter(keySystem => !!drmSystems[keySystem]) : [];
  6627. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  6628. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  6629. }
  6630. return keySystemsToAttempt;
  6631. }
  6632. const requestMediaKeySystemAccess = function (_optionalSelf$navigat) {
  6633. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  6634. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  6635. } else {
  6636. return null;
  6637. }
  6638. }();
  6639. /**
  6640. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  6641. */
  6642. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  6643. let initDataTypes;
  6644. switch (keySystem) {
  6645. case KeySystems.FAIRPLAY:
  6646. initDataTypes = ['cenc', 'sinf'];
  6647. break;
  6648. case KeySystems.WIDEVINE:
  6649. case KeySystems.PLAYREADY:
  6650. initDataTypes = ['cenc'];
  6651. break;
  6652. case KeySystems.CLEARKEY:
  6653. initDataTypes = ['cenc', 'keyids'];
  6654. break;
  6655. default:
  6656. throw new Error(`Unknown key-system: ${keySystem}`);
  6657. }
  6658. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  6659. }
  6660. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  6661. const baseConfig = {
  6662. initDataTypes: initDataTypes,
  6663. persistentState: drmSystemOptions.persistentState || 'optional',
  6664. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',
  6665. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || 'temporary'],
  6666. audioCapabilities: audioCodecs.map(codec => ({
  6667. contentType: `audio/mp4; codecs=${codec}`,
  6668. robustness: drmSystemOptions.audioRobustness || '',
  6669. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  6670. })),
  6671. videoCapabilities: videoCodecs.map(codec => ({
  6672. contentType: `video/mp4; codecs=${codec}`,
  6673. robustness: drmSystemOptions.videoRobustness || '',
  6674. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  6675. }))
  6676. };
  6677. return [baseConfig];
  6678. }
  6679. function isPersistentSessionType(drmSystemOptions) {
  6680. var _drmSystemOptions$ses;
  6681. return drmSystemOptions.sessionType === 'persistent-license' || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some(type => type === 'persistent-license'));
  6682. }
  6683. function parsePlayReadyWRM(keyBytes) {
  6684. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  6685. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  6686. // Parse Playready WRMHeader XML
  6687. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);
  6688. const parser = new DOMParser();
  6689. const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');
  6690. const keyData = xmlDoc.getElementsByTagName('KID')[0];
  6691. if (keyData) {
  6692. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute('VALUE');
  6693. if (keyId) {
  6694. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  6695. // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID
  6696. // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID
  6697. changeEndianness(keyIdArray);
  6698. return keyIdArray;
  6699. }
  6700. }
  6701. return null;
  6702. }
  6703. let keyUriToKeyIdMap = {};
  6704. class LevelKey {
  6705. static clearKeyUriToKeyIdMap() {
  6706. keyUriToKeyIdMap = {};
  6707. }
  6708. constructor(method, uri, format, formatversions = [1], iv = null, keyId) {
  6709. this.uri = void 0;
  6710. this.method = void 0;
  6711. this.keyFormat = void 0;
  6712. this.keyFormatVersions = void 0;
  6713. this.encrypted = void 0;
  6714. this.isCommonEncryption = void 0;
  6715. this.iv = null;
  6716. this.key = null;
  6717. this.keyId = null;
  6718. this.pssh = null;
  6719. this.method = method;
  6720. this.uri = uri;
  6721. this.keyFormat = format;
  6722. this.keyFormatVersions = formatversions;
  6723. this.iv = iv;
  6724. this.encrypted = method ? method !== 'NONE' : false;
  6725. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  6726. if (keyId != null && keyId.startsWith('0x')) {
  6727. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  6728. }
  6729. }
  6730. matches(key) {
  6731. var _key$iv, _this$iv;
  6732. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(',') === this.keyFormatVersions.join(',') && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(',')) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(','));
  6733. }
  6734. isSupported() {
  6735. // If it's Segment encryption or No encryption, just select that key system
  6736. if (this.method) {
  6737. if (isFullSegmentEncryption(this.method) || this.method === 'NONE') {
  6738. return true;
  6739. }
  6740. if (this.keyFormat === 'identity') {
  6741. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  6742. return this.method === 'SAMPLE-AES';
  6743. } else {
  6744. switch (this.keyFormat) {
  6745. case KeySystemFormats.FAIRPLAY:
  6746. case KeySystemFormats.WIDEVINE:
  6747. case KeySystemFormats.PLAYREADY:
  6748. case KeySystemFormats.CLEARKEY:
  6749. return ['ISO-23001-7', 'SAMPLE-AES', 'SAMPLE-AES-CENC', 'SAMPLE-AES-CTR'].indexOf(this.method) !== -1;
  6750. }
  6751. }
  6752. }
  6753. return false;
  6754. }
  6755. getDecryptData(sn) {
  6756. if (!this.encrypted || !this.uri) {
  6757. return null;
  6758. }
  6759. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  6760. if (typeof sn !== 'number') {
  6761. // We are fetching decryption data for a initialization segment
  6762. // If the segment was encrypted with AES-128/256
  6763. // It must have an IV defined. We cannot substitute the Segment Number in.
  6764. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  6765. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  6766. sn = 0;
  6767. }
  6768. const iv = createInitializationVector(sn);
  6769. const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  6770. return decryptdata;
  6771. }
  6772. if (this.pssh && this.keyId) {
  6773. return this;
  6774. }
  6775. // Initialize keyId if possible
  6776. const keyBytes = convertDataUriToArrayBytes(this.uri);
  6777. if (keyBytes) {
  6778. switch (this.keyFormat) {
  6779. case KeySystemFormats.WIDEVINE:
  6780. // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using
  6781. // the playlist-key before the "encrypted" event. (Comment out to only use "encrypted" path.)
  6782. this.pssh = keyBytes;
  6783. // In case of Widevine, if KEYID is not in the playlist, assume only two fields in the pssh KEY tag URI.
  6784. if (!this.keyId && keyBytes.length >= 22) {
  6785. const offset = keyBytes.length - 22;
  6786. this.keyId = keyBytes.subarray(offset, offset + 16);
  6787. }
  6788. break;
  6789. case KeySystemFormats.PLAYREADY:
  6790. {
  6791. const PlayReadyKeySystemUUID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);
  6792. // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using
  6793. // the playlist-key before the "encrypted" event. (Comment out to only use "encrypted" path.)
  6794. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  6795. this.keyId = parsePlayReadyWRM(keyBytes);
  6796. break;
  6797. }
  6798. default:
  6799. {
  6800. let keydata = keyBytes.subarray(0, 16);
  6801. if (keydata.length !== 16) {
  6802. const padded = new Uint8Array(16);
  6803. padded.set(keydata, 16 - keydata.length);
  6804. keydata = padded;
  6805. }
  6806. this.keyId = keydata;
  6807. break;
  6808. }
  6809. }
  6810. }
  6811. // Default behavior: assign a new keyId for each uri
  6812. if (!this.keyId || this.keyId.byteLength !== 16) {
  6813. let keyId = keyUriToKeyIdMap[this.uri];
  6814. if (!keyId) {
  6815. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  6816. keyId = new Uint8Array(16);
  6817. const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes
  6818. dv.setUint32(0, val);
  6819. keyUriToKeyIdMap[this.uri] = keyId;
  6820. }
  6821. this.keyId = keyId;
  6822. }
  6823. return this;
  6824. }
  6825. }
  6826. function createInitializationVector(segmentNumber) {
  6827. const uint8View = new Uint8Array(16);
  6828. for (let i = 12; i < 16; i++) {
  6829. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  6830. }
  6831. return uint8View;
  6832. }
  6833. 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;
  6834. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6835. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  6836. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  6837. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6838. /(?!#) *(\S[^\r\n]*)/.source,
  6839. // segment URI, group 3 => the URI (note newline is not eaten)
  6840. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  6841. ].join('|'), 'g');
  6842. const LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
  6843. class M3U8Parser {
  6844. static findGroup(groups, mediaGroupId) {
  6845. for (let i = 0; i < groups.length; i++) {
  6846. const group = groups[i];
  6847. if (group.id === mediaGroupId) {
  6848. return group;
  6849. }
  6850. }
  6851. }
  6852. static resolve(url, baseUrl) {
  6853. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  6854. alwaysNormalize: true
  6855. });
  6856. }
  6857. static isMediaPlaylist(str) {
  6858. return IS_MEDIA_PLAYLIST.test(str);
  6859. }
  6860. static parseMasterPlaylist(string, baseurl) {
  6861. const hasVariableRefs = hasVariableReferences(string) ;
  6862. const parsed = {
  6863. contentSteering: null,
  6864. levels: [],
  6865. playlistParsingError: null,
  6866. sessionData: null,
  6867. sessionKeys: null,
  6868. startTimeOffset: null,
  6869. variableList: null,
  6870. hasVariableRefs
  6871. };
  6872. const levelsWithKnownCodecs = [];
  6873. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  6874. let result;
  6875. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6876. if (result[1]) {
  6877. var _level$unknownCodecs;
  6878. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  6879. const attrs = new AttrList(result[1], parsed);
  6880. const uri = substituteVariables(parsed, result[2]) ;
  6881. const level = {
  6882. attrs,
  6883. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  6884. name: attrs.NAME,
  6885. url: M3U8Parser.resolve(uri, baseurl)
  6886. };
  6887. const resolution = attrs.decimalResolution('RESOLUTION');
  6888. if (resolution) {
  6889. level.width = resolution.width;
  6890. level.height = resolution.height;
  6891. }
  6892. setCodecs(attrs.CODECS, level);
  6893. const supplementalCodecs = attrs['SUPPLEMENTAL-CODECS'];
  6894. if (supplementalCodecs) {
  6895. level.supplemental = {};
  6896. setCodecs(supplementalCodecs, level.supplemental);
  6897. }
  6898. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  6899. levelsWithKnownCodecs.push(level);
  6900. }
  6901. parsed.levels.push(level);
  6902. } else if (result[3]) {
  6903. const tag = result[3];
  6904. const attributes = result[4];
  6905. switch (tag) {
  6906. case 'SESSION-DATA':
  6907. {
  6908. // #EXT-X-SESSION-DATA
  6909. const sessionAttrs = new AttrList(attributes, parsed);
  6910. const dataId = sessionAttrs['DATA-ID'];
  6911. if (dataId) {
  6912. if (parsed.sessionData === null) {
  6913. parsed.sessionData = {};
  6914. }
  6915. parsed.sessionData[dataId] = sessionAttrs;
  6916. }
  6917. break;
  6918. }
  6919. case 'SESSION-KEY':
  6920. {
  6921. // #EXT-X-SESSION-KEY
  6922. const sessionKey = parseKey(attributes, baseurl, parsed);
  6923. if (sessionKey.encrypted && sessionKey.isSupported()) {
  6924. if (parsed.sessionKeys === null) {
  6925. parsed.sessionKeys = [];
  6926. }
  6927. parsed.sessionKeys.push(sessionKey);
  6928. } else {
  6929. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  6930. }
  6931. break;
  6932. }
  6933. case 'DEFINE':
  6934. {
  6935. // #EXT-X-DEFINE
  6936. {
  6937. const variableAttributes = new AttrList(attributes, parsed);
  6938. addVariableDefinition(parsed, variableAttributes, baseurl);
  6939. }
  6940. break;
  6941. }
  6942. case 'CONTENT-STEERING':
  6943. {
  6944. // #EXT-X-CONTENT-STEERING
  6945. const contentSteeringAttributes = new AttrList(attributes, parsed);
  6946. parsed.contentSteering = {
  6947. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  6948. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  6949. };
  6950. break;
  6951. }
  6952. case 'START':
  6953. {
  6954. // #EXT-X-START
  6955. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  6956. break;
  6957. }
  6958. }
  6959. }
  6960. }
  6961. // Filter out levels with unknown codecs if it does not remove all levels
  6962. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  6963. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  6964. if (parsed.levels.length === 0) {
  6965. parsed.playlistParsingError = new Error('no levels found in manifest');
  6966. }
  6967. return parsed;
  6968. }
  6969. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  6970. let result;
  6971. const results = {};
  6972. const levels = parsed.levels;
  6973. const groupsByType = {
  6974. AUDIO: levels.map(level => ({
  6975. id: level.attrs.AUDIO,
  6976. audioCodec: level.audioCodec
  6977. })),
  6978. SUBTITLES: levels.map(level => ({
  6979. id: level.attrs.SUBTITLES,
  6980. textCodec: level.textCodec
  6981. })),
  6982. 'CLOSED-CAPTIONS': []
  6983. };
  6984. let id = 0;
  6985. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6986. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6987. const attrs = new AttrList(result[1], parsed);
  6988. const type = attrs.TYPE;
  6989. if (type) {
  6990. const groups = groupsByType[type];
  6991. const medias = results[type] || [];
  6992. results[type] = medias;
  6993. const lang = attrs.LANGUAGE;
  6994. const assocLang = attrs['ASSOC-LANGUAGE'];
  6995. const channels = attrs.CHANNELS;
  6996. const characteristics = attrs.CHARACTERISTICS;
  6997. const instreamId = attrs['INSTREAM-ID'];
  6998. const media = {
  6999. attrs,
  7000. bitrate: 0,
  7001. id: id++,
  7002. groupId: attrs['GROUP-ID'] || '',
  7003. name: attrs.NAME || lang || '',
  7004. type,
  7005. default: attrs.bool('DEFAULT'),
  7006. autoselect: attrs.bool('AUTOSELECT'),
  7007. forced: attrs.bool('FORCED'),
  7008. lang,
  7009. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  7010. };
  7011. if (assocLang) {
  7012. media.assocLang = assocLang;
  7013. }
  7014. if (channels) {
  7015. media.channels = channels;
  7016. }
  7017. if (characteristics) {
  7018. media.characteristics = characteristics;
  7019. }
  7020. if (instreamId) {
  7021. media.instreamId = instreamId;
  7022. }
  7023. if (groups != null && groups.length) {
  7024. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  7025. // If we don't find the track signalled, lets use the first audio groups codec we have
  7026. // Acting as a best guess
  7027. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  7028. assignCodec(media, groupCodec, 'audioCodec');
  7029. assignCodec(media, groupCodec, 'textCodec');
  7030. }
  7031. medias.push(media);
  7032. }
  7033. }
  7034. return results;
  7035. }
  7036. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  7037. var _LEVEL_PLAYLIST_REGEX;
  7038. const base = {
  7039. url: baseurl
  7040. };
  7041. const level = new LevelDetails(baseurl);
  7042. const fragments = level.fragments;
  7043. const programDateTimes = [];
  7044. // The most recent init segment seen (applies to all subsequent segments)
  7045. let currentInitSegment = null;
  7046. let currentSN = 0;
  7047. let currentPart = 0;
  7048. let totalduration = 0;
  7049. let discontinuityCounter = 0;
  7050. let currentBitrate = 0;
  7051. let prevFrag = null;
  7052. let frag = new Fragment(type, base);
  7053. let result;
  7054. let i;
  7055. let levelkeys;
  7056. let firstPdtIndex = -1;
  7057. let createNextFrag = false;
  7058. let nextByteRange = null;
  7059. let serverControlAttrs;
  7060. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  7061. level.m3u8 = string;
  7062. level.hasVariableRefs = hasVariableReferences(string) ;
  7063. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== '#EXTM3U') {
  7064. level.playlistParsingError = new Error('Missing format identifier #EXTM3U');
  7065. return level;
  7066. }
  7067. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  7068. if (createNextFrag) {
  7069. createNextFrag = false;
  7070. frag = new Fragment(type, base);
  7071. // setup the next fragment for part loading
  7072. frag.playlistOffset = totalduration;
  7073. frag.start = totalduration;
  7074. frag.sn = currentSN;
  7075. frag.cc = discontinuityCounter;
  7076. if (currentBitrate) {
  7077. frag.bitrate = currentBitrate;
  7078. }
  7079. frag.level = id;
  7080. if (currentInitSegment) {
  7081. frag.initSegment = currentInitSegment;
  7082. if (currentInitSegment.rawProgramDateTime) {
  7083. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7084. currentInitSegment.rawProgramDateTime = null;
  7085. }
  7086. if (nextByteRange) {
  7087. frag.setByteRange(nextByteRange);
  7088. nextByteRange = null;
  7089. }
  7090. }
  7091. }
  7092. const duration = result[1];
  7093. if (duration) {
  7094. // INF
  7095. frag.duration = parseFloat(duration);
  7096. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7097. const title = (' ' + result[2]).slice(1);
  7098. frag.title = title || null;
  7099. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  7100. } else if (result[3]) {
  7101. // url
  7102. if (isFiniteNumber(frag.duration)) {
  7103. frag.playlistOffset = totalduration;
  7104. frag.start = totalduration;
  7105. if (levelkeys) {
  7106. setFragLevelKeys(frag, levelkeys, level);
  7107. }
  7108. frag.sn = currentSN;
  7109. frag.level = id;
  7110. frag.cc = discontinuityCounter;
  7111. fragments.push(frag);
  7112. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7113. const uri = (' ' + result[3]).slice(1);
  7114. frag.relurl = substituteVariables(level, uri) ;
  7115. assignProgramDateTime(frag, prevFrag, programDateTimes);
  7116. prevFrag = frag;
  7117. totalduration += frag.duration;
  7118. currentSN++;
  7119. currentPart = 0;
  7120. createNextFrag = true;
  7121. }
  7122. } else {
  7123. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  7124. if (!result) {
  7125. logger.warn('No matches on slow regex match for level playlist!');
  7126. continue;
  7127. }
  7128. for (i = 1; i < result.length; i++) {
  7129. if (result[i] !== undefined) {
  7130. break;
  7131. }
  7132. }
  7133. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7134. const tag = (' ' + result[i]).slice(1);
  7135. const value1 = (' ' + result[i + 1]).slice(1);
  7136. const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : null;
  7137. switch (tag) {
  7138. case 'BYTERANGE':
  7139. if (prevFrag) {
  7140. frag.setByteRange(value1, prevFrag);
  7141. } else {
  7142. frag.setByteRange(value1);
  7143. }
  7144. break;
  7145. case 'PROGRAM-DATE-TIME':
  7146. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7147. frag.rawProgramDateTime = value1;
  7148. frag.tagList.push(['PROGRAM-DATE-TIME', value1]);
  7149. if (firstPdtIndex === -1) {
  7150. firstPdtIndex = fragments.length;
  7151. }
  7152. break;
  7153. case 'PLAYLIST-TYPE':
  7154. if (level.type) {
  7155. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7156. }
  7157. level.type = value1.toUpperCase();
  7158. break;
  7159. case 'MEDIA-SEQUENCE':
  7160. if (level.startSN !== 0) {
  7161. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7162. } else if (fragments.length > 0) {
  7163. assignMustAppearBeforeSegmentsError(level, tag, result);
  7164. }
  7165. currentSN = level.startSN = parseInt(value1);
  7166. break;
  7167. case 'SKIP':
  7168. {
  7169. if (level.skippedSegments) {
  7170. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7171. }
  7172. const skipAttrs = new AttrList(value1, level);
  7173. const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  7174. if (isFiniteNumber(skippedSegments)) {
  7175. level.skippedSegments += skippedSegments;
  7176. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  7177. for (let _i = skippedSegments; _i--;) {
  7178. fragments.push(null);
  7179. }
  7180. currentSN += skippedSegments;
  7181. }
  7182. const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  7183. if (recentlyRemovedDateranges) {
  7184. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split('\t'));
  7185. }
  7186. break;
  7187. }
  7188. case 'TARGETDURATION':
  7189. if (level.targetduration !== 0) {
  7190. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7191. }
  7192. level.targetduration = Math.max(parseInt(value1), 1);
  7193. break;
  7194. case 'VERSION':
  7195. if (level.version !== null) {
  7196. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7197. }
  7198. level.version = parseInt(value1);
  7199. break;
  7200. case 'INDEPENDENT-SEGMENTS':
  7201. break;
  7202. case 'ENDLIST':
  7203. if (!level.live) {
  7204. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7205. }
  7206. level.live = false;
  7207. break;
  7208. case '#':
  7209. if (value1 || value2) {
  7210. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  7211. }
  7212. break;
  7213. case 'DISCONTINUITY':
  7214. discontinuityCounter++;
  7215. frag.tagList.push(['DIS']);
  7216. break;
  7217. case 'GAP':
  7218. frag.gap = true;
  7219. frag.tagList.push([tag]);
  7220. break;
  7221. case 'BITRATE':
  7222. frag.tagList.push([tag, value1]);
  7223. currentBitrate = parseInt(value1) * 1000;
  7224. if (isFiniteNumber(currentBitrate)) {
  7225. frag.bitrate = currentBitrate;
  7226. } else {
  7227. currentBitrate = 0;
  7228. }
  7229. break;
  7230. case 'DATERANGE':
  7231. {
  7232. const dateRangeAttr = new AttrList(value1, level);
  7233. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  7234. level.dateRangeTagCount++;
  7235. if (dateRange.isValid || level.skippedSegments) {
  7236. level.dateRanges[dateRange.id] = dateRange;
  7237. } else {
  7238. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  7239. }
  7240. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  7241. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  7242. break;
  7243. }
  7244. case 'DEFINE':
  7245. {
  7246. {
  7247. const variableAttributes = new AttrList(value1, level);
  7248. if ('IMPORT' in variableAttributes) {
  7249. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  7250. } else {
  7251. addVariableDefinition(level, variableAttributes, baseurl);
  7252. }
  7253. }
  7254. break;
  7255. }
  7256. case 'DISCONTINUITY-SEQUENCE':
  7257. if (level.startCC !== 0) {
  7258. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7259. } else if (fragments.length > 0) {
  7260. assignMustAppearBeforeSegmentsError(level, tag, result);
  7261. }
  7262. level.startCC = discontinuityCounter = parseInt(value1);
  7263. break;
  7264. case 'KEY':
  7265. {
  7266. const levelKey = parseKey(value1, baseurl, level);
  7267. if (levelKey.isSupported()) {
  7268. if (levelKey.method === 'NONE') {
  7269. levelkeys = undefined;
  7270. break;
  7271. }
  7272. if (!levelkeys) {
  7273. levelkeys = {};
  7274. }
  7275. const currentKey = levelkeys[levelKey.keyFormat];
  7276. // Ignore duplicate playlist KEY tags
  7277. if (!(currentKey != null && currentKey.matches(levelKey))) {
  7278. if (currentKey) {
  7279. levelkeys = _extends({}, levelkeys);
  7280. }
  7281. levelkeys[levelKey.keyFormat] = levelKey;
  7282. }
  7283. } else {
  7284. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  7285. }
  7286. break;
  7287. }
  7288. case 'START':
  7289. level.startTimeOffset = parseStartTimeOffset(value1);
  7290. break;
  7291. case 'MAP':
  7292. {
  7293. const mapAttrs = new AttrList(value1, level);
  7294. if (frag.duration) {
  7295. // Initial segment tag is after segment duration tag.
  7296. // #EXTINF: 6.0
  7297. // #EXT-X-MAP:URI="init.mp4
  7298. const init = new Fragment(type, base);
  7299. setInitSegment(init, mapAttrs, id, levelkeys);
  7300. currentInitSegment = init;
  7301. frag.initSegment = currentInitSegment;
  7302. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  7303. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7304. }
  7305. } else {
  7306. // Initial segment tag is before segment duration tag
  7307. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  7308. const end = frag.byteRangeEndOffset;
  7309. if (end) {
  7310. const start = frag.byteRangeStartOffset;
  7311. nextByteRange = `${end - start}@${start}`;
  7312. } else {
  7313. nextByteRange = null;
  7314. }
  7315. setInitSegment(frag, mapAttrs, id, levelkeys);
  7316. currentInitSegment = frag;
  7317. createNextFrag = true;
  7318. }
  7319. currentInitSegment.cc = discontinuityCounter;
  7320. break;
  7321. }
  7322. case 'SERVER-CONTROL':
  7323. {
  7324. if (serverControlAttrs) {
  7325. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7326. }
  7327. serverControlAttrs = new AttrList(value1);
  7328. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  7329. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  7330. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  7331. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  7332. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  7333. break;
  7334. }
  7335. case 'PART-INF':
  7336. {
  7337. if (level.partTarget) {
  7338. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7339. }
  7340. const partInfAttrs = new AttrList(value1);
  7341. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  7342. break;
  7343. }
  7344. case 'PART':
  7345. {
  7346. let partList = level.partList;
  7347. if (!partList) {
  7348. partList = level.partList = [];
  7349. }
  7350. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  7351. const index = currentPart++;
  7352. const partAttrs = new AttrList(value1, level);
  7353. const part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  7354. partList.push(part);
  7355. frag.duration += part.duration;
  7356. break;
  7357. }
  7358. case 'PRELOAD-HINT':
  7359. {
  7360. const preloadHintAttrs = new AttrList(value1, level);
  7361. level.preloadHint = preloadHintAttrs;
  7362. break;
  7363. }
  7364. case 'RENDITION-REPORT':
  7365. {
  7366. const renditionReportAttrs = new AttrList(value1, level);
  7367. level.renditionReports = level.renditionReports || [];
  7368. level.renditionReports.push(renditionReportAttrs);
  7369. break;
  7370. }
  7371. default:
  7372. logger.warn(`line parsed but not handled: ${result}`);
  7373. break;
  7374. }
  7375. }
  7376. }
  7377. if (prevFrag && !prevFrag.relurl) {
  7378. fragments.pop();
  7379. totalduration -= prevFrag.duration;
  7380. if (level.partList) {
  7381. level.fragmentHint = prevFrag;
  7382. }
  7383. } else if (level.partList) {
  7384. assignProgramDateTime(frag, prevFrag, programDateTimes);
  7385. frag.cc = discontinuityCounter;
  7386. level.fragmentHint = frag;
  7387. if (levelkeys) {
  7388. setFragLevelKeys(frag, levelkeys, level);
  7389. }
  7390. }
  7391. if (!level.targetduration) {
  7392. level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);
  7393. }
  7394. const fragmentLength = fragments.length;
  7395. const firstFragment = fragments[0];
  7396. const lastFragment = fragments[fragmentLength - 1];
  7397. totalduration += level.skippedSegments * level.targetduration;
  7398. if (totalduration > 0 && fragmentLength && lastFragment) {
  7399. level.averagetargetduration = totalduration / fragmentLength;
  7400. const lastSn = lastFragment.sn;
  7401. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  7402. if (!level.live) {
  7403. lastFragment.endList = true;
  7404. }
  7405. if (firstFragment && level.startCC === undefined) {
  7406. level.startCC = firstFragment.cc;
  7407. }
  7408. /**
  7409. * Backfill any missing PDT values
  7410. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  7411. * one or more Media Segment URIs, the client SHOULD extrapolate
  7412. * backward from that tag (using EXTINF durations and/or media
  7413. * timestamps) to associate dates with those segments."
  7414. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  7415. * computed.
  7416. */
  7417. if (firstPdtIndex > 0) {
  7418. backfillProgramDateTimes(fragments, firstPdtIndex);
  7419. if (firstFragment) {
  7420. programDateTimes.unshift(firstFragment);
  7421. }
  7422. }
  7423. } else {
  7424. level.endSN = 0;
  7425. level.startCC = 0;
  7426. }
  7427. if (level.fragmentHint) {
  7428. totalduration += level.fragmentHint.duration;
  7429. }
  7430. level.totalduration = totalduration;
  7431. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  7432. mapDateRanges(programDateTimes, level);
  7433. }
  7434. level.endCC = discontinuityCounter;
  7435. return level;
  7436. }
  7437. }
  7438. function mapDateRanges(programDateTimes, details) {
  7439. // Make sure DateRanges are mapped to a ProgramDateTime tag that applies a date to a segment that overlaps with its start date
  7440. const programDateTimeCount = programDateTimes.length;
  7441. if (!programDateTimeCount) {
  7442. return;
  7443. }
  7444. const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  7445. const playlistEnd = details.live ? Infinity : details.totalduration;
  7446. const dateRangeIds = Object.keys(details.dateRanges);
  7447. for (let i = dateRangeIds.length; i--;) {
  7448. const dateRange = details.dateRanges[dateRangeIds[i]];
  7449. const startDateTime = dateRange.startDate.getTime();
  7450. dateRange.tagAnchor = lastProgramDateTime.ref;
  7451. for (let j = programDateTimeCount; j--;) {
  7452. const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  7453. if (fragIndex !== -1) {
  7454. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  7455. break;
  7456. }
  7457. }
  7458. }
  7459. }
  7460. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  7461. const pdtFragment = programDateTimes[index];
  7462. if (pdtFragment) {
  7463. // find matching range between PDT tags
  7464. const pdtStart = pdtFragment.programDateTime;
  7465. if (startDateTime >= pdtStart || index === 0) {
  7466. var _programDateTimes;
  7467. const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  7468. if (startDateTime <= pdtStart + durationBetweenPdt * 1000) {
  7469. // map to fragment with date-time range
  7470. const startIndex = programDateTimes[index].sn - details.startSN;
  7471. const fragments = details.fragments;
  7472. if (fragments.length > programDateTimes.length) {
  7473. const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  7474. const endIndex = endSegment.sn - details.startSN;
  7475. for (let i = endIndex; i > startIndex; i--) {
  7476. const fragStartDateTime = fragments[i].programDateTime;
  7477. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1000) {
  7478. return i;
  7479. }
  7480. }
  7481. }
  7482. return startIndex;
  7483. }
  7484. }
  7485. }
  7486. return -1;
  7487. }
  7488. function parseKey(keyTagAttributes, baseurl, parsed) {
  7489. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  7490. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  7491. const keyAttrs = new AttrList(keyTagAttributes, parsed);
  7492. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  7493. const decrypturi = keyAttrs.URI;
  7494. const decryptiv = keyAttrs.hexadecimalInteger('IV');
  7495. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  7496. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  7497. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  7498. if (decrypturi && keyAttrs.IV && !decryptiv) {
  7499. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  7500. }
  7501. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  7502. // No uri is allowed when METHOD is NONE
  7503. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  7504. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  7505. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  7506. }
  7507. function parseStartTimeOffset(startAttributes) {
  7508. const startAttrs = new AttrList(startAttributes);
  7509. const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  7510. if (isFiniteNumber(startTimeOffset)) {
  7511. return startTimeOffset;
  7512. }
  7513. return null;
  7514. }
  7515. function setCodecs(codecsAttributeValue, level) {
  7516. let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);
  7517. ['video', 'audio', 'text'].forEach(type => {
  7518. const filtered = codecs.filter(codec => isCodecType(codec, type));
  7519. if (filtered.length) {
  7520. // Comma separated list of all codecs for type
  7521. level[`${type}Codec`] = filtered.map(c => c.split('/')[0]).join(',');
  7522. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  7523. codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);
  7524. }
  7525. });
  7526. level.unknownCodecs = codecs;
  7527. }
  7528. function assignCodec(media, groupItem, codecProperty) {
  7529. const codecValue = groupItem[codecProperty];
  7530. if (codecValue) {
  7531. media[codecProperty] = codecValue;
  7532. }
  7533. }
  7534. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  7535. let fragPrev = fragments[firstPdtIndex];
  7536. for (let i = firstPdtIndex; i--;) {
  7537. const frag = fragments[i];
  7538. // Exit on delta-playlist skipped segments
  7539. if (!frag) {
  7540. return;
  7541. }
  7542. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  7543. fragPrev = frag;
  7544. }
  7545. }
  7546. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  7547. if (frag.rawProgramDateTime) {
  7548. programDateTimes.push(frag);
  7549. } else if (prevFrag != null && prevFrag.programDateTime) {
  7550. frag.programDateTime = prevFrag.endProgramDateTime;
  7551. }
  7552. }
  7553. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  7554. frag.relurl = mapAttrs.URI;
  7555. if (mapAttrs.BYTERANGE) {
  7556. frag.setByteRange(mapAttrs.BYTERANGE);
  7557. }
  7558. frag.level = id;
  7559. frag.sn = 'initSegment';
  7560. if (levelkeys) {
  7561. frag.levelkeys = levelkeys;
  7562. }
  7563. frag.initSegment = null;
  7564. }
  7565. function setFragLevelKeys(frag, levelkeys, level) {
  7566. frag.levelkeys = levelkeys;
  7567. const {
  7568. encryptedFragments
  7569. } = level;
  7570. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {
  7571. encryptedFragments.push(frag);
  7572. }
  7573. }
  7574. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  7575. level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);
  7576. }
  7577. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  7578. level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);
  7579. }
  7580. function updateFromToPTS(fragFrom, fragTo) {
  7581. const fragToPTS = fragTo.startPTS;
  7582. // if we know startPTS[toIdx]
  7583. if (isFiniteNumber(fragToPTS)) {
  7584. // update fragment duration.
  7585. // it helps to fix drifts between playlist reported duration and fragment real duration
  7586. let duration = 0;
  7587. let frag;
  7588. if (fragTo.sn > fragFrom.sn) {
  7589. duration = fragToPTS - fragFrom.start;
  7590. frag = fragFrom;
  7591. } else {
  7592. duration = fragFrom.start - fragToPTS;
  7593. frag = fragTo;
  7594. }
  7595. if (frag.duration !== duration) {
  7596. frag.setDuration(duration);
  7597. }
  7598. // we dont know startPTS[toIdx]
  7599. } else if (fragTo.sn > fragFrom.sn) {
  7600. const contiguous = fragFrom.cc === fragTo.cc;
  7601. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  7602. if (contiguous && fragFrom.minEndPTS) {
  7603. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  7604. } else {
  7605. fragTo.setStart(fragFrom.start + fragFrom.duration);
  7606. }
  7607. } else {
  7608. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  7609. }
  7610. }
  7611. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  7612. const parsedMediaDuration = endPTS - startPTS;
  7613. if (parsedMediaDuration <= 0) {
  7614. logger.warn('Fragment should have a positive duration', frag);
  7615. endPTS = startPTS + frag.duration;
  7616. endDTS = startDTS + frag.duration;
  7617. }
  7618. let maxStartPTS = startPTS;
  7619. let minEndPTS = endPTS;
  7620. const fragStartPts = frag.startPTS;
  7621. const fragEndPts = frag.endPTS;
  7622. if (isFiniteNumber(fragStartPts)) {
  7623. // delta PTS between audio and video
  7624. const deltaPTS = Math.abs(fragStartPts - startPTS);
  7625. if (!isFiniteNumber(frag.deltaPTS)) {
  7626. frag.deltaPTS = deltaPTS;
  7627. } else {
  7628. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  7629. }
  7630. maxStartPTS = Math.max(startPTS, fragStartPts);
  7631. startPTS = Math.min(startPTS, fragStartPts);
  7632. startDTS = Math.min(startDTS, frag.startDTS);
  7633. minEndPTS = Math.min(endPTS, fragEndPts);
  7634. endPTS = Math.max(endPTS, fragEndPts);
  7635. endDTS = Math.max(endDTS, frag.endDTS);
  7636. }
  7637. const drift = startPTS - frag.start;
  7638. if (frag.start !== 0) {
  7639. frag.setStart(startPTS);
  7640. }
  7641. frag.setDuration(endPTS - frag.start);
  7642. frag.startPTS = startPTS;
  7643. frag.maxStartPTS = maxStartPTS;
  7644. frag.startDTS = startDTS;
  7645. frag.endPTS = endPTS;
  7646. frag.minEndPTS = minEndPTS;
  7647. frag.endDTS = endDTS;
  7648. const sn = frag.sn;
  7649. // exit if sn out of range
  7650. if (!details || sn < details.startSN || sn > details.endSN) {
  7651. return 0;
  7652. }
  7653. let i;
  7654. const fragIdx = sn - details.startSN;
  7655. const fragments = details.fragments;
  7656. // update frag reference in fragments array
  7657. // rationale is that fragments array might not contain this frag object.
  7658. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  7659. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  7660. // resulting in invalid sliding computation
  7661. fragments[fragIdx] = frag;
  7662. // adjust fragment PTS/duration from seqnum-1 to frag 0
  7663. for (i = fragIdx; i > 0; i--) {
  7664. updateFromToPTS(fragments[i], fragments[i - 1]);
  7665. }
  7666. // adjust fragment PTS/duration from seqnum to last frag
  7667. for (i = fragIdx; i < fragments.length - 1; i++) {
  7668. updateFromToPTS(fragments[i], fragments[i + 1]);
  7669. }
  7670. if (details.fragmentHint) {
  7671. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  7672. }
  7673. details.PTSKnown = details.alignedSliding = true;
  7674. return drift;
  7675. }
  7676. function mergeDetails(oldDetails, newDetails) {
  7677. if (oldDetails === newDetails) {
  7678. return;
  7679. }
  7680. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  7681. let currentInitSegment = null;
  7682. const oldFragments = oldDetails.fragments;
  7683. for (let i = oldFragments.length - 1; i >= 0; i--) {
  7684. const oldInit = oldFragments[i].initSegment;
  7685. if (oldInit) {
  7686. currentInitSegment = oldInit;
  7687. break;
  7688. }
  7689. }
  7690. if (oldDetails.fragmentHint) {
  7691. // prevent PTS and duration from being adjusted on the next hint
  7692. delete oldDetails.fragmentHint.endPTS;
  7693. }
  7694. // check if old/new playlists have fragments in common
  7695. // loop through overlapping SN and update startPTS, cc, and duration if any found
  7696. let PTSFrag;
  7697. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments) => {
  7698. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  7699. const ccOffset = oldFrag.cc - newFrag.cc;
  7700. for (let i = newFragIndex; i < newFragments.length; i++) {
  7701. newFragments[i].cc += ccOffset;
  7702. }
  7703. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  7704. }
  7705. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  7706. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  7707. newFrag.startDTS = oldFrag.startDTS;
  7708. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  7709. newFrag.endPTS = oldFrag.endPTS;
  7710. newFrag.endDTS = oldFrag.endDTS;
  7711. newFrag.minEndPTS = oldFrag.minEndPTS;
  7712. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  7713. if (newFrag.duration) {
  7714. PTSFrag = newFrag;
  7715. }
  7716. // PTS is known when any segment has startPTS and endPTS
  7717. newDetails.PTSKnown = newDetails.alignedSliding = true;
  7718. }
  7719. if (oldFrag.hasStreams) {
  7720. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  7721. }
  7722. newFrag.loader = oldFrag.loader;
  7723. if (oldFrag.hasStats) {
  7724. newFrag.stats = oldFrag.stats;
  7725. }
  7726. if (oldFrag.initSegment) {
  7727. newFrag.initSegment = oldFrag.initSegment;
  7728. currentInitSegment = oldFrag.initSegment;
  7729. }
  7730. });
  7731. const newFragments = newDetails.fragments;
  7732. const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  7733. if (currentInitSegment) {
  7734. fragmentsToCheck.forEach(frag => {
  7735. var _currentInitSegment;
  7736. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  7737. frag.initSegment = currentInitSegment;
  7738. }
  7739. });
  7740. }
  7741. if (newDetails.skippedSegments) {
  7742. newDetails.deltaUpdateFailed = newFragments.some(frag => !frag);
  7743. if (newDetails.deltaUpdateFailed) {
  7744. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  7745. for (let i = newDetails.skippedSegments; i--;) {
  7746. newFragments.shift();
  7747. }
  7748. newDetails.startSN = newFragments[0].sn;
  7749. } else {
  7750. if (newDetails.canSkipDateRanges) {
  7751. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  7752. }
  7753. const programDateTimes = oldDetails.fragments.filter(frag => frag.rawProgramDateTime);
  7754. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  7755. for (let i = 1; i < fragmentsToCheck.length; i++) {
  7756. if (fragmentsToCheck[i].programDateTime === null) {
  7757. assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);
  7758. }
  7759. }
  7760. }
  7761. mapDateRanges(programDateTimes, newDetails);
  7762. }
  7763. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  7764. }
  7765. if (!newDetails.startCC) {
  7766. var _fragPriorToNewStart$;
  7767. const fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  7768. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  7769. }
  7770. // Merge parts
  7771. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  7772. newPart.elementaryStreams = oldPart.elementaryStreams;
  7773. newPart.stats = oldPart.stats;
  7774. });
  7775. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  7776. if (PTSFrag) {
  7777. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  7778. } else {
  7779. // ensure that delta is within oldFragments range
  7780. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  7781. // in that case we also need to adjust start offset of all fragments
  7782. adjustSliding(oldDetails, newDetails);
  7783. }
  7784. if (newFragments.length) {
  7785. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  7786. }
  7787. newDetails.driftStartTime = oldDetails.driftStartTime;
  7788. newDetails.driftStart = oldDetails.driftStart;
  7789. const advancedDateTime = newDetails.advancedDateTime;
  7790. if (newDetails.advanced && advancedDateTime) {
  7791. const edge = newDetails.edge;
  7792. if (!newDetails.driftStart) {
  7793. newDetails.driftStartTime = advancedDateTime;
  7794. newDetails.driftStart = edge;
  7795. }
  7796. newDetails.driftEndTime = advancedDateTime;
  7797. newDetails.driftEnd = edge;
  7798. } else {
  7799. newDetails.driftEndTime = oldDetails.driftEndTime;
  7800. newDetails.driftEnd = oldDetails.driftEnd;
  7801. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  7802. }
  7803. if (newDetails.requestScheduled === -1) {
  7804. newDetails.requestScheduled = oldDetails.requestScheduled;
  7805. }
  7806. }
  7807. function mergeDateRanges(oldDateRanges, newDetails) {
  7808. const {
  7809. dateRanges: deltaDateRanges,
  7810. recentlyRemovedDateranges
  7811. } = newDetails;
  7812. const dateRanges = _extends({}, oldDateRanges);
  7813. if (recentlyRemovedDateranges) {
  7814. recentlyRemovedDateranges.forEach(id => {
  7815. delete dateRanges[id];
  7816. });
  7817. }
  7818. const mergeIds = Object.keys(dateRanges);
  7819. const mergeCount = mergeIds.length;
  7820. if (mergeCount) {
  7821. Object.keys(deltaDateRanges).forEach(id => {
  7822. const mergedDateRange = dateRanges[id];
  7823. const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  7824. if (dateRange.isValid) {
  7825. dateRanges[id] = dateRange;
  7826. if (!mergedDateRange) {
  7827. dateRange.tagOrder += mergeCount;
  7828. }
  7829. } else {
  7830. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(deltaDateRanges[id].attr)}"`);
  7831. }
  7832. });
  7833. }
  7834. return dateRanges;
  7835. }
  7836. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  7837. if (oldParts && newParts) {
  7838. let delta = 0;
  7839. for (let i = 0, len = oldParts.length; i <= len; i++) {
  7840. const oldPart = oldParts[i];
  7841. const newPart = newParts[i + delta];
  7842. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  7843. intersectionFn(oldPart, newPart);
  7844. } else {
  7845. delta--;
  7846. }
  7847. }
  7848. }
  7849. }
  7850. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  7851. const skippedSegments = newDetails.skippedSegments;
  7852. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  7853. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  7854. const delta = newDetails.startSN - oldDetails.startSN;
  7855. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  7856. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  7857. for (let i = start; i <= end; i++) {
  7858. const oldFrag = oldFrags[delta + i];
  7859. let newFrag = newFrags[i];
  7860. if (skippedSegments && !newFrag && oldFrag) {
  7861. // Fill in skipped segments in delta playlist
  7862. newFrag = newDetails.fragments[i] = oldFrag;
  7863. }
  7864. if (oldFrag && newFrag) {
  7865. intersectionFn(oldFrag, newFrag, i, newFrags);
  7866. if (oldFrag.url && oldFrag.url !== newFrag.url) {
  7867. newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);
  7868. return;
  7869. } else if (oldFrag.cc !== newFrag.cc) {
  7870. newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);
  7871. return;
  7872. }
  7873. }
  7874. }
  7875. }
  7876. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  7877. return new Error(`${message} ${newFrag.url}
  7878. Playlist starting @${oldDetails.startSN}
  7879. ${oldDetails.m3u8}
  7880. Playlist starting @${newDetails.startSN}
  7881. ${newDetails.m3u8}`);
  7882. }
  7883. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {
  7884. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  7885. const oldFragments = oldDetails.fragments;
  7886. const advancedOrStable = delta >= 0;
  7887. let sliding = 0;
  7888. if (advancedOrStable && delta < oldFragments.length) {
  7889. sliding = oldFragments[delta].start;
  7890. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  7891. sliding = oldDetails.fragmentEnd;
  7892. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  7893. // align with expected position (updated playlist start sequence is past end sequence of last update)
  7894. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  7895. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  7896. // align new start with old (playlist switch has a sequence with no overlap and should not be used for alignment)
  7897. sliding = oldDetails.fragmentStart;
  7898. } else {
  7899. // new details already has a sliding offset or has skipped segments
  7900. return;
  7901. }
  7902. addSliding(newDetails, sliding);
  7903. }
  7904. function addSliding(details, sliding) {
  7905. if (sliding) {
  7906. const fragments = details.fragments;
  7907. for (let i = details.skippedSegments; i < fragments.length; i++) {
  7908. fragments[i].addStart(sliding);
  7909. }
  7910. if (details.fragmentHint) {
  7911. details.fragmentHint.addStart(sliding);
  7912. }
  7913. }
  7914. }
  7915. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  7916. let reloadInterval = 1000 * newDetails.targetduration;
  7917. if (newDetails.updated) {
  7918. // Use last segment duration when shorter than target duration and near live edge
  7919. const fragments = newDetails.fragments;
  7920. const liveEdgeMaxTargetDurations = 4;
  7921. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  7922. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  7923. if (lastSegmentDuration < reloadInterval) {
  7924. reloadInterval = lastSegmentDuration;
  7925. }
  7926. }
  7927. } else {
  7928. // estimate = 'miss half average';
  7929. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  7930. // changed then it MUST wait for a period of one-half the target
  7931. // duration before retrying.
  7932. reloadInterval /= 2;
  7933. }
  7934. return Math.round(reloadInterval);
  7935. }
  7936. function getFragmentWithSN(details, sn, fragCurrent) {
  7937. if (!details) {
  7938. return null;
  7939. }
  7940. let fragment = details.fragments[sn - details.startSN];
  7941. if (fragment) {
  7942. return fragment;
  7943. }
  7944. fragment = details.fragmentHint;
  7945. if (fragment && fragment.sn === sn) {
  7946. return fragment;
  7947. }
  7948. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  7949. return fragCurrent;
  7950. }
  7951. return null;
  7952. }
  7953. function getPartWith(details, sn, partIndex) {
  7954. if (!details) {
  7955. return null;
  7956. }
  7957. return findPart(details.partList, sn, partIndex);
  7958. }
  7959. function findPart(partList, sn, partIndex) {
  7960. if (partList) {
  7961. for (let i = partList.length; i--;) {
  7962. const part = partList[i];
  7963. if (part.index === partIndex && part.fragment.sn === sn) {
  7964. return part;
  7965. }
  7966. }
  7967. }
  7968. return null;
  7969. }
  7970. function reassignFragmentLevelIndexes(levels) {
  7971. levels.forEach((level, index) => {
  7972. var _level$details;
  7973. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach(fragment => {
  7974. fragment.level = index;
  7975. if (fragment.initSegment) {
  7976. fragment.initSegment.level = index;
  7977. }
  7978. });
  7979. });
  7980. }
  7981. function findFirstFragWithCC(fragments, cc) {
  7982. for (let i = 0, len = fragments.length; i < len; i++) {
  7983. var _fragments$i;
  7984. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  7985. return fragments[i];
  7986. }
  7987. }
  7988. return null;
  7989. }
  7990. function shouldAlignOnDiscontinuities(refDetails, details) {
  7991. if (refDetails) {
  7992. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  7993. return true;
  7994. }
  7995. }
  7996. return false;
  7997. }
  7998. function adjustFragmentStart(frag, sliding) {
  7999. if (frag) {
  8000. const start = frag.start + sliding;
  8001. frag.start = frag.startPTS = start;
  8002. frag.endPTS = start + frag.duration;
  8003. }
  8004. }
  8005. function adjustSlidingStart(sliding, details) {
  8006. // Update segments
  8007. const fragments = details.fragments;
  8008. for (let i = 0, len = fragments.length; i < len; i++) {
  8009. adjustFragmentStart(fragments[i], sliding);
  8010. }
  8011. // Update LL-HLS parts at the end of the playlist
  8012. if (details.fragmentHint) {
  8013. adjustFragmentStart(details.fragmentHint, sliding);
  8014. }
  8015. details.alignedSliding = true;
  8016. }
  8017. /**
  8018. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  8019. * contiguous stream with the last fragments.
  8020. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  8021. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  8022. * and an extra download.
  8023. * @param lastLevel
  8024. * @param details
  8025. */
  8026. function alignStream(switchDetails, details) {
  8027. if (!switchDetails) {
  8028. return;
  8029. }
  8030. alignDiscontinuities(details, switchDetails);
  8031. if (!details.alignedSliding && switchDetails) {
  8032. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  8033. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  8034. // discontinuity sequence.
  8035. alignMediaPlaylistByPDT(details, switchDetails);
  8036. }
  8037. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  8038. // Try to align on sn so that we pick a better start fragment.
  8039. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  8040. // and adjustSliding only adjusts fragments after skippedSegments.
  8041. adjustSliding(switchDetails, details, false);
  8042. }
  8043. }
  8044. /**
  8045. * Ajust the start of fragments in `details` by the difference in time between fragments of the latest
  8046. * shared discontinuity sequence change.
  8047. * @param lastLevel - The details of the last loaded level
  8048. * @param details - The details of the new level
  8049. */
  8050. function alignDiscontinuities(details, refDetails) {
  8051. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  8052. return;
  8053. }
  8054. const targetCC = Math.min(refDetails.endCC, details.endCC);
  8055. const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  8056. const frag = findFirstFragWithCC(details.fragments, targetCC);
  8057. if (!refFrag || !frag) {
  8058. return;
  8059. }
  8060. logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);
  8061. const delta = refFrag.start - frag.start;
  8062. adjustSlidingStart(delta, details);
  8063. }
  8064. /**
  8065. * Ensures appropriate time-alignment between renditions based on PDT.
  8066. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  8067. * for the last discontinuity sequence number shared by both playlists when present,
  8068. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  8069. * times/timelines of `details` accordingly.
  8070. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  8071. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  8072. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  8073. * be consistent across playlists, per the HLS spec.
  8074. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  8075. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  8076. */
  8077. function alignMediaPlaylistByPDT(details, refDetails) {
  8078. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  8079. return;
  8080. }
  8081. const fragments = details.fragments;
  8082. const refFragments = refDetails.fragments;
  8083. if (!fragments.length || !refFragments.length) {
  8084. return;
  8085. }
  8086. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  8087. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  8088. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  8089. let refFrag;
  8090. let frag;
  8091. const targetCC = Math.min(refDetails.endCC, details.endCC);
  8092. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  8093. refFrag = findFirstFragWithCC(refFragments, targetCC);
  8094. frag = findFirstFragWithCC(fragments, targetCC);
  8095. }
  8096. if (!refFrag || !frag) {
  8097. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  8098. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  8099. }
  8100. const refPDT = refFrag.programDateTime;
  8101. const targetPDT = frag.programDateTime;
  8102. if (!refPDT || !targetPDT) {
  8103. return;
  8104. }
  8105. const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  8106. adjustSlidingStart(delta, details);
  8107. }
  8108. /**
  8109. * TimeRanges to string helper
  8110. */
  8111. const TimeRanges = {
  8112. toString: function (r) {
  8113. let log = '';
  8114. const len = r.length;
  8115. for (let i = 0; i < len; i++) {
  8116. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  8117. }
  8118. return log;
  8119. }
  8120. };
  8121. const State = {
  8122. STOPPED: 'STOPPED',
  8123. IDLE: 'IDLE',
  8124. KEY_LOADING: 'KEY_LOADING',
  8125. FRAG_LOADING: 'FRAG_LOADING',
  8126. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  8127. WAITING_TRACK: 'WAITING_TRACK',
  8128. PARSING: 'PARSING',
  8129. PARSED: 'PARSED',
  8130. ENDED: 'ENDED',
  8131. ERROR: 'ERROR',
  8132. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  8133. WAITING_LEVEL: 'WAITING_LEVEL'
  8134. };
  8135. class BaseStreamController extends TaskLoop {
  8136. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  8137. super(logPrefix, hls.logger);
  8138. this.hls = void 0;
  8139. this.fragPrevious = null;
  8140. this.fragCurrent = null;
  8141. this.fragmentTracker = void 0;
  8142. this.transmuxer = null;
  8143. this._state = State.STOPPED;
  8144. this.playlistType = void 0;
  8145. this.media = null;
  8146. this.mediaBuffer = null;
  8147. this.config = void 0;
  8148. this.bitrateTest = false;
  8149. this.lastCurrentTime = 0;
  8150. this.nextLoadPosition = 0;
  8151. this.startPosition = 0;
  8152. this.startTimeOffset = null;
  8153. this.retryDate = 0;
  8154. this.levels = null;
  8155. this.fragmentLoader = void 0;
  8156. this.keyLoader = void 0;
  8157. this.levelLastLoaded = null;
  8158. this.startFragRequested = false;
  8159. this.decrypter = void 0;
  8160. this.initPTS = [];
  8161. this.buffering = true;
  8162. this.loadingParts = false;
  8163. this.loopSn = void 0;
  8164. this.onMediaSeeking = () => {
  8165. const {
  8166. config,
  8167. fragCurrent,
  8168. media,
  8169. mediaBuffer,
  8170. state
  8171. } = this;
  8172. const currentTime = media ? media.currentTime : 0;
  8173. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  8174. const noFowardBuffer = !bufferInfo.len;
  8175. this.log(`Media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}, ${noFowardBuffer ? 'out of' : 'in'} buffer`);
  8176. if (this.state === State.ENDED) {
  8177. this.resetLoadingState();
  8178. } else if (fragCurrent) {
  8179. // Seeking while frag load is in progress
  8180. const tolerance = config.maxFragLookUpTolerance;
  8181. const fragStartOffset = fragCurrent.start - tolerance;
  8182. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  8183. // if seeking out of buffered range or into new one
  8184. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  8185. const pastFragment = currentTime > fragEndOffset;
  8186. // if the seek position is outside the current fragment range
  8187. if (currentTime < fragStartOffset || pastFragment) {
  8188. if (pastFragment && fragCurrent.loader) {
  8189. this.log(`Cancelling fragment load for seek (sn: ${fragCurrent.sn})`);
  8190. fragCurrent.abortRequests();
  8191. this.resetLoadingState();
  8192. }
  8193. this.fragPrevious = null;
  8194. }
  8195. }
  8196. }
  8197. if (media) {
  8198. // Remove gap fragments
  8199. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  8200. // Don't set lastCurrentTime with backward seeks (allows for frag selection with strict tolerances)
  8201. const lastCurrentTime = this.lastCurrentTime;
  8202. if (currentTime > lastCurrentTime) {
  8203. this.lastCurrentTime = currentTime;
  8204. }
  8205. if (!this.loadingParts) {
  8206. const bufferEnd = Math.max(bufferInfo.end, currentTime);
  8207. const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);
  8208. if (shouldLoadParts) {
  8209. this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);
  8210. this.loadingParts = shouldLoadParts;
  8211. }
  8212. }
  8213. }
  8214. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  8215. if (!this.hls.hasEnoughToStart) {
  8216. this.log(`Setting ${noFowardBuffer ? 'startPosition' : 'nextLoadPosition'} to ${currentTime} for seek without enough to start`);
  8217. this.nextLoadPosition = currentTime;
  8218. if (noFowardBuffer) {
  8219. this.startPosition = currentTime;
  8220. }
  8221. }
  8222. // Async tick to speed up processing
  8223. this.tickImmediate();
  8224. };
  8225. this.onMediaEnded = () => {
  8226. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  8227. this.log(`setting startPosition to 0 because media ended`);
  8228. this.startPosition = this.lastCurrentTime = 0;
  8229. };
  8230. this.playlistType = playlistType;
  8231. this.hls = hls;
  8232. this.fragmentLoader = new FragmentLoader(hls.config);
  8233. this.keyLoader = keyLoader;
  8234. this.fragmentTracker = fragmentTracker;
  8235. this.config = hls.config;
  8236. this.decrypter = new Decrypter(hls.config);
  8237. }
  8238. registerListeners() {
  8239. const {
  8240. hls
  8241. } = this;
  8242. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  8243. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8244. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8245. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8246. hls.on(Events.ERROR, this.onError, this);
  8247. }
  8248. unregisterListeners() {
  8249. const {
  8250. hls
  8251. } = this;
  8252. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  8253. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8254. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8255. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8256. hls.off(Events.ERROR, this.onError, this);
  8257. }
  8258. doTick() {
  8259. this.onTickEnd();
  8260. }
  8261. onTickEnd() {}
  8262. startLoad(startPosition) {}
  8263. stopLoad() {
  8264. if (this.state === State.STOPPED) {
  8265. return;
  8266. }
  8267. this.fragmentLoader.abort();
  8268. this.keyLoader.abort(this.playlistType);
  8269. const frag = this.fragCurrent;
  8270. if (frag != null && frag.loader) {
  8271. frag.abortRequests();
  8272. this.fragmentTracker.removeFragment(frag);
  8273. }
  8274. this.resetTransmuxer();
  8275. this.fragCurrent = null;
  8276. this.fragPrevious = null;
  8277. this.clearInterval();
  8278. this.clearNextTick();
  8279. this.state = State.STOPPED;
  8280. }
  8281. get startPositionValue() {
  8282. const {
  8283. nextLoadPosition,
  8284. startPosition
  8285. } = this;
  8286. if (startPosition === -1 && nextLoadPosition) {
  8287. return nextLoadPosition;
  8288. }
  8289. return startPosition;
  8290. }
  8291. get bufferingEnabled() {
  8292. return this.buffering;
  8293. }
  8294. pauseBuffering() {
  8295. this.buffering = false;
  8296. }
  8297. resumeBuffering() {
  8298. this.buffering = true;
  8299. }
  8300. get inFlightFrag() {
  8301. return {
  8302. frag: this.fragCurrent,
  8303. state: this.state
  8304. };
  8305. }
  8306. _streamEnded(bufferInfo, levelDetails) {
  8307. // Stream is never "ended" when playlist is live or media is detached
  8308. if (levelDetails.live || !this.media) {
  8309. return false;
  8310. }
  8311. // Stream is not "ended" when nothing is buffered past the start
  8312. const bufferEnd = bufferInfo.end || 0;
  8313. const timelineStart = this.config.timelineOffset || 0;
  8314. if (bufferEnd <= timelineStart) {
  8315. return false;
  8316. }
  8317. // Stream is not "ended" when there is a second buffered range starting before the end of the playlist
  8318. const bufferedRanges = bufferInfo.buffered;
  8319. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  8320. // make sure bufferInfo accounts for any gaps
  8321. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  8322. }
  8323. const nextStart = bufferInfo.nextStart;
  8324. const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  8325. if (hasSecondBufferedRange) {
  8326. return false;
  8327. }
  8328. // Playhead is in unbuffered region. Marking EoS now could result in Safari failing to dispatch "ended" event following seek on start.
  8329. if (this.media.currentTime < bufferInfo.start) {
  8330. return false;
  8331. }
  8332. const partList = levelDetails.partList;
  8333. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  8334. // check instead if the last part is buffered.
  8335. if (partList != null && partList.length) {
  8336. const lastPart = partList[partList.length - 1];
  8337. // Checking the midpoint of the part for potential margin of error and related issues.
  8338. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  8339. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  8340. // part mismatches for independent audio and video playlists/segments.
  8341. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  8342. return lastPartBuffered;
  8343. }
  8344. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  8345. return this.fragmentTracker.isEndListAppended(playlistType);
  8346. }
  8347. getLevelDetails() {
  8348. if (this.levels && this.levelLastLoaded !== null) {
  8349. var _this$levelLastLoaded;
  8350. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  8351. }
  8352. }
  8353. get timelineOffset() {
  8354. const configuredTimelineOffset = this.config.timelineOffset;
  8355. if (configuredTimelineOffset) {
  8356. var _this$getLevelDetails;
  8357. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  8358. }
  8359. return 0;
  8360. }
  8361. onMediaAttached(event, data) {
  8362. const media = this.media = this.mediaBuffer = data.media;
  8363. media.removeEventListener('seeking', this.onMediaSeeking);
  8364. media.removeEventListener('ended', this.onMediaEnded);
  8365. media.addEventListener('seeking', this.onMediaSeeking);
  8366. media.addEventListener('ended', this.onMediaEnded);
  8367. const config = this.config;
  8368. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  8369. this.startLoad(config.startPosition);
  8370. }
  8371. }
  8372. onMediaDetaching(event, data) {
  8373. const transferringMedia = !!data.transferMedia;
  8374. const media = this.media;
  8375. if (media === null) {
  8376. return;
  8377. }
  8378. if (media.ended) {
  8379. this.log('MSE detaching and video ended, reset startPosition');
  8380. this.startPosition = this.lastCurrentTime = 0;
  8381. }
  8382. // remove video listeners
  8383. media.removeEventListener('seeking', this.onMediaSeeking);
  8384. media.removeEventListener('ended', this.onMediaEnded);
  8385. if (this.keyLoader && !transferringMedia) {
  8386. this.keyLoader.detach();
  8387. }
  8388. this.media = this.mediaBuffer = null;
  8389. this.loopSn = undefined;
  8390. if (transferringMedia) {
  8391. this.resetLoadingState();
  8392. this.resetTransmuxer();
  8393. return;
  8394. }
  8395. this.loadingParts = false;
  8396. this.fragmentTracker.removeAllFragments();
  8397. this.stopLoad();
  8398. }
  8399. onManifestLoading() {
  8400. this.initPTS = [];
  8401. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  8402. this.lastCurrentTime = this.startPosition = 0;
  8403. this.startFragRequested = false;
  8404. }
  8405. onError(event, data) {}
  8406. onManifestLoaded(event, data) {
  8407. this.startTimeOffset = data.startTimeOffset;
  8408. }
  8409. onHandlerDestroying() {
  8410. this.stopLoad();
  8411. if (this.transmuxer) {
  8412. this.transmuxer.destroy();
  8413. this.transmuxer = null;
  8414. }
  8415. super.onHandlerDestroying();
  8416. // @ts-ignore
  8417. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  8418. }
  8419. onHandlerDestroyed() {
  8420. this.state = State.STOPPED;
  8421. if (this.fragmentLoader) {
  8422. this.fragmentLoader.destroy();
  8423. }
  8424. if (this.keyLoader) {
  8425. this.keyLoader.destroy();
  8426. }
  8427. if (this.decrypter) {
  8428. this.decrypter.destroy();
  8429. }
  8430. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  8431. super.onHandlerDestroyed();
  8432. }
  8433. loadFragment(frag, level, targetBufferTime) {
  8434. this.startFragRequested = true;
  8435. this._loadFragForPlayback(frag, level, targetBufferTime);
  8436. }
  8437. _loadFragForPlayback(fragment, level, targetBufferTime) {
  8438. const progressCallback = data => {
  8439. const frag = data.frag;
  8440. if (this.fragContextChanged(frag)) {
  8441. this.warn(`${frag.type} sn: ${frag.sn}${data.part ? ' part: ' + data.part.index : ''} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);
  8442. this.fragmentTracker.removeFragment(frag);
  8443. return;
  8444. }
  8445. frag.stats.chunkCount++;
  8446. this._handleFragmentLoadProgress(data);
  8447. };
  8448. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then(data => {
  8449. if (!data) {
  8450. // if we're here we probably needed to backtrack or are waiting for more parts
  8451. return;
  8452. }
  8453. const state = this.state;
  8454. const frag = data.frag;
  8455. if (this.fragContextChanged(frag)) {
  8456. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  8457. this.fragmentTracker.removeFragment(frag);
  8458. this.state = State.IDLE;
  8459. }
  8460. return;
  8461. }
  8462. if ('payload' in data) {
  8463. this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);
  8464. this.hls.trigger(Events.FRAG_LOADED, data);
  8465. }
  8466. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  8467. this._handleFragmentLoadComplete(data);
  8468. }).catch(reason => {
  8469. if (this.state === State.STOPPED || this.state === State.ERROR) {
  8470. return;
  8471. }
  8472. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  8473. this.resetFragmentLoading(fragment);
  8474. });
  8475. }
  8476. clearTrackerIfNeeded(frag) {
  8477. var _this$mediaBuffer;
  8478. const {
  8479. fragmentTracker
  8480. } = this;
  8481. const fragState = fragmentTracker.getState(frag);
  8482. if (fragState === FragmentState.APPENDING) {
  8483. // Lower the max buffer length and try again
  8484. const playlistType = frag.type;
  8485. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  8486. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  8487. // If backtracking, always remove from the tracker without reducing max buffer length
  8488. const backtrackFragment = this.backtrackFragment;
  8489. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  8490. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  8491. fragmentTracker.removeFragment(frag);
  8492. }
  8493. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  8494. // Stop gap for bad tracker / buffer flush behavior
  8495. fragmentTracker.removeAllFragments();
  8496. } else if (fragmentTracker.hasParts(frag.type)) {
  8497. // In low latency mode, remove fragments for which only some parts were buffered
  8498. fragmentTracker.detectPartialFragments({
  8499. frag,
  8500. part: null,
  8501. stats: frag.stats,
  8502. id: frag.type
  8503. });
  8504. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  8505. fragmentTracker.removeFragment(frag);
  8506. }
  8507. }
  8508. }
  8509. checkLiveUpdate(details) {
  8510. if (details.updated && !details.live) {
  8511. // Live stream ended, update fragment tracker
  8512. const lastFragment = details.fragments[details.fragments.length - 1];
  8513. this.fragmentTracker.detectPartialFragments({
  8514. frag: lastFragment,
  8515. part: null,
  8516. stats: lastFragment.stats,
  8517. id: lastFragment.type
  8518. });
  8519. }
  8520. if (!details.fragments[0]) {
  8521. details.deltaUpdateFailed = true;
  8522. }
  8523. }
  8524. waitForLive(levelInfo) {
  8525. const details = levelInfo.details;
  8526. return (details == null ? void 0 : details.live) && details.type !== 'EVENT' && (this.levelLastLoaded !== levelInfo || details.expired);
  8527. }
  8528. flushMainBuffer(startOffset, endOffset, type = null) {
  8529. if (!(startOffset - endOffset)) {
  8530. return;
  8531. }
  8532. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  8533. // passing a null type flushes both buffers
  8534. const flushScope = {
  8535. startOffset,
  8536. endOffset,
  8537. type
  8538. };
  8539. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  8540. }
  8541. _loadInitSegment(fragment, level) {
  8542. this._doFragLoad(fragment, level).then(data => {
  8543. const frag = data == null ? void 0 : data.frag;
  8544. if (!frag || this.fragContextChanged(frag) || !this.levels) {
  8545. throw new Error('init load aborted');
  8546. }
  8547. return data;
  8548. }).then(data => {
  8549. const {
  8550. hls
  8551. } = this;
  8552. const {
  8553. frag,
  8554. payload
  8555. } = data;
  8556. const decryptData = frag.decryptdata;
  8557. // check to see if the payload needs to be decrypted
  8558. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  8559. const startTime = self.performance.now();
  8560. // decrypt init segment data
  8561. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(err => {
  8562. hls.trigger(Events.ERROR, {
  8563. type: ErrorTypes.MEDIA_ERROR,
  8564. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  8565. fatal: false,
  8566. error: err,
  8567. reason: err.message,
  8568. frag
  8569. });
  8570. throw err;
  8571. }).then(decryptedData => {
  8572. const endTime = self.performance.now();
  8573. hls.trigger(Events.FRAG_DECRYPTED, {
  8574. frag,
  8575. payload: decryptedData,
  8576. stats: {
  8577. tstart: startTime,
  8578. tdecrypt: endTime
  8579. }
  8580. });
  8581. data.payload = decryptedData;
  8582. return this.completeInitSegmentLoad(data);
  8583. });
  8584. }
  8585. return this.completeInitSegmentLoad(data);
  8586. }).catch(reason => {
  8587. if (this.state === State.STOPPED || this.state === State.ERROR) {
  8588. return;
  8589. }
  8590. this.warn(reason);
  8591. this.resetFragmentLoading(fragment);
  8592. });
  8593. }
  8594. completeInitSegmentLoad(data) {
  8595. const {
  8596. levels
  8597. } = this;
  8598. if (!levels) {
  8599. throw new Error('init load aborted, missing levels');
  8600. }
  8601. const stats = data.frag.stats;
  8602. if (this.state !== State.STOPPED) {
  8603. this.state = State.IDLE;
  8604. }
  8605. data.frag.data = new Uint8Array(data.payload);
  8606. stats.parsing.start = stats.buffering.start = self.performance.now();
  8607. stats.parsing.end = stats.buffering.end = self.performance.now();
  8608. this.tick();
  8609. }
  8610. fragContextChanged(frag) {
  8611. const {
  8612. fragCurrent
  8613. } = this;
  8614. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  8615. }
  8616. fragBufferedComplete(frag, part) {
  8617. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8618. this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.fragInfo(frag, false, part)} > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)'})`);
  8619. if (isMediaFragment(frag)) {
  8620. var _this$levels;
  8621. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  8622. const el = frag.elementaryStreams;
  8623. if (!Object.keys(el).some(type => !!el[type])) {
  8624. // empty segment
  8625. this.state = State.IDLE;
  8626. return;
  8627. }
  8628. }
  8629. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  8630. if (level != null && level.fragmentError) {
  8631. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  8632. level.fragmentError = 0;
  8633. }
  8634. }
  8635. this.state = State.IDLE;
  8636. }
  8637. _handleFragmentLoadComplete(fragLoadedEndData) {
  8638. const {
  8639. transmuxer
  8640. } = this;
  8641. if (!transmuxer) {
  8642. return;
  8643. }
  8644. const {
  8645. frag,
  8646. part,
  8647. partsLoaded
  8648. } = fragLoadedEndData;
  8649. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  8650. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);
  8651. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  8652. transmuxer.flush(chunkMeta);
  8653. }
  8654. _handleFragmentLoadProgress(frag) {}
  8655. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  8656. var _frag$decryptdata;
  8657. this.fragCurrent = frag;
  8658. const details = level == null ? void 0 : level.details;
  8659. if (!this.levels || !details) {
  8660. throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);
  8661. }
  8662. let keyLoadingPromise = null;
  8663. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  8664. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);
  8665. this.state = State.KEY_LOADING;
  8666. this.fragCurrent = frag;
  8667. keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {
  8668. if (!this.fragContextChanged(keyLoadedData.frag)) {
  8669. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  8670. if (this.state === State.KEY_LOADING) {
  8671. this.state = State.IDLE;
  8672. }
  8673. return keyLoadedData;
  8674. }
  8675. });
  8676. this.hls.trigger(Events.KEY_LOADING, {
  8677. frag
  8678. });
  8679. if (this.fragCurrent === null) {
  8680. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  8681. }
  8682. } else if (!frag.encrypted) {
  8683. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  8684. if (keyLoadingPromise) {
  8685. this.log(`[eme] blocking frag load until media-keys acquired`);
  8686. }
  8687. }
  8688. const fragPrevious = this.fragPrevious;
  8689. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  8690. const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  8691. if (shouldLoadParts !== this.loadingParts) {
  8692. this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);
  8693. this.loadingParts = shouldLoadParts;
  8694. }
  8695. }
  8696. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  8697. if (this.loadingParts && isMediaFragment(frag)) {
  8698. const partList = details.partList;
  8699. if (partList && progressCallback) {
  8700. if (targetBufferTime > frag.end && details.fragmentHint) {
  8701. frag = details.fragmentHint;
  8702. }
  8703. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  8704. if (partIndex > -1) {
  8705. const part = partList[partIndex];
  8706. frag = this.fragCurrent = part.fragment;
  8707. this.log(`Loading ${frag.type} sn: ${frag.sn} part: ${part.index} (${partIndex}/${partList.length - 1}) of ${this.fragInfo(frag, false, part)}) cc: ${frag.cc} [${details.startSN}-${details.endSN}], target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  8708. this.nextLoadPosition = part.start + part.duration;
  8709. this.state = State.FRAG_LOADING;
  8710. let _result;
  8711. if (keyLoadingPromise) {
  8712. _result = keyLoadingPromise.then(keyLoadedData => {
  8713. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  8714. return null;
  8715. }
  8716. return this.doFragPartsLoad(frag, part, level, progressCallback);
  8717. }).catch(error => this.handleFragLoadError(error));
  8718. } else {
  8719. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));
  8720. }
  8721. this.hls.trigger(Events.FRAG_LOADING, {
  8722. frag,
  8723. part,
  8724. targetBufferTime
  8725. });
  8726. if (this.fragCurrent === null) {
  8727. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  8728. }
  8729. return _result;
  8730. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  8731. // Fragment hint has no parts
  8732. return Promise.resolve(null);
  8733. }
  8734. }
  8735. }
  8736. if (isMediaFragment(frag) && this.loadingParts) {
  8737. this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);
  8738. this.loadingParts = false;
  8739. } else if (!frag.url) {
  8740. // Selected fragment hint for part but not loading parts
  8741. return Promise.resolve(null);
  8742. }
  8743. this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? '[' + details.startSN + '-' + details.endSN + ']' : ''}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  8744. // Don't update nextLoadPosition for fragments which are not buffered
  8745. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  8746. this.nextLoadPosition = frag.start + frag.duration;
  8747. }
  8748. this.state = State.FRAG_LOADING;
  8749. // Load key before streaming fragment data
  8750. const dataOnProgress = this.config.progressive;
  8751. let result;
  8752. if (dataOnProgress && keyLoadingPromise) {
  8753. result = keyLoadingPromise.then(keyLoadedData => {
  8754. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  8755. return null;
  8756. }
  8757. return this.fragmentLoader.load(frag, progressCallback);
  8758. }).catch(error => this.handleFragLoadError(error));
  8759. } else {
  8760. // load unencrypted fragment data with progress event,
  8761. // or handle fragment result after key and fragment are finished loading
  8762. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {
  8763. if (!dataOnProgress && fragLoadedData && progressCallback) {
  8764. progressCallback(fragLoadedData);
  8765. }
  8766. return fragLoadedData;
  8767. }).catch(error => this.handleFragLoadError(error));
  8768. }
  8769. this.hls.trigger(Events.FRAG_LOADING, {
  8770. frag,
  8771. targetBufferTime
  8772. });
  8773. if (this.fragCurrent === null) {
  8774. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  8775. }
  8776. return result;
  8777. }
  8778. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  8779. return new Promise((resolve, reject) => {
  8780. var _level$details;
  8781. const partsLoaded = [];
  8782. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  8783. const loadPart = part => {
  8784. this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {
  8785. partsLoaded[part.index] = partLoadedData;
  8786. const loadedPart = partLoadedData.part;
  8787. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  8788. const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  8789. if (nextPart) {
  8790. loadPart(nextPart);
  8791. } else {
  8792. return resolve({
  8793. frag,
  8794. part: loadedPart,
  8795. partsLoaded
  8796. });
  8797. }
  8798. }).catch(reject);
  8799. };
  8800. loadPart(fromPart);
  8801. });
  8802. }
  8803. handleFragLoadError(error) {
  8804. if ('data' in error) {
  8805. const data = error.data;
  8806. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  8807. this.handleFragLoadAborted(data.frag, data.part);
  8808. } else {
  8809. this.hls.trigger(Events.ERROR, data);
  8810. }
  8811. } else {
  8812. this.hls.trigger(Events.ERROR, {
  8813. type: ErrorTypes.OTHER_ERROR,
  8814. details: ErrorDetails.INTERNAL_EXCEPTION,
  8815. err: error,
  8816. error,
  8817. fatal: true
  8818. });
  8819. }
  8820. return null;
  8821. }
  8822. _handleTransmuxerFlush(chunkMeta) {
  8823. const context = this.getCurrentContext(chunkMeta);
  8824. if (!context || this.state !== State.PARSING) {
  8825. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  8826. this.state = State.IDLE;
  8827. }
  8828. return;
  8829. }
  8830. const {
  8831. frag,
  8832. part,
  8833. level
  8834. } = context;
  8835. const now = self.performance.now();
  8836. frag.stats.parsing.end = now;
  8837. if (part) {
  8838. part.stats.parsing.end = now;
  8839. }
  8840. // See if part loading should be disabled/enabled based on buffer and playback position.
  8841. const levelDetails = this.getLevelDetails();
  8842. const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  8843. const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  8844. if (shouldLoadParts !== this.loadingParts) {
  8845. this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} after parsing segment ending @${frag.end.toFixed(2)}`);
  8846. this.loadingParts = shouldLoadParts;
  8847. }
  8848. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  8849. }
  8850. shouldLoadParts(details, bufferEnd) {
  8851. if (this.config.lowLatencyMode) {
  8852. if (!details) {
  8853. return this.loadingParts;
  8854. }
  8855. if (details != null && details.partList) {
  8856. var _details$fragmentHint;
  8857. // Buffer must be ahead of first part + duration of parts after last segment
  8858. // and playback must be at or past segment adjacent to part list
  8859. const firstPart = details.partList[0];
  8860. const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  8861. if (bufferEnd >= safePartStart) {
  8862. var _this$media;
  8863. const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  8864. if (playhead > firstPart.start - firstPart.fragment.duration) {
  8865. return true;
  8866. }
  8867. }
  8868. }
  8869. }
  8870. return false;
  8871. }
  8872. getCurrentContext(chunkMeta) {
  8873. const {
  8874. levels,
  8875. fragCurrent
  8876. } = this;
  8877. const {
  8878. level: levelIndex,
  8879. sn,
  8880. part: partIndex
  8881. } = chunkMeta;
  8882. if (!(levels != null && levels[levelIndex])) {
  8883. this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);
  8884. return null;
  8885. }
  8886. const level = levels[levelIndex];
  8887. const levelDetails = level.details;
  8888. const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  8889. const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  8890. if (!frag) {
  8891. return null;
  8892. }
  8893. if (fragCurrent && fragCurrent !== frag) {
  8894. frag.stats = fragCurrent.stats;
  8895. }
  8896. return {
  8897. frag,
  8898. part,
  8899. level
  8900. };
  8901. }
  8902. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  8903. var _buffer;
  8904. if (!data || this.state !== State.PARSING) {
  8905. return;
  8906. }
  8907. const {
  8908. data1,
  8909. data2
  8910. } = data;
  8911. let buffer = data1;
  8912. if (data1 && data2) {
  8913. // Combine the moof + mdat so that we buffer with a single append
  8914. buffer = appendUint8Array(data1, data2);
  8915. }
  8916. if (!((_buffer = buffer) != null && _buffer.length)) {
  8917. return;
  8918. }
  8919. const offsetTimestamp = this.initPTS[frag.cc];
  8920. const offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : undefined;
  8921. const segment = {
  8922. type: data.type,
  8923. frag,
  8924. part,
  8925. chunkMeta,
  8926. offset,
  8927. parent: frag.type,
  8928. data: buffer
  8929. };
  8930. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  8931. if (data.dropped && data.independent && !part) {
  8932. if (noBacktracking) {
  8933. return;
  8934. }
  8935. // Clear buffer so that we reload previous segments sequentially if required
  8936. this.flushBufferGap(frag);
  8937. }
  8938. }
  8939. flushBufferGap(frag) {
  8940. const media = this.media;
  8941. if (!media) {
  8942. return;
  8943. }
  8944. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  8945. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  8946. this.flushMainBuffer(0, frag.start);
  8947. return;
  8948. }
  8949. // Remove back-buffer without interrupting playback to allow back tracking
  8950. const currentTime = media.currentTime;
  8951. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  8952. const fragDuration = frag.duration;
  8953. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  8954. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  8955. if (frag.start - start > segmentFraction) {
  8956. this.flushMainBuffer(start, frag.start);
  8957. }
  8958. }
  8959. getFwdBufferInfo(bufferable, type) {
  8960. var _this$media2;
  8961. const pos = this.getLoadPosition();
  8962. if (!isFiniteNumber(pos)) {
  8963. return null;
  8964. }
  8965. const backwardSeek = this.lastCurrentTime > pos;
  8966. const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  8967. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  8968. }
  8969. getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  8970. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  8971. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  8972. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  8973. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  8974. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  8975. const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  8976. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  8977. }
  8978. }
  8979. return bufferInfo;
  8980. }
  8981. getMaxBufferLength(levelBitrate) {
  8982. const {
  8983. config
  8984. } = this;
  8985. let maxBufLen;
  8986. if (levelBitrate) {
  8987. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  8988. } else {
  8989. maxBufLen = config.maxBufferLength;
  8990. }
  8991. return Math.min(maxBufLen, config.maxMaxBufferLength);
  8992. }
  8993. reduceMaxBufferLength(threshold, fragDuration) {
  8994. const config = this.config;
  8995. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  8996. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  8997. if (reducedLength >= minLength) {
  8998. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  8999. config.maxMaxBufferLength = reducedLength;
  9000. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  9001. return true;
  9002. }
  9003. return false;
  9004. }
  9005. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  9006. var _this$fragmentTracker;
  9007. const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  9008. if (fragOrPart && 'fragment' in fragOrPart) {
  9009. return fragOrPart.fragment;
  9010. }
  9011. return fragOrPart;
  9012. }
  9013. getNextFragment(pos, levelDetails) {
  9014. const fragments = levelDetails.fragments;
  9015. const fragLen = fragments.length;
  9016. if (!fragLen) {
  9017. return null;
  9018. }
  9019. // find fragment index, contiguous with end of buffer position
  9020. const {
  9021. config
  9022. } = this;
  9023. const start = fragments[0].start;
  9024. const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  9025. let frag = null;
  9026. if (levelDetails.live) {
  9027. const initialLiveManifestSize = config.initialLiveManifestSize;
  9028. if (fragLen < initialLiveManifestSize) {
  9029. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  9030. return null;
  9031. }
  9032. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  9033. // In order to discover the range, we load the best matching fragment for that level and demux it.
  9034. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  9035. // we get the fragment matching that start time
  9036. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  9037. var _frag;
  9038. if (canLoadParts && !this.loadingParts) {
  9039. this.log(`LL-Part loading ON for initial live fragment`);
  9040. this.loadingParts = true;
  9041. }
  9042. frag = this.getInitialLiveFragment(levelDetails);
  9043. const mainStart = this.hls.startPosition;
  9044. const liveSyncPosition = this.hls.liveSyncPosition;
  9045. const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  9046. this.log(`Setting startPosition to ${startPosition} to match start frag at live edge. mainStart: ${mainStart} liveSyncPosition: ${liveSyncPosition} frag.start: ${(_frag = frag) == null ? void 0 : _frag.start}`);
  9047. this.startPosition = this.nextLoadPosition = startPosition;
  9048. }
  9049. } else if (pos <= start) {
  9050. // VoD playlist: if loadPosition before start of playlist, load first fragment
  9051. frag = fragments[0];
  9052. }
  9053. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  9054. if (!frag) {
  9055. const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  9056. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  9057. }
  9058. let programFrag = this.filterReplacedPrimary(frag, levelDetails);
  9059. if (!programFrag && frag) {
  9060. const curSNIdx = frag.sn - levelDetails.startSN;
  9061. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  9062. }
  9063. return this.mapToInitFragWhenRequired(programFrag);
  9064. }
  9065. isLoopLoading(frag, targetBufferTime) {
  9066. const trackerState = this.fragmentTracker.getState(frag);
  9067. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  9068. }
  9069. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  9070. let nextFragment = null;
  9071. if (frag.gap) {
  9072. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  9073. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  9074. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  9075. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  9076. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  9077. // Returning here might result in not finding an audio and video candiate to skip to
  9078. const sn = nextFragment.sn;
  9079. if (this.loopSn !== sn) {
  9080. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${sn}`);
  9081. this.loopSn = sn;
  9082. }
  9083. return null;
  9084. }
  9085. }
  9086. }
  9087. this.loopSn = undefined;
  9088. return nextFragment;
  9089. }
  9090. get primaryPrefetch() {
  9091. if (interstitialsEnabled(this.hls.config)) {
  9092. var _this$hls$interstitia, _this$hls$interstitia2;
  9093. const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;
  9094. if (playingInterstitial) {
  9095. return true;
  9096. }
  9097. }
  9098. return false;
  9099. }
  9100. filterReplacedPrimary(frag, details) {
  9101. if (!frag) {
  9102. return frag;
  9103. }
  9104. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  9105. // Do not load fragments outside the buffering schedule segment
  9106. const interstitials = this.hls.interstitialsManager;
  9107. const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  9108. if (bufferingItem) {
  9109. const bufferingInterstitial = bufferingItem.event;
  9110. if (bufferingInterstitial) {
  9111. // Do not stream fragments while buffering Interstitial Events (except for overlap at the start)
  9112. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  9113. return null;
  9114. }
  9115. } else {
  9116. // Limit fragment loading to media in schedule item
  9117. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  9118. // fragment ends by schedule item start
  9119. // this.fragmentTracker.fragBuffered(frag, true);
  9120. return null;
  9121. }
  9122. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  9123. // fragment is past schedule item end
  9124. // allow some overflow when not appending in place to prevent stalls
  9125. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  9126. return null;
  9127. }
  9128. }
  9129. }
  9130. }
  9131. // Skip loading of fragments that overlap completely with appendInPlace interstitials
  9132. const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  9133. if (playerQueue) {
  9134. for (let i = playerQueue.length; i--;) {
  9135. const interstitial = playerQueue[i].interstitial;
  9136. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  9137. return null;
  9138. }
  9139. }
  9140. }
  9141. }
  9142. return frag;
  9143. }
  9144. mapToInitFragWhenRequired(frag) {
  9145. // If an initSegment is present, it must be buffered first
  9146. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  9147. return frag.initSegment;
  9148. }
  9149. return frag;
  9150. }
  9151. getNextPart(partList, frag, targetBufferTime) {
  9152. let nextPart = -1;
  9153. let contiguous = false;
  9154. let independentAttrOmitted = true;
  9155. for (let i = 0, len = partList.length; i < len; i++) {
  9156. const part = partList[i];
  9157. independentAttrOmitted = independentAttrOmitted && !part.independent;
  9158. if (nextPart > -1 && targetBufferTime < part.start) {
  9159. break;
  9160. }
  9161. const loaded = part.loaded;
  9162. if (loaded) {
  9163. nextPart = -1;
  9164. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  9165. nextPart = i;
  9166. }
  9167. contiguous = loaded;
  9168. }
  9169. return nextPart;
  9170. }
  9171. loadedEndOfParts(partList, targetBufferTime) {
  9172. const lastPart = partList[partList.length - 1];
  9173. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  9174. }
  9175. /*
  9176. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  9177. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  9178. start and end times for each fragment in the playlist (after which this method will not need to be called).
  9179. */
  9180. getInitialLiveFragment(levelDetails) {
  9181. const fragments = levelDetails.fragments;
  9182. const fragPrevious = this.fragPrevious;
  9183. let frag = null;
  9184. if (fragPrevious) {
  9185. if (levelDetails.hasProgramDateTime) {
  9186. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  9187. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  9188. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  9189. }
  9190. if (!frag) {
  9191. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  9192. const targetSN = fragPrevious.sn + 1;
  9193. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  9194. const fragNext = fragments[targetSN - levelDetails.startSN];
  9195. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  9196. if (fragPrevious.cc === fragNext.cc) {
  9197. frag = fragNext;
  9198. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  9199. }
  9200. }
  9201. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  9202. // will have the wrong start times
  9203. if (!frag) {
  9204. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  9205. if (frag) {
  9206. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  9207. }
  9208. }
  9209. }
  9210. } else {
  9211. // Find a new start fragment when fragPrevious is null
  9212. const liveStart = this.hls.liveSyncPosition;
  9213. if (liveStart !== null) {
  9214. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  9215. }
  9216. }
  9217. return frag;
  9218. }
  9219. /*
  9220. This method finds the best matching fragment given the provided position.
  9221. */
  9222. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  9223. const {
  9224. config
  9225. } = this;
  9226. let {
  9227. fragPrevious
  9228. } = this;
  9229. let {
  9230. fragments,
  9231. endSN
  9232. } = levelDetails;
  9233. const {
  9234. fragmentHint
  9235. } = levelDetails;
  9236. const {
  9237. maxFragLookUpTolerance
  9238. } = config;
  9239. const partList = levelDetails.partList;
  9240. const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  9241. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  9242. // Include incomplete fragment with parts at end
  9243. fragments = fragments.concat(fragmentHint);
  9244. endSN = fragmentHint.sn;
  9245. }
  9246. let frag;
  9247. if (bufferEnd < end) {
  9248. var _this$media3;
  9249. const backwardSeek = bufferEnd < this.lastCurrentTime;
  9250. const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  9251. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  9252. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  9253. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  9254. } else {
  9255. // reach end of playlist
  9256. frag = fragments[fragments.length - 1];
  9257. }
  9258. if (frag) {
  9259. const curSNIdx = frag.sn - levelDetails.startSN;
  9260. // Move fragPrevious forward to support forcing the next fragment to load
  9261. // when the buffer catches up to a previously buffered range.
  9262. const fragState = this.fragmentTracker.getState(frag);
  9263. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  9264. fragPrevious = frag;
  9265. }
  9266. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  9267. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  9268. // non-uniform fragment durations
  9269. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  9270. if (sameLevel) {
  9271. const nextFrag = fragments[curSNIdx + 1];
  9272. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  9273. frag = nextFrag;
  9274. } else {
  9275. frag = null;
  9276. }
  9277. }
  9278. }
  9279. }
  9280. return frag;
  9281. }
  9282. alignPlaylists(details, previousDetails, switchDetails) {
  9283. // TODO: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  9284. // this could all go in level-helper mergeDetails()
  9285. const length = details.fragments.length;
  9286. if (!length) {
  9287. this.warn(`No fragments in live playlist`);
  9288. return 0;
  9289. }
  9290. const slidingStart = details.fragmentStart;
  9291. const firstLevelLoad = !previousDetails;
  9292. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  9293. if (firstLevelLoad || !aligned && !slidingStart) {
  9294. alignStream(switchDetails, details);
  9295. const alignedSlidingStart = details.fragmentStart;
  9296. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} fragments: ${length}`);
  9297. return alignedSlidingStart;
  9298. }
  9299. return slidingStart;
  9300. }
  9301. waitForCdnTuneIn(details) {
  9302. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  9303. const advancePartLimit = 3;
  9304. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  9305. }
  9306. setStartPosition(details, sliding) {
  9307. // compute start position if set to -1. use it straight away if value is defined
  9308. let startPosition = this.startPosition;
  9309. if (startPosition < sliding) {
  9310. startPosition = -1;
  9311. }
  9312. const timelineOffset = this.timelineOffset;
  9313. if (startPosition === -1) {
  9314. // Use Playlist EXT-X-START:TIME-OFFSET when set
  9315. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  9316. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  9317. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  9318. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  9319. startPosition = sliding + startTimeOffset;
  9320. if (startTimeOffset < 0) {
  9321. startPosition += details.edge;
  9322. }
  9323. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  9324. this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist`);
  9325. this.startPosition = startPosition;
  9326. } else if (details.live) {
  9327. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  9328. // not been specified via the config or an as an argument to startLoad (#3736).
  9329. startPosition = this.hls.liveSyncPosition || sliding;
  9330. this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);
  9331. this.startPosition = -1;
  9332. } else {
  9333. this.log(`setting startPosition to 0 by default`);
  9334. this.startPosition = startPosition = 0;
  9335. }
  9336. this.lastCurrentTime = startPosition + timelineOffset;
  9337. }
  9338. this.nextLoadPosition = startPosition + timelineOffset;
  9339. }
  9340. getLoadPosition() {
  9341. var _this$hls;
  9342. const {
  9343. media
  9344. } = this;
  9345. // if we have not yet loaded any fragment, start loading from start position
  9346. let pos = 0;
  9347. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  9348. pos = media.currentTime;
  9349. } else if (this.nextLoadPosition >= 0) {
  9350. pos = this.nextLoadPosition;
  9351. }
  9352. return pos;
  9353. }
  9354. handleFragLoadAborted(frag, part) {
  9355. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  9356. this.log(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of ${this.playlistLabel()} ${frag.level} was aborted`);
  9357. this.resetFragmentLoading(frag);
  9358. }
  9359. }
  9360. resetFragmentLoading(frag) {
  9361. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  9362. this.state = State.IDLE;
  9363. }
  9364. }
  9365. onFragmentOrKeyLoadError(filterType, data) {
  9366. if (data.chunkMeta && !data.frag) {
  9367. const context = this.getCurrentContext(data.chunkMeta);
  9368. if (context) {
  9369. data.frag = context.frag;
  9370. }
  9371. }
  9372. const frag = data.frag;
  9373. // Handle frag error related to caller's filterType
  9374. if (!frag || frag.type !== filterType || !this.levels) {
  9375. return;
  9376. }
  9377. if (this.fragContextChanged(frag)) {
  9378. var _this$fragCurrent;
  9379. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);
  9380. return;
  9381. }
  9382. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  9383. if (gapTagEncountered) {
  9384. this.fragmentTracker.fragBuffered(frag, true);
  9385. }
  9386. // keep retrying until the limit will be reached
  9387. const errorAction = data.errorAction;
  9388. const {
  9389. action,
  9390. flags,
  9391. retryCount = 0,
  9392. retryConfig
  9393. } = errorAction || {};
  9394. const couldRetry = !!errorAction && !!retryConfig;
  9395. const retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  9396. const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  9397. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  9398. this.resetFragmentErrors(filterType);
  9399. this.treatAsGap(frag);
  9400. errorAction.resolved = true;
  9401. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  9402. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9403. const delay = getRetryDelay(retryConfig, retryCount);
  9404. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  9405. errorAction.resolved = true;
  9406. this.retryDate = self.performance.now() + delay;
  9407. this.state = State.FRAG_LOADING_WAITING_RETRY;
  9408. } else if (retryConfig && errorAction) {
  9409. this.resetFragmentErrors(filterType);
  9410. if (retryCount < retryConfig.maxNumRetry) {
  9411. // Network retry is skipped when level switch is preferred
  9412. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  9413. errorAction.resolved = true;
  9414. }
  9415. } else {
  9416. this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  9417. return;
  9418. }
  9419. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  9420. this.state = State.WAITING_LEVEL;
  9421. } else {
  9422. this.state = State.ERROR;
  9423. }
  9424. // Perform next async tick sooner to speed up error action resolution
  9425. this.tickImmediate();
  9426. }
  9427. reduceLengthAndFlushBuffer(data) {
  9428. // if in appending state
  9429. if (this.state === State.PARSING || this.state === State.PARSED) {
  9430. const frag = data.frag;
  9431. const playlistType = data.parent;
  9432. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  9433. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  9434. // reduce max buf len if current position is buffered
  9435. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  9436. if (buffered) {
  9437. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  9438. }
  9439. const flushBuffer = !buffered;
  9440. if (flushBuffer) {
  9441. // current position is not buffered, but browser is still complaining about buffer full error
  9442. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  9443. // in that case flush the whole audio buffer to recover
  9444. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  9445. }
  9446. if (frag) {
  9447. this.fragmentTracker.removeFragment(frag);
  9448. this.nextLoadPosition = frag.start;
  9449. }
  9450. this.resetLoadingState();
  9451. return flushBuffer;
  9452. }
  9453. return false;
  9454. }
  9455. resetFragmentErrors(filterType) {
  9456. if (filterType === PlaylistLevelType.AUDIO) {
  9457. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  9458. this.fragCurrent = null;
  9459. }
  9460. // Fragment errors that result in a level switch or redundant fail-over
  9461. // should reset the stream controller state to idle
  9462. if (!this.hls.hasEnoughToStart) {
  9463. this.startFragRequested = false;
  9464. }
  9465. if (this.state !== State.STOPPED) {
  9466. this.state = State.IDLE;
  9467. }
  9468. }
  9469. afterBufferFlushed(media, bufferType, playlistType) {
  9470. if (!media) {
  9471. return;
  9472. }
  9473. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  9474. // (so that we will check against video.buffered ranges in case of alt audio track)
  9475. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  9476. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  9477. if (this.state === State.ENDED) {
  9478. this.resetLoadingState();
  9479. }
  9480. }
  9481. resetLoadingState() {
  9482. this.log('Reset loading state');
  9483. this.fragCurrent = null;
  9484. this.fragPrevious = null;
  9485. if (this.state !== State.STOPPED) {
  9486. this.state = State.IDLE;
  9487. }
  9488. }
  9489. resetStartWhenNotLoaded(level) {
  9490. // if loadedmetadata is not set, it means that first frag request failed
  9491. // in that case, reset startFragRequested flag
  9492. if (!this.hls.hasEnoughToStart) {
  9493. this.startFragRequested = false;
  9494. const details = level ? level.details : null;
  9495. if (details != null && details.live) {
  9496. // Update the start position and return to IDLE to recover live start
  9497. this.log(`resetting startPosition for live start`);
  9498. this.startPosition = -1;
  9499. this.setStartPosition(details, details.fragmentStart);
  9500. this.resetLoadingState();
  9501. } else {
  9502. this.nextLoadPosition = this.startPosition;
  9503. }
  9504. }
  9505. }
  9506. resetWhenMissingContext(chunkMeta) {
  9507. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);
  9508. this.removeUnbufferedFrags();
  9509. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9510. this.resetLoadingState();
  9511. }
  9512. removeUnbufferedFrags(start = 0) {
  9513. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  9514. }
  9515. updateLevelTiming(frag, part, level, partial) {
  9516. const details = level.details;
  9517. if (!details) {
  9518. this.warn('level.details undefined');
  9519. return;
  9520. }
  9521. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  9522. const info = frag.elementaryStreams[type];
  9523. if (info) {
  9524. const parsedDuration = info.endPTS - info.startPTS;
  9525. if (parsedDuration <= 0) {
  9526. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  9527. // The new transmuxer will be configured with a time offset matching the next fragment start,
  9528. // preventing the timeline from shifting.
  9529. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  9530. return result || false;
  9531. }
  9532. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  9533. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  9534. details,
  9535. level,
  9536. drift,
  9537. type,
  9538. frag,
  9539. start: info.startPTS,
  9540. end: info.endPTS
  9541. });
  9542. return true;
  9543. }
  9544. return result;
  9545. }, false);
  9546. if (!parsed) {
  9547. var _this$transmuxer;
  9548. if (level.fragmentError === 0) {
  9549. // Mark and track the odd empty segment as a gap to avoid reloading
  9550. this.treatAsGap(frag, level);
  9551. }
  9552. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  9553. const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);
  9554. this.warn(error.message);
  9555. this.hls.trigger(Events.ERROR, {
  9556. type: ErrorTypes.MEDIA_ERROR,
  9557. details: ErrorDetails.FRAG_PARSING_ERROR,
  9558. fatal: false,
  9559. error,
  9560. frag,
  9561. reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} "${level.url}"`
  9562. });
  9563. if (!this.hls) {
  9564. return;
  9565. }
  9566. this.resetTransmuxer();
  9567. }
  9568. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  9569. }
  9570. this.state = State.PARSED;
  9571. this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.fragInfo(frag, false, part)})`);
  9572. this.hls.trigger(Events.FRAG_PARSED, {
  9573. frag,
  9574. part
  9575. });
  9576. }
  9577. playlistLabel() {
  9578. return this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track';
  9579. }
  9580. fragInfo(frag, pts = true, part) {
  9581. var _ref, _ref2;
  9582. return `${this.playlistLabel()} ${frag.level} (${part ? 'part' : 'frag'}:[${((_ref = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref : NaN).toFixed(3)}-${((_ref2 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref2 : NaN).toFixed(3)}]${part && frag.type === 'main' ? 'INDEPENDENT=' + (part.independent ? 'YES' : 'NO') : ''}`;
  9583. }
  9584. treatAsGap(frag, level) {
  9585. if (level) {
  9586. level.fragmentError++;
  9587. }
  9588. frag.gap = true;
  9589. this.fragmentTracker.removeFragment(frag);
  9590. this.fragmentTracker.fragBuffered(frag, true);
  9591. }
  9592. resetTransmuxer() {
  9593. var _this$transmuxer2;
  9594. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  9595. }
  9596. recoverWorkerError(data) {
  9597. if (data.event === 'demuxerWorker') {
  9598. this.fragmentTracker.removeAllFragments();
  9599. if (this.transmuxer) {
  9600. this.transmuxer.destroy();
  9601. this.transmuxer = null;
  9602. }
  9603. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9604. this.resetLoadingState();
  9605. }
  9606. }
  9607. set state(nextState) {
  9608. const previousState = this._state;
  9609. if (previousState !== nextState) {
  9610. this._state = nextState;
  9611. this.log(`${previousState}->${nextState}`);
  9612. }
  9613. }
  9614. get state() {
  9615. return this._state;
  9616. }
  9617. }
  9618. function interstitialsEnabled(config) {
  9619. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  9620. }
  9621. class ChunkCache {
  9622. constructor() {
  9623. this.chunks = [];
  9624. this.dataLength = 0;
  9625. }
  9626. push(chunk) {
  9627. this.chunks.push(chunk);
  9628. this.dataLength += chunk.length;
  9629. }
  9630. flush() {
  9631. const {
  9632. chunks,
  9633. dataLength
  9634. } = this;
  9635. let result;
  9636. if (!chunks.length) {
  9637. return new Uint8Array(0);
  9638. } else if (chunks.length === 1) {
  9639. result = chunks[0];
  9640. } else {
  9641. result = concatUint8Arrays(chunks, dataLength);
  9642. }
  9643. this.reset();
  9644. return result;
  9645. }
  9646. reset() {
  9647. this.chunks.length = 0;
  9648. this.dataLength = 0;
  9649. }
  9650. }
  9651. function concatUint8Arrays(chunks, dataLength) {
  9652. const result = new Uint8Array(dataLength);
  9653. let offset = 0;
  9654. for (let i = 0; i < chunks.length; i++) {
  9655. const chunk = chunks[i];
  9656. result.set(chunk, offset);
  9657. offset += chunk.length;
  9658. }
  9659. return result;
  9660. }
  9661. var eventemitter3 = {exports: {}};
  9662. var hasRequiredEventemitter3;
  9663. function requireEventemitter3 () {
  9664. if (hasRequiredEventemitter3) return eventemitter3.exports;
  9665. hasRequiredEventemitter3 = 1;
  9666. (function (module) {
  9667. var has = Object.prototype.hasOwnProperty
  9668. , prefix = '~';
  9669. /**
  9670. * Constructor to create a storage for our `EE` objects.
  9671. * An `Events` instance is a plain object whose properties are event names.
  9672. *
  9673. * @constructor
  9674. * @private
  9675. */
  9676. function Events() {}
  9677. //
  9678. // We try to not inherit from `Object.prototype`. In some engines creating an
  9679. // instance in this way is faster than calling `Object.create(null)` directly.
  9680. // If `Object.create(null)` is not supported we prefix the event names with a
  9681. // character to make sure that the built-in object properties are not
  9682. // overridden or used as an attack vector.
  9683. //
  9684. if (Object.create) {
  9685. Events.prototype = Object.create(null);
  9686. //
  9687. // This hack is needed because the `__proto__` property is still inherited in
  9688. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  9689. //
  9690. if (!new Events().__proto__) prefix = false;
  9691. }
  9692. /**
  9693. * Representation of a single event listener.
  9694. *
  9695. * @param {Function} fn The listener function.
  9696. * @param {*} context The context to invoke the listener with.
  9697. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  9698. * @constructor
  9699. * @private
  9700. */
  9701. function EE(fn, context, once) {
  9702. this.fn = fn;
  9703. this.context = context;
  9704. this.once = once || false;
  9705. }
  9706. /**
  9707. * Add a listener for a given event.
  9708. *
  9709. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  9710. * @param {(String|Symbol)} event The event name.
  9711. * @param {Function} fn The listener function.
  9712. * @param {*} context The context to invoke the listener with.
  9713. * @param {Boolean} once Specify if the listener is a one-time listener.
  9714. * @returns {EventEmitter}
  9715. * @private
  9716. */
  9717. function addListener(emitter, event, fn, context, once) {
  9718. if (typeof fn !== 'function') {
  9719. throw new TypeError('The listener must be a function');
  9720. }
  9721. var listener = new EE(fn, context || emitter, once)
  9722. , evt = prefix ? prefix + event : event;
  9723. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  9724. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  9725. else emitter._events[evt] = [emitter._events[evt], listener];
  9726. return emitter;
  9727. }
  9728. /**
  9729. * Clear event by name.
  9730. *
  9731. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  9732. * @param {(String|Symbol)} evt The Event name.
  9733. * @private
  9734. */
  9735. function clearEvent(emitter, evt) {
  9736. if (--emitter._eventsCount === 0) emitter._events = new Events();
  9737. else delete emitter._events[evt];
  9738. }
  9739. /**
  9740. * Minimal `EventEmitter` interface that is molded against the Node.js
  9741. * `EventEmitter` interface.
  9742. *
  9743. * @constructor
  9744. * @public
  9745. */
  9746. function EventEmitter() {
  9747. this._events = new Events();
  9748. this._eventsCount = 0;
  9749. }
  9750. /**
  9751. * Return an array listing the events for which the emitter has registered
  9752. * listeners.
  9753. *
  9754. * @returns {Array}
  9755. * @public
  9756. */
  9757. EventEmitter.prototype.eventNames = function eventNames() {
  9758. var names = []
  9759. , events
  9760. , name;
  9761. if (this._eventsCount === 0) return names;
  9762. for (name in (events = this._events)) {
  9763. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  9764. }
  9765. if (Object.getOwnPropertySymbols) {
  9766. return names.concat(Object.getOwnPropertySymbols(events));
  9767. }
  9768. return names;
  9769. };
  9770. /**
  9771. * Return the listeners registered for a given event.
  9772. *
  9773. * @param {(String|Symbol)} event The event name.
  9774. * @returns {Array} The registered listeners.
  9775. * @public
  9776. */
  9777. EventEmitter.prototype.listeners = function listeners(event) {
  9778. var evt = prefix ? prefix + event : event
  9779. , handlers = this._events[evt];
  9780. if (!handlers) return [];
  9781. if (handlers.fn) return [handlers.fn];
  9782. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  9783. ee[i] = handlers[i].fn;
  9784. }
  9785. return ee;
  9786. };
  9787. /**
  9788. * Return the number of listeners listening to a given event.
  9789. *
  9790. * @param {(String|Symbol)} event The event name.
  9791. * @returns {Number} The number of listeners.
  9792. * @public
  9793. */
  9794. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  9795. var evt = prefix ? prefix + event : event
  9796. , listeners = this._events[evt];
  9797. if (!listeners) return 0;
  9798. if (listeners.fn) return 1;
  9799. return listeners.length;
  9800. };
  9801. /**
  9802. * Calls each of the listeners registered for a given event.
  9803. *
  9804. * @param {(String|Symbol)} event The event name.
  9805. * @returns {Boolean} `true` if the event had listeners, else `false`.
  9806. * @public
  9807. */
  9808. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  9809. var evt = prefix ? prefix + event : event;
  9810. if (!this._events[evt]) return false;
  9811. var listeners = this._events[evt]
  9812. , len = arguments.length
  9813. , args
  9814. , i;
  9815. if (listeners.fn) {
  9816. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  9817. switch (len) {
  9818. case 1: return listeners.fn.call(listeners.context), true;
  9819. case 2: return listeners.fn.call(listeners.context, a1), true;
  9820. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  9821. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  9822. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  9823. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  9824. }
  9825. for (i = 1, args = new Array(len -1); i < len; i++) {
  9826. args[i - 1] = arguments[i];
  9827. }
  9828. listeners.fn.apply(listeners.context, args);
  9829. } else {
  9830. var length = listeners.length
  9831. , j;
  9832. for (i = 0; i < length; i++) {
  9833. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  9834. switch (len) {
  9835. case 1: listeners[i].fn.call(listeners[i].context); break;
  9836. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  9837. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  9838. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  9839. default:
  9840. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  9841. args[j - 1] = arguments[j];
  9842. }
  9843. listeners[i].fn.apply(listeners[i].context, args);
  9844. }
  9845. }
  9846. }
  9847. return true;
  9848. };
  9849. /**
  9850. * Add a listener for a given event.
  9851. *
  9852. * @param {(String|Symbol)} event The event name.
  9853. * @param {Function} fn The listener function.
  9854. * @param {*} [context=this] The context to invoke the listener with.
  9855. * @returns {EventEmitter} `this`.
  9856. * @public
  9857. */
  9858. EventEmitter.prototype.on = function on(event, fn, context) {
  9859. return addListener(this, event, fn, context, false);
  9860. };
  9861. /**
  9862. * Add a one-time listener for a given event.
  9863. *
  9864. * @param {(String|Symbol)} event The event name.
  9865. * @param {Function} fn The listener function.
  9866. * @param {*} [context=this] The context to invoke the listener with.
  9867. * @returns {EventEmitter} `this`.
  9868. * @public
  9869. */
  9870. EventEmitter.prototype.once = function once(event, fn, context) {
  9871. return addListener(this, event, fn, context, true);
  9872. };
  9873. /**
  9874. * Remove the listeners of a given event.
  9875. *
  9876. * @param {(String|Symbol)} event The event name.
  9877. * @param {Function} fn Only remove the listeners that match this function.
  9878. * @param {*} context Only remove the listeners that have this context.
  9879. * @param {Boolean} once Only remove one-time listeners.
  9880. * @returns {EventEmitter} `this`.
  9881. * @public
  9882. */
  9883. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  9884. var evt = prefix ? prefix + event : event;
  9885. if (!this._events[evt]) return this;
  9886. if (!fn) {
  9887. clearEvent(this, evt);
  9888. return this;
  9889. }
  9890. var listeners = this._events[evt];
  9891. if (listeners.fn) {
  9892. if (
  9893. listeners.fn === fn &&
  9894. (!once || listeners.once) &&
  9895. (!context || listeners.context === context)
  9896. ) {
  9897. clearEvent(this, evt);
  9898. }
  9899. } else {
  9900. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  9901. if (
  9902. listeners[i].fn !== fn ||
  9903. (once && !listeners[i].once) ||
  9904. (context && listeners[i].context !== context)
  9905. ) {
  9906. events.push(listeners[i]);
  9907. }
  9908. }
  9909. //
  9910. // Reset the array, or remove it completely if we have no more listeners.
  9911. //
  9912. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  9913. else clearEvent(this, evt);
  9914. }
  9915. return this;
  9916. };
  9917. /**
  9918. * Remove all listeners, or those of the specified event.
  9919. *
  9920. * @param {(String|Symbol)} [event] The event name.
  9921. * @returns {EventEmitter} `this`.
  9922. * @public
  9923. */
  9924. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  9925. var evt;
  9926. if (event) {
  9927. evt = prefix ? prefix + event : event;
  9928. if (this._events[evt]) clearEvent(this, evt);
  9929. } else {
  9930. this._events = new Events();
  9931. this._eventsCount = 0;
  9932. }
  9933. return this;
  9934. };
  9935. //
  9936. // Alias methods names because people roll like that.
  9937. //
  9938. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  9939. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  9940. //
  9941. // Expose the prefix.
  9942. //
  9943. EventEmitter.prefixed = prefix;
  9944. //
  9945. // Allow `EventEmitter` to be imported as module namespace.
  9946. //
  9947. EventEmitter.EventEmitter = EventEmitter;
  9948. //
  9949. // Expose the module.
  9950. //
  9951. {
  9952. module.exports = EventEmitter;
  9953. }
  9954. } (eventemitter3));
  9955. return eventemitter3.exports;
  9956. }
  9957. var eventemitter3Exports = requireEventemitter3();
  9958. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  9959. const version = "1.6.7";
  9960. // ensure the worker ends up in the bundle
  9961. // If the worker should not be included this gets aliased to empty.js
  9962. const workerStore = {};
  9963. function hasUMDWorker() {
  9964. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  9965. }
  9966. function injectWorker() {
  9967. const workerContext = workerStore[version];
  9968. if (workerContext) {
  9969. workerContext.clientCount++;
  9970. return workerContext;
  9971. }
  9972. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  9973. type: 'text/javascript'
  9974. });
  9975. const objectURL = self.URL.createObjectURL(blob);
  9976. const worker = new self.Worker(objectURL);
  9977. const result = {
  9978. worker,
  9979. objectURL,
  9980. clientCount: 1
  9981. };
  9982. workerStore[version] = result;
  9983. return result;
  9984. }
  9985. function loadWorker(path) {
  9986. const workerContext = workerStore[path];
  9987. if (workerContext) {
  9988. workerContext.clientCount++;
  9989. return workerContext;
  9990. }
  9991. const scriptURL = new self.URL(path, self.location.href).href;
  9992. const worker = new self.Worker(scriptURL);
  9993. const result = {
  9994. worker,
  9995. scriptURL,
  9996. clientCount: 1
  9997. };
  9998. workerStore[path] = result;
  9999. return result;
  10000. }
  10001. function removeWorkerFromStore(path) {
  10002. const workerContext = workerStore[path || version];
  10003. if (workerContext) {
  10004. const clientCount = workerContext.clientCount--;
  10005. if (clientCount === 1) {
  10006. const {
  10007. worker,
  10008. objectURL
  10009. } = workerContext;
  10010. delete workerStore[path || version];
  10011. if (objectURL) {
  10012. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  10013. self.URL.revokeObjectURL(objectURL);
  10014. }
  10015. worker.terminate();
  10016. }
  10017. }
  10018. }
  10019. /**
  10020. * Returns true if an ID3 footer can be found at offset in data
  10021. *
  10022. * @param data - The data to search in
  10023. * @param offset - The offset at which to start searching
  10024. *
  10025. * @returns `true` if an ID3 footer is found
  10026. *
  10027. * @internal
  10028. *
  10029. * @group ID3
  10030. */
  10031. function isId3Footer(data, offset) {
  10032. /*
  10033. * The footer is a copy of the header, but with a different identifier
  10034. */
  10035. if (offset + 10 <= data.length) {
  10036. // look for '3DI' identifier
  10037. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  10038. // check version is within range
  10039. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  10040. // check size is within range
  10041. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  10042. return true;
  10043. }
  10044. }
  10045. }
  10046. }
  10047. return false;
  10048. }
  10049. /**
  10050. * Returns true if an ID3 header can be found at offset in data
  10051. *
  10052. * @param data - The data to search in
  10053. * @param offset - The offset at which to start searching
  10054. *
  10055. * @returns `true` if an ID3 header is found
  10056. *
  10057. * @internal
  10058. *
  10059. * @group ID3
  10060. */
  10061. function isId3Header(data, offset) {
  10062. /*
  10063. * http://id3.org/id3v2.3.0
  10064. * [0] = 'I'
  10065. * [1] = 'D'
  10066. * [2] = '3'
  10067. * [3,4] = {Version}
  10068. * [5] = {Flags}
  10069. * [6-9] = {ID3 Size}
  10070. *
  10071. * An ID3v2 tag can be detected with the following pattern:
  10072. * $49 44 33 yy yy xx zz zz zz zz
  10073. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  10074. */
  10075. if (offset + 10 <= data.length) {
  10076. // look for 'ID3' identifier
  10077. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  10078. // check version is within range
  10079. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  10080. // check size is within range
  10081. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  10082. return true;
  10083. }
  10084. }
  10085. }
  10086. }
  10087. return false;
  10088. }
  10089. /**
  10090. * Read ID3 size
  10091. *
  10092. * @param data - The data to read from
  10093. * @param offset - The offset at which to start reading
  10094. *
  10095. * @returns The size
  10096. *
  10097. * @internal
  10098. *
  10099. * @group ID3
  10100. */
  10101. function readId3Size(data, offset) {
  10102. let size = 0;
  10103. size = (data[offset] & 0x7f) << 21;
  10104. size |= (data[offset + 1] & 0x7f) << 14;
  10105. size |= (data[offset + 2] & 0x7f) << 7;
  10106. size |= data[offset + 3] & 0x7f;
  10107. return size;
  10108. }
  10109. /**
  10110. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  10111. *
  10112. * @param data - The data to search in
  10113. * @param offset - The offset at which to start searching
  10114. *
  10115. * @returns The block of data containing any ID3 tags found
  10116. * or `undefined` if no header is found at the starting offset
  10117. *
  10118. * @internal
  10119. *
  10120. * @group ID3
  10121. */
  10122. function getId3Data(data, offset) {
  10123. const front = offset;
  10124. let length = 0;
  10125. while (isId3Header(data, offset)) {
  10126. // ID3 header is 10 bytes
  10127. length += 10;
  10128. const size = readId3Size(data, offset + 6);
  10129. length += size;
  10130. if (isId3Footer(data, offset + 10)) {
  10131. // ID3 footer is 10 bytes
  10132. length += 10;
  10133. }
  10134. offset += length;
  10135. }
  10136. if (length > 0) {
  10137. return data.subarray(front, front + length);
  10138. }
  10139. return undefined;
  10140. }
  10141. function getAudioConfig(observer, data, offset, manifestCodec) {
  10142. const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  10143. const byte2 = data[offset + 2];
  10144. const adtsSamplingIndex = byte2 >> 2 & 0xf;
  10145. if (adtsSamplingIndex > 12) {
  10146. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  10147. observer.emit(Events.ERROR, Events.ERROR, {
  10148. type: ErrorTypes.MEDIA_ERROR,
  10149. details: ErrorDetails.FRAG_PARSING_ERROR,
  10150. fatal: true,
  10151. error,
  10152. reason: error.message
  10153. });
  10154. return;
  10155. }
  10156. // MPEG-4 Audio Object Type (profile_ObjectType+1)
  10157. const adtsObjectType = (byte2 >> 6 & 0x3) + 1;
  10158. const channelCount = data[offset + 3] >> 6 & 0x3 | (byte2 & 1) << 2;
  10159. const codec = 'mp4a.40.' + adtsObjectType;
  10160. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  10161. ISO/IEC 14496-3 - Table 1.13 — Syntax of AudioSpecificConfig()
  10162. Audio Profile / Audio Object Type
  10163. 0: Null
  10164. 1: AAC Main
  10165. 2: AAC LC (Low Complexity)
  10166. 3: AAC SSR (Scalable Sample Rate)
  10167. 4: AAC LTP (Long Term Prediction)
  10168. 5: SBR (Spectral Band Replication)
  10169. 6: AAC Scalable
  10170. sampling freq
  10171. 0: 96000 Hz
  10172. 1: 88200 Hz
  10173. 2: 64000 Hz
  10174. 3: 48000 Hz
  10175. 4: 44100 Hz
  10176. 5: 32000 Hz
  10177. 6: 24000 Hz
  10178. 7: 22050 Hz
  10179. 8: 16000 Hz
  10180. 9: 12000 Hz
  10181. 10: 11025 Hz
  10182. 11: 8000 Hz
  10183. 12: 7350 Hz
  10184. 13: Reserved
  10185. 14: Reserved
  10186. 15: frequency is written explictly
  10187. Channel Configurations
  10188. These are the channel configurations:
  10189. 0: Defined in AOT Specifc Config
  10190. 1: 1 channel: front-center
  10191. 2: 2 channels: front-left, front-right
  10192. */
  10193. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  10194. const samplerate = adtsSamplingRates[adtsSamplingIndex];
  10195. let aacSampleIndex = adtsSamplingIndex;
  10196. if (adtsObjectType === 5 || adtsObjectType === 29) {
  10197. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10198. // there is a factor 2 between frame sample rate and output sample rate
  10199. // multiply frequency by 2 (see table above, equivalent to substract 3)
  10200. aacSampleIndex -= 3;
  10201. }
  10202. const config = [adtsObjectType << 3 | (aacSampleIndex & 0x0e) >> 1, (aacSampleIndex & 0x01) << 7 | channelCount << 3];
  10203. logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);
  10204. return {
  10205. config,
  10206. samplerate,
  10207. channelCount,
  10208. codec,
  10209. parsedCodec: codec,
  10210. manifestCodec
  10211. };
  10212. }
  10213. function isHeaderPattern$1(data, offset) {
  10214. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  10215. }
  10216. function getHeaderLength(data, offset) {
  10217. return data[offset + 1] & 0x01 ? 7 : 9;
  10218. }
  10219. function getFullFrameLength(data, offset) {
  10220. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  10221. }
  10222. function canGetFrameLength(data, offset) {
  10223. return offset + 5 < data.length;
  10224. }
  10225. function isHeader$1(data, offset) {
  10226. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10227. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10228. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10229. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  10230. }
  10231. function canParse$1(data, offset) {
  10232. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  10233. }
  10234. function probe$1(data, offset) {
  10235. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  10236. // or end of data is reached
  10237. if (isHeader$1(data, offset)) {
  10238. // ADTS header Length
  10239. const headerLength = getHeaderLength(data, offset);
  10240. if (offset + headerLength >= data.length) {
  10241. return false;
  10242. }
  10243. // ADTS frame Length
  10244. const frameLength = getFullFrameLength(data, offset);
  10245. if (frameLength <= headerLength) {
  10246. return false;
  10247. }
  10248. const newOffset = offset + frameLength;
  10249. return newOffset === data.length || isHeader$1(data, newOffset);
  10250. }
  10251. return false;
  10252. }
  10253. function initTrackConfig(track, observer, data, offset, audioCodec) {
  10254. if (!track.samplerate) {
  10255. const config = getAudioConfig(observer, data, offset, audioCodec);
  10256. if (!config) {
  10257. return;
  10258. }
  10259. _extends(track, config);
  10260. }
  10261. }
  10262. function getFrameDuration(samplerate) {
  10263. return 1024 * 90000 / samplerate;
  10264. }
  10265. function parseFrameHeader(data, offset) {
  10266. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  10267. const headerLength = getHeaderLength(data, offset);
  10268. if (offset + headerLength <= data.length) {
  10269. // retrieve frame size
  10270. const frameLength = getFullFrameLength(data, offset) - headerLength;
  10271. if (frameLength > 0) {
  10272. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  10273. return {
  10274. headerLength,
  10275. frameLength
  10276. };
  10277. }
  10278. }
  10279. }
  10280. function appendFrame$2(track, data, offset, pts, frameIndex) {
  10281. const frameDuration = getFrameDuration(track.samplerate);
  10282. const stamp = pts + frameIndex * frameDuration;
  10283. const header = parseFrameHeader(data, offset);
  10284. let unit;
  10285. if (header) {
  10286. const {
  10287. frameLength,
  10288. headerLength
  10289. } = header;
  10290. const _length = headerLength + frameLength;
  10291. const missing = Math.max(0, offset + _length - data.length);
  10292. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  10293. if (missing) {
  10294. unit = new Uint8Array(_length - headerLength);
  10295. unit.set(data.subarray(offset + headerLength, data.length), 0);
  10296. } else {
  10297. unit = data.subarray(offset + headerLength, offset + _length);
  10298. }
  10299. const _sample = {
  10300. unit,
  10301. pts: stamp
  10302. };
  10303. if (!missing) {
  10304. track.samples.push(_sample);
  10305. }
  10306. return {
  10307. sample: _sample,
  10308. length: _length,
  10309. missing
  10310. };
  10311. }
  10312. // overflow incomplete header
  10313. const length = data.length - offset;
  10314. unit = new Uint8Array(length);
  10315. unit.set(data.subarray(offset, data.length), 0);
  10316. const sample = {
  10317. unit,
  10318. pts: stamp
  10319. };
  10320. return {
  10321. sample,
  10322. length,
  10323. missing: -1
  10324. };
  10325. }
  10326. /**
  10327. * Checks if the given data contains an ID3 tag.
  10328. *
  10329. * @param data - The data to check
  10330. * @param offset - The offset at which to start checking
  10331. *
  10332. * @returns `true` if an ID3 tag is found
  10333. *
  10334. * @group ID3
  10335. *
  10336. * @beta
  10337. */
  10338. function canParseId3(data, offset) {
  10339. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  10340. }
  10341. function toArrayBuffer(view) {
  10342. if (view instanceof ArrayBuffer) {
  10343. return view;
  10344. } else {
  10345. if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {
  10346. // This is a TypedArray over the whole buffer.
  10347. return view.buffer;
  10348. }
  10349. // This is a 'view' on the buffer. Create a new buffer that only contains
  10350. // the data. Note that since this isn't an ArrayBuffer, the 'new' call
  10351. // will allocate a new buffer to hold the copy.
  10352. return new Uint8Array(view).buffer;
  10353. }
  10354. }
  10355. function toUint8(data, offset = 0, length = Infinity) {
  10356. return view(data, offset, length, Uint8Array);
  10357. }
  10358. function view(data, offset, length, Type) {
  10359. const buffer = unsafeGetArrayBuffer(data);
  10360. let bytesPerElement = 1;
  10361. if ('BYTES_PER_ELEMENT' in Type) {
  10362. bytesPerElement = Type.BYTES_PER_ELEMENT;
  10363. }
  10364. // Absolute end of the |data| view within |buffer|.
  10365. const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  10366. const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  10367. // Absolute start of the result within |buffer|.
  10368. const rawStart = (dataOffset + offset) / bytesPerElement;
  10369. const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  10370. // Absolute end of the result within |buffer|.
  10371. const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  10372. return new Type(buffer, start, end - start);
  10373. }
  10374. function unsafeGetArrayBuffer(view) {
  10375. if (view instanceof ArrayBuffer) {
  10376. return view;
  10377. } else {
  10378. return view.buffer;
  10379. }
  10380. }
  10381. function isArrayBufferView(obj) {
  10382. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== undefined && obj.byteOffset !== undefined;
  10383. }
  10384. function decodeId3ImageFrame(frame) {
  10385. const metadataFrame = {
  10386. key: frame.type,
  10387. description: '',
  10388. data: '',
  10389. mimeType: null,
  10390. pictureType: null
  10391. };
  10392. const utf8Encoding = 0x03;
  10393. if (frame.size < 2) {
  10394. return undefined;
  10395. }
  10396. if (frame.data[0] !== utf8Encoding) {
  10397. console.log('Ignore frame with unrecognized character ' + 'encoding');
  10398. return undefined;
  10399. }
  10400. const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  10401. if (mimeTypeEndIndex === -1) {
  10402. return undefined;
  10403. }
  10404. const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  10405. const pictureType = frame.data[2 + mimeTypeEndIndex];
  10406. const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  10407. if (descriptionEndIndex === -1) {
  10408. return undefined;
  10409. }
  10410. const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  10411. let data;
  10412. if (mimeType === '-->') {
  10413. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  10414. } else {
  10415. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  10416. }
  10417. metadataFrame.mimeType = mimeType;
  10418. metadataFrame.pictureType = pictureType;
  10419. metadataFrame.description = description;
  10420. metadataFrame.data = data;
  10421. return metadataFrame;
  10422. }
  10423. /**
  10424. * Decode an ID3 PRIV frame.
  10425. *
  10426. * @param frame - the ID3 PRIV frame
  10427. *
  10428. * @returns The decoded ID3 PRIV frame
  10429. *
  10430. * @internal
  10431. *
  10432. * @group ID3
  10433. */
  10434. function decodeId3PrivFrame(frame) {
  10435. /*
  10436. Format: <text string>\0<binary data>
  10437. */
  10438. if (frame.size < 2) {
  10439. return undefined;
  10440. }
  10441. const owner = utf8ArrayToStr(frame.data, true);
  10442. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  10443. return {
  10444. key: frame.type,
  10445. info: owner,
  10446. data: privateData.buffer
  10447. };
  10448. }
  10449. /**
  10450. * Decodes an ID3 text frame
  10451. *
  10452. * @param frame - the ID3 text frame
  10453. *
  10454. * @returns The decoded ID3 text frame
  10455. *
  10456. * @internal
  10457. *
  10458. * @group ID3
  10459. */
  10460. function decodeId3TextFrame(frame) {
  10461. if (frame.size < 2) {
  10462. return undefined;
  10463. }
  10464. if (frame.type === 'TXXX') {
  10465. /*
  10466. Format:
  10467. [0] = {Text Encoding}
  10468. [1-?] = {Description}\0{Value}
  10469. */
  10470. let index = 1;
  10471. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  10472. index += description.length + 1;
  10473. const value = utf8ArrayToStr(frame.data.subarray(index));
  10474. return {
  10475. key: frame.type,
  10476. info: description,
  10477. data: value
  10478. };
  10479. }
  10480. /*
  10481. Format:
  10482. [0] = {Text Encoding}
  10483. [1-?] = {Value}
  10484. */
  10485. const text = utf8ArrayToStr(frame.data.subarray(1));
  10486. return {
  10487. key: frame.type,
  10488. info: '',
  10489. data: text
  10490. };
  10491. }
  10492. /**
  10493. * Decode a URL frame
  10494. *
  10495. * @param frame - the ID3 URL frame
  10496. *
  10497. * @returns The decoded ID3 URL frame
  10498. *
  10499. * @internal
  10500. *
  10501. * @group ID3
  10502. */
  10503. function decodeId3UrlFrame(frame) {
  10504. if (frame.type === 'WXXX') {
  10505. /*
  10506. Format:
  10507. [0] = {Text Encoding}
  10508. [1-?] = {Description}\0{URL}
  10509. */
  10510. if (frame.size < 2) {
  10511. return undefined;
  10512. }
  10513. let index = 1;
  10514. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  10515. index += description.length + 1;
  10516. const value = utf8ArrayToStr(frame.data.subarray(index));
  10517. return {
  10518. key: frame.type,
  10519. info: description,
  10520. data: value
  10521. };
  10522. }
  10523. /*
  10524. Format:
  10525. [0-?] = {URL}
  10526. */
  10527. const url = utf8ArrayToStr(frame.data);
  10528. return {
  10529. key: frame.type,
  10530. info: '',
  10531. data: url
  10532. };
  10533. }
  10534. /**
  10535. * Decode an ID3 frame.
  10536. *
  10537. * @param frame - the ID3 frame
  10538. *
  10539. * @returns The decoded ID3 frame
  10540. *
  10541. * @internal
  10542. *
  10543. * @group ID3
  10544. */
  10545. function decodeId3Frame(frame) {
  10546. if (frame.type === 'PRIV') {
  10547. return decodeId3PrivFrame(frame);
  10548. } else if (frame.type[0] === 'W') {
  10549. return decodeId3UrlFrame(frame);
  10550. } else if (frame.type === 'APIC') {
  10551. return decodeId3ImageFrame(frame);
  10552. }
  10553. return decodeId3TextFrame(frame);
  10554. }
  10555. /**
  10556. * Returns the data of an ID3 frame.
  10557. *
  10558. * @param data - The data to read from
  10559. *
  10560. * @returns The data of the ID3 frame
  10561. *
  10562. * @internal
  10563. *
  10564. * @group ID3
  10565. */
  10566. function getId3FrameData(data) {
  10567. /*
  10568. Frame ID $xx xx xx xx (four characters)
  10569. Size $xx xx xx xx
  10570. Flags $xx xx
  10571. */
  10572. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  10573. const size = readId3Size(data, 4);
  10574. // skip frame id, size, and flags
  10575. const offset = 10;
  10576. return {
  10577. type,
  10578. size,
  10579. data: data.subarray(offset, offset + size)
  10580. };
  10581. }
  10582. const HEADER_FOOTER_SIZE = 10;
  10583. const FRAME_SIZE = 10;
  10584. /**
  10585. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  10586. *
  10587. * @param id3Data - The ID3 data containing one or more ID3 tags
  10588. *
  10589. * @returns Array of ID3 frame objects
  10590. *
  10591. * @group ID3
  10592. *
  10593. * @beta
  10594. */
  10595. function getId3Frames(id3Data) {
  10596. let offset = 0;
  10597. const frames = [];
  10598. while (isId3Header(id3Data, offset)) {
  10599. const size = readId3Size(id3Data, offset + 6);
  10600. if (id3Data[offset + 5] >> 6 & 1) {
  10601. // skip extended header
  10602. offset += HEADER_FOOTER_SIZE;
  10603. }
  10604. // skip past ID3 header
  10605. offset += HEADER_FOOTER_SIZE;
  10606. const end = offset + size;
  10607. // loop through frames in the ID3 tag
  10608. while (offset + FRAME_SIZE < end) {
  10609. const frameData = getId3FrameData(id3Data.subarray(offset));
  10610. const frame = decodeId3Frame(frameData);
  10611. if (frame) {
  10612. frames.push(frame);
  10613. }
  10614. // skip frame header and frame data
  10615. offset += frameData.size + HEADER_FOOTER_SIZE;
  10616. }
  10617. if (isId3Footer(id3Data, offset)) {
  10618. offset += HEADER_FOOTER_SIZE;
  10619. }
  10620. }
  10621. return frames;
  10622. }
  10623. /**
  10624. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  10625. *
  10626. * @param frame - the ID3 frame
  10627. *
  10628. * @returns `true` if the ID3 frame is an Elementary Stream timestamp frame
  10629. *
  10630. * @internal
  10631. *
  10632. * @group ID3
  10633. */
  10634. function isId3TimestampFrame(frame) {
  10635. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  10636. }
  10637. /**
  10638. * Read a 33 bit timestamp from an ID3 frame.
  10639. *
  10640. * @param timeStampFrame - the ID3 frame
  10641. *
  10642. * @returns The timestamp
  10643. *
  10644. * @internal
  10645. *
  10646. * @group ID3
  10647. */
  10648. function readId3Timestamp(timeStampFrame) {
  10649. if (timeStampFrame.data.byteLength === 8) {
  10650. const data = new Uint8Array(timeStampFrame.data);
  10651. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  10652. // with the upper 31 bits set to zero.
  10653. const pts33Bit = data[3] & 0x1;
  10654. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  10655. timestamp /= 45;
  10656. if (pts33Bit) {
  10657. timestamp += 47721858.84;
  10658. } // 2^32 / 90
  10659. return Math.round(timestamp);
  10660. }
  10661. return undefined;
  10662. }
  10663. /**
  10664. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  10665. *
  10666. * @param data - Block of data containing one or more ID3 tags
  10667. *
  10668. * @returns The timestamp
  10669. *
  10670. * @group ID3
  10671. *
  10672. * @beta
  10673. */
  10674. function getId3Timestamp(data) {
  10675. const frames = getId3Frames(data);
  10676. for (let i = 0; i < frames.length; i++) {
  10677. const frame = frames[i];
  10678. if (isId3TimestampFrame(frame)) {
  10679. return readId3Timestamp(frame);
  10680. }
  10681. }
  10682. return undefined;
  10683. }
  10684. let MetadataSchema = /*#__PURE__*/function (MetadataSchema) {
  10685. MetadataSchema["audioId3"] = "org.id3";
  10686. MetadataSchema["dateRange"] = "com.apple.quicktime.HLS";
  10687. MetadataSchema["emsg"] = "https://aomedia.org/emsg/ID3";
  10688. MetadataSchema["misbklv"] = "urn:misb:KLV:bin:1910.1";
  10689. return MetadataSchema;
  10690. }({});
  10691. function dummyTrack(type = '', inputTimeScale = 90000) {
  10692. return {
  10693. type,
  10694. id: -1,
  10695. pid: -1,
  10696. inputTimeScale,
  10697. sequenceNumber: -1,
  10698. samples: [],
  10699. dropped: 0
  10700. };
  10701. }
  10702. class BaseAudioDemuxer {
  10703. constructor() {
  10704. this._audioTrack = void 0;
  10705. this._id3Track = void 0;
  10706. this.frameIndex = 0;
  10707. this.cachedData = null;
  10708. this.basePTS = null;
  10709. this.initPTS = null;
  10710. this.lastPTS = null;
  10711. }
  10712. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10713. this._id3Track = {
  10714. type: 'id3',
  10715. id: 3,
  10716. pid: -1,
  10717. inputTimeScale: 90000,
  10718. sequenceNumber: 0,
  10719. samples: [],
  10720. dropped: 0
  10721. };
  10722. }
  10723. resetTimeStamp(deaultTimestamp) {
  10724. this.initPTS = deaultTimestamp;
  10725. this.resetContiguity();
  10726. }
  10727. resetContiguity() {
  10728. this.basePTS = null;
  10729. this.lastPTS = null;
  10730. this.frameIndex = 0;
  10731. }
  10732. canParse(data, offset) {
  10733. return false;
  10734. }
  10735. appendFrame(track, data, offset) {}
  10736. // feed incoming data to the front of the parsing pipeline
  10737. demux(data, timeOffset) {
  10738. if (this.cachedData) {
  10739. data = appendUint8Array(this.cachedData, data);
  10740. this.cachedData = null;
  10741. }
  10742. let id3Data = getId3Data(data, 0);
  10743. let offset = id3Data ? id3Data.length : 0;
  10744. let lastDataIndex;
  10745. const track = this._audioTrack;
  10746. const id3Track = this._id3Track;
  10747. const timestamp = id3Data ? getId3Timestamp(id3Data) : undefined;
  10748. const length = data.length;
  10749. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  10750. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  10751. this.lastPTS = this.basePTS;
  10752. }
  10753. if (this.lastPTS === null) {
  10754. this.lastPTS = this.basePTS;
  10755. }
  10756. // more expressive than alternative: id3Data?.length
  10757. if (id3Data && id3Data.length > 0) {
  10758. id3Track.samples.push({
  10759. pts: this.lastPTS,
  10760. dts: this.lastPTS,
  10761. data: id3Data,
  10762. type: MetadataSchema.audioId3,
  10763. duration: Number.POSITIVE_INFINITY
  10764. });
  10765. }
  10766. while (offset < length) {
  10767. if (this.canParse(data, offset)) {
  10768. const frame = this.appendFrame(track, data, offset);
  10769. if (frame) {
  10770. this.frameIndex++;
  10771. this.lastPTS = frame.sample.pts;
  10772. offset += frame.length;
  10773. lastDataIndex = offset;
  10774. } else {
  10775. offset = length;
  10776. }
  10777. } else if (canParseId3(data, offset)) {
  10778. // after a canParse, a call to getId3Data *should* always returns some data
  10779. id3Data = getId3Data(data, offset);
  10780. id3Track.samples.push({
  10781. pts: this.lastPTS,
  10782. dts: this.lastPTS,
  10783. data: id3Data,
  10784. type: MetadataSchema.audioId3,
  10785. duration: Number.POSITIVE_INFINITY
  10786. });
  10787. offset += id3Data.length;
  10788. lastDataIndex = offset;
  10789. } else {
  10790. offset++;
  10791. }
  10792. if (offset === length && lastDataIndex !== length) {
  10793. const partialData = data.slice(lastDataIndex);
  10794. if (this.cachedData) {
  10795. this.cachedData = appendUint8Array(this.cachedData, partialData);
  10796. } else {
  10797. this.cachedData = partialData;
  10798. }
  10799. }
  10800. }
  10801. return {
  10802. audioTrack: track,
  10803. videoTrack: dummyTrack(),
  10804. id3Track,
  10805. textTrack: dummyTrack()
  10806. };
  10807. }
  10808. demuxSampleAes(data, keyData, timeOffset) {
  10809. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  10810. }
  10811. flush(timeOffset) {
  10812. // Parse cache in case of remaining frames.
  10813. const cachedData = this.cachedData;
  10814. if (cachedData) {
  10815. this.cachedData = null;
  10816. this.demux(cachedData, 0);
  10817. }
  10818. return {
  10819. audioTrack: this._audioTrack,
  10820. videoTrack: dummyTrack(),
  10821. id3Track: this._id3Track,
  10822. textTrack: dummyTrack()
  10823. };
  10824. }
  10825. destroy() {
  10826. this.cachedData = null;
  10827. // @ts-ignore
  10828. this._audioTrack = this._id3Track = undefined;
  10829. }
  10830. }
  10831. /**
  10832. * Initialize PTS
  10833. * <p>
  10834. * use timestamp unless it is undefined, NaN or Infinity
  10835. * </p>
  10836. */
  10837. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  10838. if (isFiniteNumber(timestamp)) {
  10839. return timestamp * 90;
  10840. }
  10841. const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  10842. return timeOffset * 90000 + init90kHz;
  10843. };
  10844. /**
  10845. * MPEG parser helper
  10846. */
  10847. let chromeVersion$1 = null;
  10848. 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];
  10849. const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  10850. const SamplesCoefficients = [
  10851. // MPEG 2.5
  10852. [0,
  10853. // Reserved
  10854. 72,
  10855. // Layer3
  10856. 144,
  10857. // Layer2
  10858. 12 // Layer1
  10859. ],
  10860. // Reserved
  10861. [0,
  10862. // Reserved
  10863. 0,
  10864. // Layer3
  10865. 0,
  10866. // Layer2
  10867. 0 // Layer1
  10868. ],
  10869. // MPEG 2
  10870. [0,
  10871. // Reserved
  10872. 72,
  10873. // Layer3
  10874. 144,
  10875. // Layer2
  10876. 12 // Layer1
  10877. ],
  10878. // MPEG 1
  10879. [0,
  10880. // Reserved
  10881. 144,
  10882. // Layer3
  10883. 144,
  10884. // Layer2
  10885. 12 // Layer1
  10886. ]];
  10887. const BytesInSlot = [0,
  10888. // Reserved
  10889. 1,
  10890. // Layer3
  10891. 1,
  10892. // Layer2
  10893. 4 // Layer1
  10894. ];
  10895. function appendFrame$1(track, data, offset, pts, frameIndex) {
  10896. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  10897. if (offset + 24 > data.length) {
  10898. return;
  10899. }
  10900. const header = parseHeader(data, offset);
  10901. if (header && offset + header.frameLength <= data.length) {
  10902. const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  10903. const stamp = pts + frameIndex * frameDuration;
  10904. const sample = {
  10905. unit: data.subarray(offset, offset + header.frameLength),
  10906. pts: stamp,
  10907. dts: stamp
  10908. };
  10909. track.config = [];
  10910. track.channelCount = header.channelCount;
  10911. track.samplerate = header.sampleRate;
  10912. track.samples.push(sample);
  10913. return {
  10914. sample,
  10915. length: header.frameLength,
  10916. missing: 0
  10917. };
  10918. }
  10919. }
  10920. function parseHeader(data, offset) {
  10921. const mpegVersion = data[offset + 1] >> 3 & 3;
  10922. const mpegLayer = data[offset + 1] >> 1 & 3;
  10923. const bitRateIndex = data[offset + 2] >> 4 & 15;
  10924. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  10925. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  10926. const paddingBit = data[offset + 2] >> 1 & 1;
  10927. const channelMode = data[offset + 3] >> 6;
  10928. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  10929. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  10930. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  10931. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  10932. const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  10933. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  10934. const bytesInSlot = BytesInSlot[mpegLayer];
  10935. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  10936. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  10937. if (chromeVersion$1 === null) {
  10938. const userAgent = navigator.userAgent || '';
  10939. const result = userAgent.match(/Chrome\/(\d+)/i);
  10940. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  10941. }
  10942. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  10943. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  10944. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  10945. data[offset + 3] = data[offset + 3] | 0x80;
  10946. }
  10947. return {
  10948. sampleRate,
  10949. channelCount,
  10950. frameLength,
  10951. samplesPerFrame
  10952. };
  10953. }
  10954. }
  10955. function isHeaderPattern(data, offset) {
  10956. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  10957. }
  10958. function isHeader(data, offset) {
  10959. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10960. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10961. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10962. return offset + 1 < data.length && isHeaderPattern(data, offset);
  10963. }
  10964. function canParse(data, offset) {
  10965. const headerSize = 4;
  10966. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  10967. }
  10968. function probe(data, offset) {
  10969. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  10970. // or end of data is reached
  10971. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  10972. // MPEG header Length
  10973. const headerLength = 4;
  10974. // MPEG frame Length
  10975. const header = parseHeader(data, offset);
  10976. let frameLength = headerLength;
  10977. if (header != null && header.frameLength) {
  10978. frameLength = header.frameLength;
  10979. }
  10980. const newOffset = offset + frameLength;
  10981. return newOffset === data.length || isHeader(data, newOffset);
  10982. }
  10983. return false;
  10984. }
  10985. /**
  10986. * AAC demuxer
  10987. */
  10988. class AACDemuxer extends BaseAudioDemuxer {
  10989. constructor(observer, config) {
  10990. super();
  10991. this.observer = void 0;
  10992. this.config = void 0;
  10993. this.observer = observer;
  10994. this.config = config;
  10995. }
  10996. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10997. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10998. this._audioTrack = {
  10999. container: 'audio/adts',
  11000. type: 'audio',
  11001. id: 2,
  11002. pid: -1,
  11003. sequenceNumber: 0,
  11004. segmentCodec: 'aac',
  11005. samples: [],
  11006. manifestCodec: audioCodec,
  11007. duration: trackDuration,
  11008. inputTimeScale: 90000,
  11009. dropped: 0
  11010. };
  11011. }
  11012. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  11013. static probe(data, logger) {
  11014. if (!data) {
  11015. return false;
  11016. }
  11017. // Check for the ADTS sync word
  11018. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  11019. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  11020. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  11021. const id3Data = getId3Data(data, 0);
  11022. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  11023. if (probe(data, offset)) {
  11024. return false;
  11025. }
  11026. for (let length = data.length; offset < length; offset++) {
  11027. if (probe$1(data, offset)) {
  11028. logger.log('ADTS sync word found !');
  11029. return true;
  11030. }
  11031. }
  11032. return false;
  11033. }
  11034. canParse(data, offset) {
  11035. return canParse$1(data, offset);
  11036. }
  11037. appendFrame(track, data, offset) {
  11038. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  11039. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  11040. if (frame && frame.missing === 0) {
  11041. return frame;
  11042. }
  11043. }
  11044. }
  11045. const getAudioBSID = (data, offset) => {
  11046. // check the bsid to confirm ac-3 | ec-3
  11047. let bsid = 0;
  11048. let numBits = 5;
  11049. offset += numBits;
  11050. const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  11051. const mask = new Uint32Array(1); // unsigned 32 bit mask value
  11052. const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  11053. while (numBits > 0) {
  11054. byte[0] = data[offset];
  11055. // read remaining bits, upto 8 bits at a time
  11056. const bits = Math.min(numBits, 8);
  11057. const shift = 8 - bits;
  11058. mask[0] = 0xff000000 >>> 24 + shift << shift;
  11059. temp[0] = (byte[0] & mask[0]) >> shift;
  11060. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  11061. offset += 1;
  11062. numBits -= bits;
  11063. }
  11064. return bsid;
  11065. };
  11066. class AC3Demuxer extends BaseAudioDemuxer {
  11067. constructor(observer) {
  11068. super();
  11069. this.observer = void 0;
  11070. this.observer = observer;
  11071. }
  11072. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11073. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  11074. this._audioTrack = {
  11075. container: 'audio/ac-3',
  11076. type: 'audio',
  11077. id: 2,
  11078. pid: -1,
  11079. sequenceNumber: 0,
  11080. segmentCodec: 'ac3',
  11081. samples: [],
  11082. manifestCodec: audioCodec,
  11083. duration: trackDuration,
  11084. inputTimeScale: 90000,
  11085. dropped: 0
  11086. };
  11087. }
  11088. canParse(data, offset) {
  11089. return offset + 64 < data.length;
  11090. }
  11091. appendFrame(track, data, offset) {
  11092. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  11093. if (frameLength !== -1) {
  11094. const sample = track.samples[track.samples.length - 1];
  11095. return {
  11096. sample,
  11097. length: frameLength,
  11098. missing: 0
  11099. };
  11100. }
  11101. }
  11102. static probe(data) {
  11103. if (!data) {
  11104. return false;
  11105. }
  11106. const id3Data = getId3Data(data, 0);
  11107. if (!id3Data) {
  11108. return false;
  11109. }
  11110. // look for the ac-3 sync bytes
  11111. const offset = id3Data.length;
  11112. if (data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  11113. // check the bsid to confirm ac-3
  11114. getAudioBSID(data, offset) < 16) {
  11115. return true;
  11116. }
  11117. return false;
  11118. }
  11119. }
  11120. function appendFrame(track, data, start, pts, frameIndex) {
  11121. if (start + 8 > data.length) {
  11122. return -1; // not enough bytes left
  11123. }
  11124. if (data[start] !== 0x0b || data[start + 1] !== 0x77) {
  11125. return -1; // invalid magic
  11126. }
  11127. // get sample rate
  11128. const samplingRateCode = data[start + 4] >> 6;
  11129. if (samplingRateCode >= 3) {
  11130. return -1; // invalid sampling rate
  11131. }
  11132. const samplingRateMap = [48000, 44100, 32000];
  11133. const sampleRate = samplingRateMap[samplingRateCode];
  11134. // get frame size
  11135. const frameSizeCode = data[start + 4] & 0x3f;
  11136. const frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];
  11137. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  11138. if (start + frameLength > data.length) {
  11139. return -1;
  11140. }
  11141. // get channel count
  11142. const channelMode = data[start + 6] >> 5;
  11143. let skipCount = 0;
  11144. if (channelMode === 2) {
  11145. skipCount += 2;
  11146. } else {
  11147. if (channelMode & 1 && channelMode !== 1) {
  11148. skipCount += 2;
  11149. }
  11150. if (channelMode & 4) {
  11151. skipCount += 2;
  11152. }
  11153. }
  11154. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  11155. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  11156. const channelCount = channelsMap[channelMode] + lfeon;
  11157. // build dac3 box
  11158. const bsid = data[start + 5] >> 3;
  11159. const bsmod = data[start + 5] & 7;
  11160. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 0xe0]);
  11161. const frameDuration = 1536 / sampleRate * 90000;
  11162. const stamp = pts + frameIndex * frameDuration;
  11163. const unit = data.subarray(start, start + frameLength);
  11164. track.config = config;
  11165. track.channelCount = channelCount;
  11166. track.samplerate = sampleRate;
  11167. track.samples.push({
  11168. unit,
  11169. pts: stamp
  11170. });
  11171. return frameLength;
  11172. }
  11173. /**
  11174. * MP3 demuxer
  11175. */
  11176. class MP3Demuxer extends BaseAudioDemuxer {
  11177. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11178. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  11179. this._audioTrack = {
  11180. container: 'audio/mpeg',
  11181. type: 'audio',
  11182. id: 2,
  11183. pid: -1,
  11184. sequenceNumber: 0,
  11185. segmentCodec: 'mp3',
  11186. samples: [],
  11187. manifestCodec: audioCodec,
  11188. duration: trackDuration,
  11189. inputTimeScale: 90000,
  11190. dropped: 0
  11191. };
  11192. }
  11193. static probe(data) {
  11194. if (!data) {
  11195. return false;
  11196. }
  11197. // check if data contains ID3 timestamp and MPEG sync word
  11198. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  11199. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  11200. // More info http://www.mp3-tech.org/programmer/frame_header.html
  11201. const id3Data = getId3Data(data, 0);
  11202. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  11203. // Check for ac-3|ec-3 sync bytes and return false if present
  11204. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  11205. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  11206. getAudioBSID(data, offset) <= 16) {
  11207. return false;
  11208. }
  11209. for (let length = data.length; offset < length; offset++) {
  11210. if (probe(data, offset)) {
  11211. logger.log('MPEG Audio sync word found !');
  11212. return true;
  11213. }
  11214. }
  11215. return false;
  11216. }
  11217. canParse(data, offset) {
  11218. return canParse(data, offset);
  11219. }
  11220. appendFrame(track, data, offset) {
  11221. if (this.basePTS === null) {
  11222. return;
  11223. }
  11224. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  11225. }
  11226. }
  11227. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  11228. class MP4Demuxer {
  11229. constructor(observer, config) {
  11230. this.remainderData = null;
  11231. this.timeOffset = 0;
  11232. this.config = void 0;
  11233. this.videoTrack = void 0;
  11234. this.audioTrack = void 0;
  11235. this.id3Track = void 0;
  11236. this.txtTrack = void 0;
  11237. this.config = config;
  11238. }
  11239. resetTimeStamp() {}
  11240. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11241. const videoTrack = this.videoTrack = dummyTrack('video', 1);
  11242. const audioTrack = this.audioTrack = dummyTrack('audio', 1);
  11243. const captionTrack = this.txtTrack = dummyTrack('text', 1);
  11244. this.id3Track = dummyTrack('id3', 1);
  11245. this.timeOffset = 0;
  11246. if (!(initSegment != null && initSegment.byteLength)) {
  11247. return;
  11248. }
  11249. const initData = parseInitSegment(initSegment);
  11250. if (initData.video) {
  11251. const {
  11252. id,
  11253. timescale,
  11254. codec,
  11255. supplemental
  11256. } = initData.video;
  11257. videoTrack.id = id;
  11258. videoTrack.timescale = captionTrack.timescale = timescale;
  11259. videoTrack.codec = codec;
  11260. videoTrack.supplemental = supplemental;
  11261. }
  11262. if (initData.audio) {
  11263. const {
  11264. id,
  11265. timescale,
  11266. codec
  11267. } = initData.audio;
  11268. audioTrack.id = id;
  11269. audioTrack.timescale = timescale;
  11270. audioTrack.codec = codec;
  11271. }
  11272. captionTrack.id = RemuxerTrackIdConfig.text;
  11273. videoTrack.sampleDuration = 0;
  11274. videoTrack.duration = audioTrack.duration = trackDuration;
  11275. }
  11276. resetContiguity() {
  11277. this.remainderData = null;
  11278. }
  11279. static probe(data) {
  11280. return hasMoofData(data);
  11281. }
  11282. demux(data, timeOffset) {
  11283. this.timeOffset = timeOffset;
  11284. // 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
  11285. let videoSamples = data;
  11286. const videoTrack = this.videoTrack;
  11287. const textTrack = this.txtTrack;
  11288. if (this.config.progressive) {
  11289. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  11290. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  11291. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  11292. if (this.remainderData) {
  11293. videoSamples = appendUint8Array(this.remainderData, data);
  11294. }
  11295. const segmentedData = segmentValidRange(videoSamples);
  11296. this.remainderData = segmentedData.remainder;
  11297. videoTrack.samples = segmentedData.valid || new Uint8Array();
  11298. } else {
  11299. videoTrack.samples = videoSamples;
  11300. }
  11301. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  11302. textTrack.samples = parseSamples(timeOffset, videoTrack);
  11303. return {
  11304. videoTrack,
  11305. audioTrack: this.audioTrack,
  11306. id3Track,
  11307. textTrack: this.txtTrack
  11308. };
  11309. }
  11310. flush() {
  11311. const timeOffset = this.timeOffset;
  11312. const videoTrack = this.videoTrack;
  11313. const textTrack = this.txtTrack;
  11314. videoTrack.samples = this.remainderData || new Uint8Array();
  11315. this.remainderData = null;
  11316. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  11317. textTrack.samples = parseSamples(timeOffset, videoTrack);
  11318. return {
  11319. videoTrack,
  11320. audioTrack: dummyTrack(),
  11321. id3Track,
  11322. textTrack: dummyTrack()
  11323. };
  11324. }
  11325. extractID3Track(videoTrack, timeOffset) {
  11326. const id3Track = this.id3Track;
  11327. if (videoTrack.samples.length) {
  11328. const emsgs = findBox(videoTrack.samples, ['emsg']);
  11329. if (emsgs) {
  11330. emsgs.forEach(data => {
  11331. const emsgInfo = parseEmsg(data);
  11332. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  11333. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  11334. let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  11335. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  11336. if (duration <= 0.001) {
  11337. duration = Number.POSITIVE_INFINITY;
  11338. }
  11339. const payload = emsgInfo.payload;
  11340. id3Track.samples.push({
  11341. data: payload,
  11342. len: payload.byteLength,
  11343. dts: pts,
  11344. pts: pts,
  11345. type: MetadataSchema.emsg,
  11346. duration: duration
  11347. });
  11348. } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith('urn:misb:KLV:bin:1910.1')) {
  11349. const pts = getEmsgStartTime(emsgInfo, timeOffset);
  11350. id3Track.samples.push({
  11351. data: emsgInfo.payload,
  11352. len: emsgInfo.payload.byteLength,
  11353. dts: pts,
  11354. pts: pts,
  11355. type: MetadataSchema.misbklv,
  11356. duration: Number.POSITIVE_INFINITY
  11357. });
  11358. }
  11359. });
  11360. }
  11361. }
  11362. return id3Track;
  11363. }
  11364. demuxSampleAes(data, keyData, timeOffset) {
  11365. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  11366. }
  11367. destroy() {
  11368. // @ts-ignore
  11369. this.config = null;
  11370. this.remainderData = null;
  11371. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = undefined;
  11372. }
  11373. }
  11374. function getEmsgStartTime(emsgInfo, timeOffset) {
  11375. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  11376. }
  11377. /**
  11378. * SAMPLE-AES decrypter
  11379. */
  11380. class SampleAesDecrypter {
  11381. constructor(observer, config, keyData) {
  11382. this.keyData = void 0;
  11383. this.decrypter = void 0;
  11384. this.keyData = keyData;
  11385. this.decrypter = new Decrypter(config, {
  11386. removePKCS7Padding: false
  11387. });
  11388. }
  11389. decryptBuffer(encryptedData) {
  11390. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  11391. }
  11392. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  11393. decryptAacSample(samples, sampleIndex, callback) {
  11394. const curUnit = samples[sampleIndex].unit;
  11395. if (curUnit.length <= 16) {
  11396. // No encrypted portion in this sample (first 16 bytes is not
  11397. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  11398. return;
  11399. }
  11400. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  11401. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  11402. this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {
  11403. const decryptedData = new Uint8Array(decryptedBuffer);
  11404. curUnit.set(decryptedData, 16);
  11405. if (!this.decrypter.isSync()) {
  11406. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  11407. }
  11408. });
  11409. }
  11410. decryptAacSamples(samples, sampleIndex, callback) {
  11411. for (;; sampleIndex++) {
  11412. if (sampleIndex >= samples.length) {
  11413. callback();
  11414. return;
  11415. }
  11416. if (samples[sampleIndex].unit.length < 32) {
  11417. continue;
  11418. }
  11419. this.decryptAacSample(samples, sampleIndex, callback);
  11420. if (!this.decrypter.isSync()) {
  11421. return;
  11422. }
  11423. }
  11424. }
  11425. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  11426. getAvcEncryptedData(decodedData) {
  11427. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  11428. const encryptedData = new Int8Array(encryptedDataLen);
  11429. let outputPos = 0;
  11430. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  11431. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  11432. }
  11433. return encryptedData;
  11434. }
  11435. getAvcDecryptedUnit(decodedData, decryptedData) {
  11436. const uint8DecryptedData = new Uint8Array(decryptedData);
  11437. let inputPos = 0;
  11438. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  11439. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  11440. }
  11441. return decodedData;
  11442. }
  11443. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  11444. const decodedData = discardEPB(curUnit.data);
  11445. const encryptedData = this.getAvcEncryptedData(decodedData);
  11446. this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {
  11447. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  11448. if (!this.decrypter.isSync()) {
  11449. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  11450. }
  11451. });
  11452. }
  11453. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  11454. if (samples instanceof Uint8Array) {
  11455. throw new Error('Cannot decrypt samples of type Uint8Array');
  11456. }
  11457. for (;; sampleIndex++, unitIndex = 0) {
  11458. if (sampleIndex >= samples.length) {
  11459. callback();
  11460. return;
  11461. }
  11462. const curUnits = samples[sampleIndex].units;
  11463. for (;; unitIndex++) {
  11464. if (unitIndex >= curUnits.length) {
  11465. break;
  11466. }
  11467. const curUnit = curUnits[unitIndex];
  11468. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  11469. continue;
  11470. }
  11471. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  11472. if (!this.decrypter.isSync()) {
  11473. return;
  11474. }
  11475. }
  11476. }
  11477. }
  11478. }
  11479. class BaseVideoParser {
  11480. constructor() {
  11481. this.VideoSample = null;
  11482. }
  11483. createVideoSample(key, pts, dts) {
  11484. return {
  11485. key,
  11486. frame: false,
  11487. pts,
  11488. dts,
  11489. units: [],
  11490. length: 0
  11491. };
  11492. }
  11493. getLastNalUnit(samples) {
  11494. var _VideoSample;
  11495. let VideoSample = this.VideoSample;
  11496. let lastUnit;
  11497. // try to fallback to previous sample if current one is empty
  11498. if (!VideoSample || VideoSample.units.length === 0) {
  11499. VideoSample = samples[samples.length - 1];
  11500. }
  11501. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  11502. const units = VideoSample.units;
  11503. lastUnit = units[units.length - 1];
  11504. }
  11505. return lastUnit;
  11506. }
  11507. pushAccessUnit(VideoSample, videoTrack) {
  11508. if (VideoSample.units.length && VideoSample.frame) {
  11509. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  11510. if (VideoSample.pts === undefined) {
  11511. const samples = videoTrack.samples;
  11512. const nbSamples = samples.length;
  11513. if (nbSamples) {
  11514. const lastSample = samples[nbSamples - 1];
  11515. VideoSample.pts = lastSample.pts;
  11516. VideoSample.dts = lastSample.dts;
  11517. } else {
  11518. // dropping samples, no timestamp found
  11519. videoTrack.dropped++;
  11520. return;
  11521. }
  11522. }
  11523. videoTrack.samples.push(VideoSample);
  11524. }
  11525. }
  11526. parseNALu(track, array, endOfSegment) {
  11527. const len = array.byteLength;
  11528. let state = track.naluState || 0;
  11529. const lastState = state;
  11530. const units = [];
  11531. let i = 0;
  11532. let value;
  11533. let overflow;
  11534. let unitType;
  11535. let lastUnitStart = -1;
  11536. let lastUnitType = 0;
  11537. // logger.log('PES:' + Hex.hexDump(array));
  11538. if (state === -1) {
  11539. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  11540. lastUnitStart = 0;
  11541. // NALu type is value read from offset 0
  11542. lastUnitType = this.getNALuType(array, 0);
  11543. state = 0;
  11544. i = 1;
  11545. }
  11546. while (i < len) {
  11547. value = array[i++];
  11548. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  11549. if (!state) {
  11550. state = value ? 0 : 1;
  11551. continue;
  11552. }
  11553. if (state === 1) {
  11554. state = value ? 0 : 2;
  11555. continue;
  11556. }
  11557. // here we have state either equal to 2 or 3
  11558. if (!value) {
  11559. state = 3;
  11560. } else if (value === 1) {
  11561. overflow = i - state - 1;
  11562. if (lastUnitStart >= 0) {
  11563. const unit = {
  11564. data: array.subarray(lastUnitStart, overflow),
  11565. type: lastUnitType
  11566. };
  11567. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  11568. units.push(unit);
  11569. } else {
  11570. // lastUnitStart is undefined => this is the first start code found in this PES packet
  11571. // first check if start code delimiter is overlapping between 2 PES packets,
  11572. // ie it started in last packet (lastState not zero)
  11573. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  11574. const lastUnit = this.getLastNalUnit(track.samples);
  11575. if (lastUnit) {
  11576. if (lastState && i <= 4 - lastState) {
  11577. // start delimiter overlapping between PES packets
  11578. // strip start delimiter bytes from the end of last NAL unit
  11579. // check if lastUnit had a state different from zero
  11580. if (lastUnit.state) {
  11581. // strip last bytes
  11582. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  11583. }
  11584. }
  11585. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  11586. if (overflow > 0) {
  11587. // logger.log('first NALU found with overflow:' + overflow);
  11588. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  11589. lastUnit.state = 0;
  11590. }
  11591. }
  11592. }
  11593. // check if we can read unit type
  11594. if (i < len) {
  11595. unitType = this.getNALuType(array, i);
  11596. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  11597. lastUnitStart = i;
  11598. lastUnitType = unitType;
  11599. state = 0;
  11600. } else {
  11601. // not enough byte to read unit type. let's read it on next PES parsing
  11602. state = -1;
  11603. }
  11604. } else {
  11605. state = 0;
  11606. }
  11607. }
  11608. if (lastUnitStart >= 0 && state >= 0) {
  11609. const unit = {
  11610. data: array.subarray(lastUnitStart, len),
  11611. type: lastUnitType,
  11612. state: state
  11613. };
  11614. units.push(unit);
  11615. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  11616. }
  11617. // no NALu found
  11618. if (units.length === 0) {
  11619. // append pes.data to previous NAL unit
  11620. const lastUnit = this.getLastNalUnit(track.samples);
  11621. if (lastUnit) {
  11622. lastUnit.data = appendUint8Array(lastUnit.data, array);
  11623. }
  11624. }
  11625. track.naluState = state;
  11626. return units;
  11627. }
  11628. }
  11629. /**
  11630. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  11631. */
  11632. class ExpGolomb {
  11633. constructor(data) {
  11634. this.data = void 0;
  11635. this.bytesAvailable = void 0;
  11636. this.word = void 0;
  11637. this.bitsAvailable = void 0;
  11638. this.data = data;
  11639. // the number of bytes left to examine in this.data
  11640. this.bytesAvailable = data.byteLength;
  11641. // the current word being examined
  11642. this.word = 0; // :uint
  11643. // the number of bits left to examine in the current word
  11644. this.bitsAvailable = 0; // :uint
  11645. }
  11646. // ():void
  11647. loadWord() {
  11648. const data = this.data;
  11649. const bytesAvailable = this.bytesAvailable;
  11650. const position = data.byteLength - bytesAvailable;
  11651. const workingBytes = new Uint8Array(4);
  11652. const availableBytes = Math.min(4, bytesAvailable);
  11653. if (availableBytes === 0) {
  11654. throw new Error('no bytes available');
  11655. }
  11656. workingBytes.set(data.subarray(position, position + availableBytes));
  11657. this.word = new DataView(workingBytes.buffer).getUint32(0);
  11658. // track the amount of this.data that has been processed
  11659. this.bitsAvailable = availableBytes * 8;
  11660. this.bytesAvailable -= availableBytes;
  11661. }
  11662. // (count:int):void
  11663. skipBits(count) {
  11664. let skipBytes; // :int
  11665. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  11666. if (this.bitsAvailable > count) {
  11667. this.word <<= count;
  11668. this.bitsAvailable -= count;
  11669. } else {
  11670. count -= this.bitsAvailable;
  11671. skipBytes = count >> 3;
  11672. count -= skipBytes << 3;
  11673. this.bytesAvailable -= skipBytes;
  11674. this.loadWord();
  11675. this.word <<= count;
  11676. this.bitsAvailable -= count;
  11677. }
  11678. }
  11679. // (size:int):uint
  11680. readBits(size) {
  11681. let bits = Math.min(this.bitsAvailable, size); // :uint
  11682. const valu = this.word >>> 32 - bits; // :uint
  11683. if (size > 32) {
  11684. logger.error('Cannot read more than 32 bits at a time');
  11685. }
  11686. this.bitsAvailable -= bits;
  11687. if (this.bitsAvailable > 0) {
  11688. this.word <<= bits;
  11689. } else if (this.bytesAvailable > 0) {
  11690. this.loadWord();
  11691. } else {
  11692. throw new Error('no bits available');
  11693. }
  11694. bits = size - bits;
  11695. if (bits > 0 && this.bitsAvailable) {
  11696. return valu << bits | this.readBits(bits);
  11697. } else {
  11698. return valu;
  11699. }
  11700. }
  11701. // ():uint
  11702. skipLZ() {
  11703. let leadingZeroCount; // :uint
  11704. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  11705. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  11706. // the first bit of working word is 1
  11707. this.word <<= leadingZeroCount;
  11708. this.bitsAvailable -= leadingZeroCount;
  11709. return leadingZeroCount;
  11710. }
  11711. }
  11712. // we exhausted word and still have not found a 1
  11713. this.loadWord();
  11714. return leadingZeroCount + this.skipLZ();
  11715. }
  11716. // ():void
  11717. skipUEG() {
  11718. this.skipBits(1 + this.skipLZ());
  11719. }
  11720. // ():void
  11721. skipEG() {
  11722. this.skipBits(1 + this.skipLZ());
  11723. }
  11724. // ():uint
  11725. readUEG() {
  11726. const clz = this.skipLZ(); // :uint
  11727. return this.readBits(clz + 1) - 1;
  11728. }
  11729. // ():int
  11730. readEG() {
  11731. const valu = this.readUEG(); // :int
  11732. if (0x01 & valu) {
  11733. // the number is odd if the low order bit is set
  11734. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  11735. } else {
  11736. return -1 * (valu >>> 1); // divide by two then make it negative
  11737. }
  11738. }
  11739. // Some convenience functions
  11740. // :Boolean
  11741. readBoolean() {
  11742. return this.readBits(1) === 1;
  11743. }
  11744. // ():int
  11745. readUByte() {
  11746. return this.readBits(8);
  11747. }
  11748. // ():int
  11749. readUShort() {
  11750. return this.readBits(16);
  11751. }
  11752. // ():int
  11753. readUInt() {
  11754. return this.readBits(32);
  11755. }
  11756. }
  11757. class AvcVideoParser extends BaseVideoParser {
  11758. parsePES(track, textTrack, pes, endOfSegment) {
  11759. const units = this.parseNALu(track, pes.data, endOfSegment);
  11760. let VideoSample = this.VideoSample;
  11761. let push;
  11762. let spsfound = false;
  11763. // free pes.data to save up some memory
  11764. pes.data = null;
  11765. // if new NAL units found and last sample still there, let's push ...
  11766. // this helps parsing streams with missing AUD (only do this if AUD never found)
  11767. if (VideoSample && units.length && !track.audFound) {
  11768. this.pushAccessUnit(VideoSample, track);
  11769. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  11770. }
  11771. units.forEach(unit => {
  11772. var _VideoSample2, _VideoSample3;
  11773. switch (unit.type) {
  11774. // NDR
  11775. case 1:
  11776. {
  11777. let iskey = false;
  11778. push = true;
  11779. const data = unit.data;
  11780. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  11781. if (spsfound && data.length > 4) {
  11782. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  11783. const sliceType = this.readSliceType(data);
  11784. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  11785. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  11786. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  11787. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  11788. // if (sliceType === 2 || sliceType === 7) {
  11789. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  11790. iskey = true;
  11791. }
  11792. }
  11793. if (iskey) {
  11794. var _VideoSample;
  11795. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  11796. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  11797. this.pushAccessUnit(VideoSample, track);
  11798. VideoSample = this.VideoSample = null;
  11799. }
  11800. }
  11801. if (!VideoSample) {
  11802. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  11803. }
  11804. VideoSample.frame = true;
  11805. VideoSample.key = iskey;
  11806. break;
  11807. // IDR
  11808. }
  11809. case 5:
  11810. push = true;
  11811. // handle PES not starting with AUD
  11812. // if we have frame data already, that cannot belong to the same frame, so force a push
  11813. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  11814. this.pushAccessUnit(VideoSample, track);
  11815. VideoSample = this.VideoSample = null;
  11816. }
  11817. if (!VideoSample) {
  11818. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  11819. }
  11820. VideoSample.key = true;
  11821. VideoSample.frame = true;
  11822. break;
  11823. // SEI
  11824. case 6:
  11825. {
  11826. push = true;
  11827. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  11828. break;
  11829. // SPS
  11830. }
  11831. case 7:
  11832. {
  11833. var _track$pixelRatio, _track$pixelRatio2;
  11834. push = true;
  11835. spsfound = true;
  11836. const sps = unit.data;
  11837. const config = this.readSPS(sps);
  11838. 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]) {
  11839. track.width = config.width;
  11840. track.height = config.height;
  11841. track.pixelRatio = config.pixelRatio;
  11842. track.sps = [sps];
  11843. const codecarray = sps.subarray(1, 4);
  11844. let codecstring = 'avc1.';
  11845. for (let i = 0; i < 3; i++) {
  11846. let h = codecarray[i].toString(16);
  11847. if (h.length < 2) {
  11848. h = '0' + h;
  11849. }
  11850. codecstring += h;
  11851. }
  11852. track.codec = codecstring;
  11853. }
  11854. break;
  11855. }
  11856. // PPS
  11857. case 8:
  11858. push = true;
  11859. track.pps = [unit.data];
  11860. break;
  11861. // AUD
  11862. case 9:
  11863. push = true;
  11864. track.audFound = true;
  11865. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  11866. this.pushAccessUnit(VideoSample, track);
  11867. VideoSample = null;
  11868. }
  11869. if (!VideoSample) {
  11870. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  11871. }
  11872. break;
  11873. // Filler Data
  11874. case 12:
  11875. push = true;
  11876. break;
  11877. default:
  11878. push = false;
  11879. break;
  11880. }
  11881. if (VideoSample && push) {
  11882. const units = VideoSample.units;
  11883. units.push(unit);
  11884. }
  11885. });
  11886. // if last PES packet, push samples
  11887. if (endOfSegment && VideoSample) {
  11888. this.pushAccessUnit(VideoSample, track);
  11889. this.VideoSample = null;
  11890. }
  11891. }
  11892. getNALuType(data, offset) {
  11893. return data[offset] & 0x1f;
  11894. }
  11895. readSliceType(data) {
  11896. const eg = new ExpGolomb(data);
  11897. // skip NALu type
  11898. eg.readUByte();
  11899. // discard first_mb_in_slice
  11900. eg.readUEG();
  11901. // return slice_type
  11902. return eg.readUEG();
  11903. }
  11904. /**
  11905. * The scaling list is optionally transmitted as part of a sequence parameter
  11906. * set and is not relevant to transmuxing.
  11907. * @param count the number of entries in this scaling list
  11908. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  11909. */
  11910. skipScalingList(count, reader) {
  11911. let lastScale = 8;
  11912. let nextScale = 8;
  11913. let deltaScale;
  11914. for (let j = 0; j < count; j++) {
  11915. if (nextScale !== 0) {
  11916. deltaScale = reader.readEG();
  11917. nextScale = (lastScale + deltaScale + 256) % 256;
  11918. }
  11919. lastScale = nextScale === 0 ? lastScale : nextScale;
  11920. }
  11921. }
  11922. /**
  11923. * Read a sequence parameter set and return some interesting video
  11924. * properties. A sequence parameter set is the H264 metadata that
  11925. * describes the properties of upcoming video frames.
  11926. * @returns an object with configuration parsed from the
  11927. * sequence parameter set, including the dimensions of the
  11928. * associated video frames.
  11929. */
  11930. readSPS(sps) {
  11931. const eg = new ExpGolomb(sps);
  11932. let frameCropLeftOffset = 0;
  11933. let frameCropRightOffset = 0;
  11934. let frameCropTopOffset = 0;
  11935. let frameCropBottomOffset = 0;
  11936. let numRefFramesInPicOrderCntCycle;
  11937. let scalingListCount;
  11938. let i;
  11939. const readUByte = eg.readUByte.bind(eg);
  11940. const readBits = eg.readBits.bind(eg);
  11941. const readUEG = eg.readUEG.bind(eg);
  11942. const readBoolean = eg.readBoolean.bind(eg);
  11943. const skipBits = eg.skipBits.bind(eg);
  11944. const skipEG = eg.skipEG.bind(eg);
  11945. const skipUEG = eg.skipUEG.bind(eg);
  11946. const skipScalingList = this.skipScalingList.bind(this);
  11947. readUByte();
  11948. const profileIdc = readUByte(); // profile_idc
  11949. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  11950. skipBits(3); // reserved_zero_3bits u(3),
  11951. readUByte(); // level_idc u(8)
  11952. skipUEG(); // seq_parameter_set_id
  11953. // some profiles have more optional data we don't need
  11954. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  11955. const chromaFormatIdc = readUEG();
  11956. if (chromaFormatIdc === 3) {
  11957. skipBits(1);
  11958. } // separate_colour_plane_flag
  11959. skipUEG(); // bit_depth_luma_minus8
  11960. skipUEG(); // bit_depth_chroma_minus8
  11961. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  11962. if (readBoolean()) {
  11963. // seq_scaling_matrix_present_flag
  11964. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  11965. for (i = 0; i < scalingListCount; i++) {
  11966. if (readBoolean()) {
  11967. // seq_scaling_list_present_flag[ i ]
  11968. if (i < 6) {
  11969. skipScalingList(16, eg);
  11970. } else {
  11971. skipScalingList(64, eg);
  11972. }
  11973. }
  11974. }
  11975. }
  11976. }
  11977. skipUEG(); // log2_max_frame_num_minus4
  11978. const picOrderCntType = readUEG();
  11979. if (picOrderCntType === 0) {
  11980. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  11981. } else if (picOrderCntType === 1) {
  11982. skipBits(1); // delta_pic_order_always_zero_flag
  11983. skipEG(); // offset_for_non_ref_pic
  11984. skipEG(); // offset_for_top_to_bottom_field
  11985. numRefFramesInPicOrderCntCycle = readUEG();
  11986. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  11987. skipEG();
  11988. } // offset_for_ref_frame[ i ]
  11989. }
  11990. skipUEG(); // max_num_ref_frames
  11991. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  11992. const picWidthInMbsMinus1 = readUEG();
  11993. const picHeightInMapUnitsMinus1 = readUEG();
  11994. const frameMbsOnlyFlag = readBits(1);
  11995. if (frameMbsOnlyFlag === 0) {
  11996. skipBits(1);
  11997. } // mb_adaptive_frame_field_flag
  11998. skipBits(1); // direct_8x8_inference_flag
  11999. if (readBoolean()) {
  12000. // frame_cropping_flag
  12001. frameCropLeftOffset = readUEG();
  12002. frameCropRightOffset = readUEG();
  12003. frameCropTopOffset = readUEG();
  12004. frameCropBottomOffset = readUEG();
  12005. }
  12006. let pixelRatio = [1, 1];
  12007. if (readBoolean()) {
  12008. // vui_parameters_present_flag
  12009. if (readBoolean()) {
  12010. // aspect_ratio_info_present_flag
  12011. const aspectRatioIdc = readUByte();
  12012. switch (aspectRatioIdc) {
  12013. case 1:
  12014. pixelRatio = [1, 1];
  12015. break;
  12016. case 2:
  12017. pixelRatio = [12, 11];
  12018. break;
  12019. case 3:
  12020. pixelRatio = [10, 11];
  12021. break;
  12022. case 4:
  12023. pixelRatio = [16, 11];
  12024. break;
  12025. case 5:
  12026. pixelRatio = [40, 33];
  12027. break;
  12028. case 6:
  12029. pixelRatio = [24, 11];
  12030. break;
  12031. case 7:
  12032. pixelRatio = [20, 11];
  12033. break;
  12034. case 8:
  12035. pixelRatio = [32, 11];
  12036. break;
  12037. case 9:
  12038. pixelRatio = [80, 33];
  12039. break;
  12040. case 10:
  12041. pixelRatio = [18, 11];
  12042. break;
  12043. case 11:
  12044. pixelRatio = [15, 11];
  12045. break;
  12046. case 12:
  12047. pixelRatio = [64, 33];
  12048. break;
  12049. case 13:
  12050. pixelRatio = [160, 99];
  12051. break;
  12052. case 14:
  12053. pixelRatio = [4, 3];
  12054. break;
  12055. case 15:
  12056. pixelRatio = [3, 2];
  12057. break;
  12058. case 16:
  12059. pixelRatio = [2, 1];
  12060. break;
  12061. case 255:
  12062. {
  12063. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  12064. break;
  12065. }
  12066. }
  12067. }
  12068. }
  12069. return {
  12070. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  12071. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  12072. pixelRatio: pixelRatio
  12073. };
  12074. }
  12075. }
  12076. class HevcVideoParser extends BaseVideoParser {
  12077. constructor(...args) {
  12078. super(...args);
  12079. this.initVPS = null;
  12080. }
  12081. parsePES(track, textTrack, pes, endOfSegment) {
  12082. const units = this.parseNALu(track, pes.data, endOfSegment);
  12083. let VideoSample = this.VideoSample;
  12084. let push;
  12085. let spsfound = false;
  12086. // free pes.data to save up some memory
  12087. pes.data = null;
  12088. // if new NAL units found and last sample still there, let's push ...
  12089. // this helps parsing streams with missing AUD (only do this if AUD never found)
  12090. if (VideoSample && units.length && !track.audFound) {
  12091. this.pushAccessUnit(VideoSample, track);
  12092. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  12093. }
  12094. units.forEach(unit => {
  12095. var _VideoSample2, _VideoSample3;
  12096. switch (unit.type) {
  12097. // NON-IDR, NON RANDOM ACCESS SLICE
  12098. case 0:
  12099. case 1:
  12100. case 2:
  12101. case 3:
  12102. case 4:
  12103. case 5:
  12104. case 6:
  12105. case 7:
  12106. case 8:
  12107. case 9:
  12108. if (!VideoSample) {
  12109. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  12110. }
  12111. VideoSample.frame = true;
  12112. push = true;
  12113. break;
  12114. // CRA, BLA (random access picture)
  12115. case 16:
  12116. case 17:
  12117. case 18:
  12118. case 21:
  12119. push = true;
  12120. if (spsfound) {
  12121. var _VideoSample;
  12122. // handle PES not starting with AUD
  12123. // if we have frame data already, that cannot belong to the same frame, so force a push
  12124. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  12125. this.pushAccessUnit(VideoSample, track);
  12126. VideoSample = this.VideoSample = null;
  12127. }
  12128. }
  12129. if (!VideoSample) {
  12130. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  12131. }
  12132. VideoSample.key = true;
  12133. VideoSample.frame = true;
  12134. break;
  12135. // IDR
  12136. case 19:
  12137. case 20:
  12138. push = true;
  12139. // handle PES not starting with AUD
  12140. // if we have frame data already, that cannot belong to the same frame, so force a push
  12141. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  12142. this.pushAccessUnit(VideoSample, track);
  12143. VideoSample = this.VideoSample = null;
  12144. }
  12145. if (!VideoSample) {
  12146. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  12147. }
  12148. VideoSample.key = true;
  12149. VideoSample.frame = true;
  12150. break;
  12151. // SEI
  12152. case 39:
  12153. push = true;
  12154. parseSEIMessageFromNALu(unit.data, 2,
  12155. // NALu header size
  12156. pes.pts, textTrack.samples);
  12157. break;
  12158. // VPS
  12159. case 32:
  12160. push = true;
  12161. if (!track.vps) {
  12162. if (typeof track.params !== 'object') {
  12163. track.params = {};
  12164. }
  12165. track.params = _extends(track.params, this.readVPS(unit.data));
  12166. this.initVPS = unit.data;
  12167. }
  12168. track.vps = [unit.data];
  12169. break;
  12170. // SPS
  12171. case 33:
  12172. push = true;
  12173. spsfound = true;
  12174. if (track.vps !== undefined && track.vps[0] !== this.initVPS && track.sps !== undefined && !this.matchSPS(track.sps[0], unit.data)) {
  12175. this.initVPS = track.vps[0];
  12176. track.sps = track.pps = undefined;
  12177. }
  12178. if (!track.sps) {
  12179. const config = this.readSPS(unit.data);
  12180. track.width = config.width;
  12181. track.height = config.height;
  12182. track.pixelRatio = config.pixelRatio;
  12183. track.codec = config.codecString;
  12184. track.sps = [];
  12185. if (typeof track.params !== 'object') {
  12186. track.params = {};
  12187. }
  12188. for (const prop in config.params) {
  12189. track.params[prop] = config.params[prop];
  12190. }
  12191. }
  12192. this.pushParameterSet(track.sps, unit.data, track.vps);
  12193. if (!VideoSample) {
  12194. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);
  12195. }
  12196. VideoSample.key = true;
  12197. break;
  12198. // PPS
  12199. case 34:
  12200. push = true;
  12201. if (typeof track.params === 'object') {
  12202. if (!track.pps) {
  12203. track.pps = [];
  12204. const config = this.readPPS(unit.data);
  12205. for (const prop in config) {
  12206. track.params[prop] = config[prop];
  12207. }
  12208. }
  12209. this.pushParameterSet(track.pps, unit.data, track.vps);
  12210. }
  12211. break;
  12212. // ACCESS UNIT DELIMITER
  12213. case 35:
  12214. push = true;
  12215. track.audFound = true;
  12216. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  12217. this.pushAccessUnit(VideoSample, track);
  12218. VideoSample = null;
  12219. }
  12220. if (!VideoSample) {
  12221. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  12222. }
  12223. break;
  12224. default:
  12225. push = false;
  12226. break;
  12227. }
  12228. if (VideoSample && push) {
  12229. const units = VideoSample.units;
  12230. units.push(unit);
  12231. }
  12232. });
  12233. // if last PES packet, push samples
  12234. if (endOfSegment && VideoSample) {
  12235. this.pushAccessUnit(VideoSample, track);
  12236. this.VideoSample = null;
  12237. }
  12238. }
  12239. pushParameterSet(parameterSets, data, vps) {
  12240. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  12241. parameterSets.push(data);
  12242. }
  12243. }
  12244. getNALuType(data, offset) {
  12245. return (data[offset] & 0x7e) >>> 1;
  12246. }
  12247. ebsp2rbsp(arr) {
  12248. const dst = new Uint8Array(arr.byteLength);
  12249. let dstIdx = 0;
  12250. for (let i = 0; i < arr.byteLength; i++) {
  12251. if (i >= 2) {
  12252. // Unescape: Skip 0x03 after 00 00
  12253. if (arr[i] === 0x03 && arr[i - 1] === 0x00 && arr[i - 2] === 0x00) {
  12254. continue;
  12255. }
  12256. }
  12257. dst[dstIdx] = arr[i];
  12258. dstIdx++;
  12259. }
  12260. return new Uint8Array(dst.buffer, 0, dstIdx);
  12261. }
  12262. pushAccessUnit(VideoSample, videoTrack) {
  12263. super.pushAccessUnit(VideoSample, videoTrack);
  12264. if (this.initVPS) {
  12265. this.initVPS = null; // null initVPS to prevent possible track's sps/pps growth until next VPS
  12266. }
  12267. }
  12268. readVPS(vps) {
  12269. const eg = new ExpGolomb(vps);
  12270. // remove header
  12271. eg.readUByte();
  12272. eg.readUByte();
  12273. eg.readBits(4); // video_parameter_set_id
  12274. eg.skipBits(2);
  12275. eg.readBits(6); // max_layers_minus1
  12276. const max_sub_layers_minus1 = eg.readBits(3);
  12277. const temporal_id_nesting_flag = eg.readBoolean();
  12278. // ...vui fps can be here, but empty fps value is not critical for metadata
  12279. return {
  12280. numTemporalLayers: max_sub_layers_minus1 + 1,
  12281. temporalIdNested: temporal_id_nesting_flag
  12282. };
  12283. }
  12284. readSPS(sps) {
  12285. const eg = new ExpGolomb(this.ebsp2rbsp(sps));
  12286. eg.readUByte();
  12287. eg.readUByte();
  12288. eg.readBits(4); //video_parameter_set_id
  12289. const max_sub_layers_minus1 = eg.readBits(3);
  12290. eg.readBoolean(); // temporal_id_nesting_flag
  12291. // profile_tier_level
  12292. const general_profile_space = eg.readBits(2);
  12293. const general_tier_flag = eg.readBoolean();
  12294. const general_profile_idc = eg.readBits(5);
  12295. const general_profile_compatibility_flags_1 = eg.readUByte();
  12296. const general_profile_compatibility_flags_2 = eg.readUByte();
  12297. const general_profile_compatibility_flags_3 = eg.readUByte();
  12298. const general_profile_compatibility_flags_4 = eg.readUByte();
  12299. const general_constraint_indicator_flags_1 = eg.readUByte();
  12300. const general_constraint_indicator_flags_2 = eg.readUByte();
  12301. const general_constraint_indicator_flags_3 = eg.readUByte();
  12302. const general_constraint_indicator_flags_4 = eg.readUByte();
  12303. const general_constraint_indicator_flags_5 = eg.readUByte();
  12304. const general_constraint_indicator_flags_6 = eg.readUByte();
  12305. const general_level_idc = eg.readUByte();
  12306. const sub_layer_profile_present_flags = [];
  12307. const sub_layer_level_present_flags = [];
  12308. for (let i = 0; i < max_sub_layers_minus1; i++) {
  12309. sub_layer_profile_present_flags.push(eg.readBoolean());
  12310. sub_layer_level_present_flags.push(eg.readBoolean());
  12311. }
  12312. if (max_sub_layers_minus1 > 0) {
  12313. for (let i = max_sub_layers_minus1; i < 8; i++) {
  12314. eg.readBits(2);
  12315. }
  12316. }
  12317. for (let i = 0; i < max_sub_layers_minus1; i++) {
  12318. if (sub_layer_profile_present_flags[i]) {
  12319. eg.readUByte(); // sub_layer_profile_space, sub_layer_tier_flag, sub_layer_profile_idc
  12320. eg.readUByte();
  12321. eg.readUByte();
  12322. eg.readUByte();
  12323. eg.readUByte(); // sub_layer_profile_compatibility_flag
  12324. eg.readUByte();
  12325. eg.readUByte();
  12326. eg.readUByte();
  12327. eg.readUByte();
  12328. eg.readUByte();
  12329. eg.readUByte();
  12330. }
  12331. if (sub_layer_level_present_flags[i]) {
  12332. eg.readUByte();
  12333. }
  12334. }
  12335. eg.readUEG(); // seq_parameter_set_id
  12336. const chroma_format_idc = eg.readUEG();
  12337. if (chroma_format_idc == 3) {
  12338. eg.skipBits(1); //separate_colour_plane_flag
  12339. }
  12340. const pic_width_in_luma_samples = eg.readUEG();
  12341. const pic_height_in_luma_samples = eg.readUEG();
  12342. const conformance_window_flag = eg.readBoolean();
  12343. let pic_left_offset = 0,
  12344. pic_right_offset = 0,
  12345. pic_top_offset = 0,
  12346. pic_bottom_offset = 0;
  12347. if (conformance_window_flag) {
  12348. pic_left_offset += eg.readUEG();
  12349. pic_right_offset += eg.readUEG();
  12350. pic_top_offset += eg.readUEG();
  12351. pic_bottom_offset += eg.readUEG();
  12352. }
  12353. const bit_depth_luma_minus8 = eg.readUEG();
  12354. const bit_depth_chroma_minus8 = eg.readUEG();
  12355. const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  12356. const sub_layer_ordering_info_present_flag = eg.readBoolean();
  12357. for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {
  12358. eg.skipUEG(); // max_dec_pic_buffering_minus1[i]
  12359. eg.skipUEG(); // max_num_reorder_pics[i]
  12360. eg.skipUEG(); // max_latency_increase_plus1[i]
  12361. }
  12362. eg.skipUEG(); // log2_min_luma_coding_block_size_minus3
  12363. eg.skipUEG(); // log2_diff_max_min_luma_coding_block_size
  12364. eg.skipUEG(); // log2_min_transform_block_size_minus2
  12365. eg.skipUEG(); // log2_diff_max_min_transform_block_size
  12366. eg.skipUEG(); // max_transform_hierarchy_depth_inter
  12367. eg.skipUEG(); // max_transform_hierarchy_depth_intra
  12368. const scaling_list_enabled_flag = eg.readBoolean();
  12369. if (scaling_list_enabled_flag) {
  12370. const sps_scaling_list_data_present_flag = eg.readBoolean();
  12371. if (sps_scaling_list_data_present_flag) {
  12372. for (let sizeId = 0; sizeId < 4; sizeId++) {
  12373. for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  12374. const scaling_list_pred_mode_flag = eg.readBoolean();
  12375. if (!scaling_list_pred_mode_flag) {
  12376. eg.readUEG(); // scaling_list_pred_matrix_id_delta
  12377. } else {
  12378. const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  12379. if (sizeId > 1) {
  12380. eg.readEG();
  12381. }
  12382. for (let i = 0; i < coefNum; i++) {
  12383. eg.readEG();
  12384. }
  12385. }
  12386. }
  12387. }
  12388. }
  12389. }
  12390. eg.readBoolean(); // amp_enabled_flag
  12391. eg.readBoolean(); // sample_adaptive_offset_enabled_flag
  12392. const pcm_enabled_flag = eg.readBoolean();
  12393. if (pcm_enabled_flag) {
  12394. eg.readUByte();
  12395. eg.skipUEG();
  12396. eg.skipUEG();
  12397. eg.readBoolean();
  12398. }
  12399. const num_short_term_ref_pic_sets = eg.readUEG();
  12400. let num_delta_pocs = 0;
  12401. for (let i = 0; i < num_short_term_ref_pic_sets; i++) {
  12402. let inter_ref_pic_set_prediction_flag = false;
  12403. if (i !== 0) {
  12404. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  12405. }
  12406. if (inter_ref_pic_set_prediction_flag) {
  12407. if (i === num_short_term_ref_pic_sets) {
  12408. eg.readUEG();
  12409. }
  12410. eg.readBoolean();
  12411. eg.readUEG();
  12412. let next_num_delta_pocs = 0;
  12413. for (let j = 0; j <= num_delta_pocs; j++) {
  12414. const used_by_curr_pic_flag = eg.readBoolean();
  12415. let use_delta_flag = false;
  12416. if (!used_by_curr_pic_flag) {
  12417. use_delta_flag = eg.readBoolean();
  12418. }
  12419. if (used_by_curr_pic_flag || use_delta_flag) {
  12420. next_num_delta_pocs++;
  12421. }
  12422. }
  12423. num_delta_pocs = next_num_delta_pocs;
  12424. } else {
  12425. const num_negative_pics = eg.readUEG();
  12426. const num_positive_pics = eg.readUEG();
  12427. num_delta_pocs = num_negative_pics + num_positive_pics;
  12428. for (let j = 0; j < num_negative_pics; j++) {
  12429. eg.readUEG();
  12430. eg.readBoolean();
  12431. }
  12432. for (let j = 0; j < num_positive_pics; j++) {
  12433. eg.readUEG();
  12434. eg.readBoolean();
  12435. }
  12436. }
  12437. }
  12438. const long_term_ref_pics_present_flag = eg.readBoolean();
  12439. if (long_term_ref_pics_present_flag) {
  12440. const num_long_term_ref_pics_sps = eg.readUEG();
  12441. for (let i = 0; i < num_long_term_ref_pics_sps; i++) {
  12442. for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {
  12443. eg.readBits(1);
  12444. }
  12445. eg.readBits(1);
  12446. }
  12447. }
  12448. let min_spatial_segmentation_idc = 0;
  12449. let sar_width = 1,
  12450. sar_height = 1;
  12451. let fps_fixed = true,
  12452. fps_den = 1,
  12453. fps_num = 0;
  12454. eg.readBoolean(); // sps_temporal_mvp_enabled_flag
  12455. eg.readBoolean(); // strong_intra_smoothing_enabled_flag
  12456. let default_display_window_flag = false;
  12457. const vui_parameters_present_flag = eg.readBoolean();
  12458. if (vui_parameters_present_flag) {
  12459. const aspect_ratio_info_present_flag = eg.readBoolean();
  12460. if (aspect_ratio_info_present_flag) {
  12461. const aspect_ratio_idc = eg.readUByte();
  12462. const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  12463. const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  12464. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  12465. sar_width = sar_width_table[aspect_ratio_idc - 1];
  12466. sar_height = sar_height_table[aspect_ratio_idc - 1];
  12467. } else if (aspect_ratio_idc === 255) {
  12468. sar_width = eg.readBits(16);
  12469. sar_height = eg.readBits(16);
  12470. }
  12471. }
  12472. const overscan_info_present_flag = eg.readBoolean();
  12473. if (overscan_info_present_flag) {
  12474. eg.readBoolean();
  12475. }
  12476. const video_signal_type_present_flag = eg.readBoolean();
  12477. if (video_signal_type_present_flag) {
  12478. eg.readBits(3);
  12479. eg.readBoolean();
  12480. const colour_description_present_flag = eg.readBoolean();
  12481. if (colour_description_present_flag) {
  12482. eg.readUByte();
  12483. eg.readUByte();
  12484. eg.readUByte();
  12485. }
  12486. }
  12487. const chroma_loc_info_present_flag = eg.readBoolean();
  12488. if (chroma_loc_info_present_flag) {
  12489. eg.readUEG();
  12490. eg.readUEG();
  12491. }
  12492. eg.readBoolean(); // neutral_chroma_indication_flag
  12493. eg.readBoolean(); // field_seq_flag
  12494. eg.readBoolean(); // frame_field_info_present_flag
  12495. default_display_window_flag = eg.readBoolean();
  12496. if (default_display_window_flag) {
  12497. pic_left_offset += eg.readUEG();
  12498. pic_right_offset += eg.readUEG();
  12499. pic_top_offset += eg.readUEG();
  12500. pic_bottom_offset += eg.readUEG();
  12501. }
  12502. const vui_timing_info_present_flag = eg.readBoolean();
  12503. if (vui_timing_info_present_flag) {
  12504. fps_den = eg.readBits(32);
  12505. fps_num = eg.readBits(32);
  12506. const vui_poc_proportional_to_timing_flag = eg.readBoolean();
  12507. if (vui_poc_proportional_to_timing_flag) {
  12508. eg.readUEG();
  12509. }
  12510. const vui_hrd_parameters_present_flag = eg.readBoolean();
  12511. if (vui_hrd_parameters_present_flag) {
  12512. //const commonInfPresentFlag = true;
  12513. //if (commonInfPresentFlag) {
  12514. const nal_hrd_parameters_present_flag = eg.readBoolean();
  12515. const vcl_hrd_parameters_present_flag = eg.readBoolean();
  12516. let sub_pic_hrd_params_present_flag = false;
  12517. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  12518. sub_pic_hrd_params_present_flag = eg.readBoolean();
  12519. if (sub_pic_hrd_params_present_flag) {
  12520. eg.readUByte();
  12521. eg.readBits(5);
  12522. eg.readBoolean();
  12523. eg.readBits(5);
  12524. }
  12525. eg.readBits(4); // bit_rate_scale
  12526. eg.readBits(4); // cpb_size_scale
  12527. if (sub_pic_hrd_params_present_flag) {
  12528. eg.readBits(4);
  12529. }
  12530. eg.readBits(5);
  12531. eg.readBits(5);
  12532. eg.readBits(5);
  12533. }
  12534. //}
  12535. for (let i = 0; i <= max_sub_layers_minus1; i++) {
  12536. fps_fixed = eg.readBoolean(); // fixed_pic_rate_general_flag
  12537. const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  12538. let low_delay_hrd_flag = false;
  12539. if (fixed_pic_rate_within_cvs_flag) {
  12540. eg.readEG();
  12541. } else {
  12542. low_delay_hrd_flag = eg.readBoolean();
  12543. }
  12544. const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  12545. if (nal_hrd_parameters_present_flag) {
  12546. for (let j = 0; j < cpb_cnt; j++) {
  12547. eg.readUEG();
  12548. eg.readUEG();
  12549. if (sub_pic_hrd_params_present_flag) {
  12550. eg.readUEG();
  12551. eg.readUEG();
  12552. }
  12553. eg.skipBits(1);
  12554. }
  12555. }
  12556. if (vcl_hrd_parameters_present_flag) {
  12557. for (let j = 0; j < cpb_cnt; j++) {
  12558. eg.readUEG();
  12559. eg.readUEG();
  12560. if (sub_pic_hrd_params_present_flag) {
  12561. eg.readUEG();
  12562. eg.readUEG();
  12563. }
  12564. eg.skipBits(1);
  12565. }
  12566. }
  12567. }
  12568. }
  12569. }
  12570. const bitstream_restriction_flag = eg.readBoolean();
  12571. if (bitstream_restriction_flag) {
  12572. eg.readBoolean(); // tiles_fixed_structure_flag
  12573. eg.readBoolean(); // motion_vectors_over_pic_boundaries_flag
  12574. eg.readBoolean(); // restricted_ref_pic_lists_flag
  12575. min_spatial_segmentation_idc = eg.readUEG();
  12576. }
  12577. }
  12578. let width = pic_width_in_luma_samples,
  12579. height = pic_height_in_luma_samples;
  12580. if (conformance_window_flag || default_display_window_flag) {
  12581. let chroma_scale_w = 1,
  12582. chroma_scale_h = 1;
  12583. if (chroma_format_idc === 1) {
  12584. // YUV 420
  12585. chroma_scale_w = chroma_scale_h = 2;
  12586. } else if (chroma_format_idc == 2) {
  12587. // YUV 422
  12588. chroma_scale_w = 2;
  12589. }
  12590. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  12591. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  12592. }
  12593. const profile_space_string = general_profile_space ? ['A', 'B', 'C'][general_profile_space] : '';
  12594. const profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;
  12595. let profile_compatibility_rev = 0;
  12596. for (let i = 0; i < 32; i++) {
  12597. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0; // reverse bit position (and cast as UInt32)
  12598. }
  12599. let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  12600. if (general_profile_idc === 1 && profile_compatibility_flags_string === '2') {
  12601. profile_compatibility_flags_string = '6';
  12602. }
  12603. const tier_flag_string = general_tier_flag ? 'H' : 'L';
  12604. return {
  12605. codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,
  12606. params: {
  12607. general_tier_flag,
  12608. general_profile_idc,
  12609. general_profile_space,
  12610. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  12611. general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],
  12612. general_level_idc,
  12613. bit_depth: bit_depth_luma_minus8 + 8,
  12614. bit_depth_luma_minus8,
  12615. bit_depth_chroma_minus8,
  12616. min_spatial_segmentation_idc,
  12617. chroma_format_idc: chroma_format_idc,
  12618. frame_rate: {
  12619. fixed: fps_fixed,
  12620. fps: fps_num / fps_den
  12621. }
  12622. },
  12623. width,
  12624. height,
  12625. pixelRatio: [sar_width, sar_height]
  12626. };
  12627. }
  12628. readPPS(pps) {
  12629. const eg = new ExpGolomb(this.ebsp2rbsp(pps));
  12630. eg.readUByte();
  12631. eg.readUByte();
  12632. eg.skipUEG(); // pic_parameter_set_id
  12633. eg.skipUEG(); // seq_parameter_set_id
  12634. eg.skipBits(2); // dependent_slice_segments_enabled_flag, output_flag_present_flag
  12635. eg.skipBits(3); // num_extra_slice_header_bits
  12636. eg.skipBits(2); // sign_data_hiding_enabled_flag, cabac_init_present_flag
  12637. eg.skipUEG();
  12638. eg.skipUEG();
  12639. eg.skipEG(); // init_qp_minus26
  12640. eg.skipBits(2); // constrained_intra_pred_flag, transform_skip_enabled_flag
  12641. const cu_qp_delta_enabled_flag = eg.readBoolean();
  12642. if (cu_qp_delta_enabled_flag) {
  12643. eg.skipUEG();
  12644. }
  12645. eg.skipEG(); // cb_qp_offset
  12646. eg.skipEG(); // cr_qp_offset
  12647. eg.skipBits(4); // pps_slice_chroma_qp_offsets_present_flag, weighted_pred_flag, weighted_bipred_flag, transquant_bypass_enabled_flag
  12648. const tiles_enabled_flag = eg.readBoolean();
  12649. const entropy_coding_sync_enabled_flag = eg.readBoolean();
  12650. let parallelismType = 1; // slice-based parallel decoding
  12651. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  12652. parallelismType = 0; // mixed-type parallel decoding
  12653. } else if (entropy_coding_sync_enabled_flag) {
  12654. parallelismType = 3; // wavefront-based parallel decoding
  12655. } else if (tiles_enabled_flag) {
  12656. parallelismType = 2; // tile-based parallel decoding
  12657. }
  12658. return {
  12659. parallelismType
  12660. };
  12661. }
  12662. matchSPS(sps1, sps2) {
  12663. // compare without headers and VPS related params
  12664. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  12665. }
  12666. }
  12667. const PACKET_LENGTH = 188;
  12668. class TSDemuxer {
  12669. constructor(observer, config, typeSupported, logger) {
  12670. this.logger = void 0;
  12671. this.observer = void 0;
  12672. this.config = void 0;
  12673. this.typeSupported = void 0;
  12674. this.sampleAes = null;
  12675. this.pmtParsed = false;
  12676. this.audioCodec = void 0;
  12677. this.videoCodec = void 0;
  12678. this._pmtId = -1;
  12679. this._videoTrack = void 0;
  12680. this._audioTrack = void 0;
  12681. this._id3Track = void 0;
  12682. this._txtTrack = void 0;
  12683. this.aacOverFlow = null;
  12684. this.remainderData = null;
  12685. this.videoParser = void 0;
  12686. this.observer = observer;
  12687. this.config = config;
  12688. this.typeSupported = typeSupported;
  12689. this.logger = logger;
  12690. this.videoParser = null;
  12691. }
  12692. static probe(data, logger) {
  12693. const syncOffset = TSDemuxer.syncOffset(data);
  12694. if (syncOffset > 0) {
  12695. logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  12696. }
  12697. return syncOffset !== -1;
  12698. }
  12699. static syncOffset(data) {
  12700. const length = data.length;
  12701. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  12702. let i = 0;
  12703. while (i < scanwindow) {
  12704. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  12705. let foundPat = false;
  12706. let packetStart = -1;
  12707. let tsPackets = 0;
  12708. for (let j = i; j < length; j += PACKET_LENGTH) {
  12709. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  12710. tsPackets++;
  12711. if (packetStart === -1) {
  12712. packetStart = j;
  12713. // First sync word found at offset, increase scan length (#5251)
  12714. if (packetStart !== 0) {
  12715. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  12716. }
  12717. }
  12718. if (!foundPat) {
  12719. foundPat = parsePID(data, j) === 0;
  12720. }
  12721. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  12722. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  12723. return packetStart;
  12724. }
  12725. } else if (tsPackets) {
  12726. // Exit if sync word found, but does not contain contiguous packets
  12727. return -1;
  12728. } else {
  12729. break;
  12730. }
  12731. }
  12732. i++;
  12733. }
  12734. return -1;
  12735. }
  12736. /**
  12737. * Creates a track model internal to demuxer used to drive remuxing input
  12738. */
  12739. static createTrack(type, duration) {
  12740. return {
  12741. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  12742. type,
  12743. id: RemuxerTrackIdConfig[type],
  12744. pid: -1,
  12745. inputTimeScale: 90000,
  12746. sequenceNumber: 0,
  12747. samples: [],
  12748. dropped: 0,
  12749. duration: type === 'audio' ? duration : undefined
  12750. };
  12751. }
  12752. /**
  12753. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  12754. * Resets all internal track instances of the demuxer.
  12755. */
  12756. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12757. this.pmtParsed = false;
  12758. this._pmtId = -1;
  12759. this._videoTrack = TSDemuxer.createTrack('video');
  12760. this._videoTrack.duration = trackDuration;
  12761. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  12762. this._id3Track = TSDemuxer.createTrack('id3');
  12763. this._txtTrack = TSDemuxer.createTrack('text');
  12764. this._audioTrack.segmentCodec = 'aac';
  12765. // flush any partial content
  12766. this.aacOverFlow = null;
  12767. this.remainderData = null;
  12768. this.audioCodec = audioCodec;
  12769. this.videoCodec = videoCodec;
  12770. }
  12771. resetTimeStamp() {}
  12772. resetContiguity() {
  12773. const {
  12774. _audioTrack,
  12775. _videoTrack,
  12776. _id3Track
  12777. } = this;
  12778. if (_audioTrack) {
  12779. _audioTrack.pesData = null;
  12780. }
  12781. if (_videoTrack) {
  12782. _videoTrack.pesData = null;
  12783. }
  12784. if (_id3Track) {
  12785. _id3Track.pesData = null;
  12786. }
  12787. this.aacOverFlow = null;
  12788. this.remainderData = null;
  12789. }
  12790. demux(data, timeOffset, isSampleAes = false, flush = false) {
  12791. if (!isSampleAes) {
  12792. this.sampleAes = null;
  12793. }
  12794. let pes;
  12795. const videoTrack = this._videoTrack;
  12796. const audioTrack = this._audioTrack;
  12797. const id3Track = this._id3Track;
  12798. const textTrack = this._txtTrack;
  12799. let videoPid = videoTrack.pid;
  12800. let videoData = videoTrack.pesData;
  12801. let audioPid = audioTrack.pid;
  12802. let id3Pid = id3Track.pid;
  12803. let audioData = audioTrack.pesData;
  12804. let id3Data = id3Track.pesData;
  12805. let unknownPID = null;
  12806. let pmtParsed = this.pmtParsed;
  12807. let pmtId = this._pmtId;
  12808. let len = data.length;
  12809. if (this.remainderData) {
  12810. data = appendUint8Array(this.remainderData, data);
  12811. len = data.length;
  12812. this.remainderData = null;
  12813. }
  12814. if (len < PACKET_LENGTH && !flush) {
  12815. this.remainderData = data;
  12816. return {
  12817. audioTrack,
  12818. videoTrack,
  12819. id3Track,
  12820. textTrack
  12821. };
  12822. }
  12823. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  12824. len -= (len - syncOffset) % PACKET_LENGTH;
  12825. if (len < data.byteLength && !flush) {
  12826. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  12827. }
  12828. // loop through TS packets
  12829. let tsPacketErrors = 0;
  12830. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  12831. if (data[start] === 0x47) {
  12832. const stt = !!(data[start + 1] & 0x40);
  12833. const pid = parsePID(data, start);
  12834. const atf = (data[start + 3] & 0x30) >> 4;
  12835. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  12836. let offset;
  12837. if (atf > 1) {
  12838. offset = start + 5 + data[start + 4];
  12839. // continue if there is only adaptation field
  12840. if (offset === start + PACKET_LENGTH) {
  12841. continue;
  12842. }
  12843. } else {
  12844. offset = start + 4;
  12845. }
  12846. switch (pid) {
  12847. case videoPid:
  12848. if (stt) {
  12849. if (videoData && (pes = parsePES(videoData, this.logger))) {
  12850. if (this.videoParser === null) {
  12851. switch (videoTrack.segmentCodec) {
  12852. case 'avc':
  12853. this.videoParser = new AvcVideoParser();
  12854. break;
  12855. case 'hevc':
  12856. {
  12857. this.videoParser = new HevcVideoParser();
  12858. }
  12859. break;
  12860. }
  12861. }
  12862. if (this.videoParser !== null) {
  12863. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  12864. }
  12865. }
  12866. videoData = {
  12867. data: [],
  12868. size: 0
  12869. };
  12870. }
  12871. if (videoData) {
  12872. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12873. videoData.size += start + PACKET_LENGTH - offset;
  12874. }
  12875. break;
  12876. case audioPid:
  12877. if (stt) {
  12878. if (audioData && (pes = parsePES(audioData, this.logger))) {
  12879. switch (audioTrack.segmentCodec) {
  12880. case 'aac':
  12881. this.parseAACPES(audioTrack, pes);
  12882. break;
  12883. case 'mp3':
  12884. this.parseMPEGPES(audioTrack, pes);
  12885. break;
  12886. case 'ac3':
  12887. {
  12888. this.parseAC3PES(audioTrack, pes);
  12889. }
  12890. break;
  12891. }
  12892. }
  12893. audioData = {
  12894. data: [],
  12895. size: 0
  12896. };
  12897. }
  12898. if (audioData) {
  12899. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12900. audioData.size += start + PACKET_LENGTH - offset;
  12901. }
  12902. break;
  12903. case id3Pid:
  12904. if (stt) {
  12905. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  12906. this.parseID3PES(id3Track, pes);
  12907. }
  12908. id3Data = {
  12909. data: [],
  12910. size: 0
  12911. };
  12912. }
  12913. if (id3Data) {
  12914. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12915. id3Data.size += start + PACKET_LENGTH - offset;
  12916. }
  12917. break;
  12918. case 0:
  12919. if (stt) {
  12920. offset += data[offset] + 1;
  12921. }
  12922. pmtId = this._pmtId = parsePAT(data, offset);
  12923. // this.logger.log('PMT PID:' + this._pmtId);
  12924. break;
  12925. case pmtId:
  12926. {
  12927. if (stt) {
  12928. offset += data[offset] + 1;
  12929. }
  12930. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  12931. // only update track id if track PID found while parsing PMT
  12932. // this is to avoid resetting the PID to -1 in case
  12933. // track PID transiently disappears from the stream
  12934. // this could happen in case of transient missing audio samples for example
  12935. // NOTE this is only the PID of the track as found in TS,
  12936. // but we are not using this for MP4 track IDs.
  12937. videoPid = parsedPIDs.videoPid;
  12938. if (videoPid > 0) {
  12939. videoTrack.pid = videoPid;
  12940. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  12941. }
  12942. audioPid = parsedPIDs.audioPid;
  12943. if (audioPid > 0) {
  12944. audioTrack.pid = audioPid;
  12945. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  12946. }
  12947. id3Pid = parsedPIDs.id3Pid;
  12948. if (id3Pid > 0) {
  12949. id3Track.pid = id3Pid;
  12950. }
  12951. if (unknownPID !== null && !pmtParsed) {
  12952. this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  12953. unknownPID = null;
  12954. // we set it to -188, the += 188 in the for loop will reset start to 0
  12955. start = syncOffset - 188;
  12956. }
  12957. pmtParsed = this.pmtParsed = true;
  12958. break;
  12959. }
  12960. case 0x11:
  12961. case 0x1fff:
  12962. break;
  12963. default:
  12964. unknownPID = pid;
  12965. break;
  12966. }
  12967. } else {
  12968. tsPacketErrors++;
  12969. }
  12970. }
  12971. if (tsPacketErrors > 0) {
  12972. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), undefined, this.logger);
  12973. }
  12974. videoTrack.pesData = videoData;
  12975. audioTrack.pesData = audioData;
  12976. id3Track.pesData = id3Data;
  12977. const demuxResult = {
  12978. audioTrack,
  12979. videoTrack,
  12980. id3Track,
  12981. textTrack
  12982. };
  12983. if (flush) {
  12984. this.extractRemainingSamples(demuxResult);
  12985. }
  12986. return demuxResult;
  12987. }
  12988. flush() {
  12989. const {
  12990. remainderData
  12991. } = this;
  12992. this.remainderData = null;
  12993. let result;
  12994. if (remainderData) {
  12995. result = this.demux(remainderData, -1, false, true);
  12996. } else {
  12997. result = {
  12998. videoTrack: this._videoTrack,
  12999. audioTrack: this._audioTrack,
  13000. id3Track: this._id3Track,
  13001. textTrack: this._txtTrack
  13002. };
  13003. }
  13004. this.extractRemainingSamples(result);
  13005. if (this.sampleAes) {
  13006. return this.decrypt(result, this.sampleAes);
  13007. }
  13008. return result;
  13009. }
  13010. extractRemainingSamples(demuxResult) {
  13011. const {
  13012. audioTrack,
  13013. videoTrack,
  13014. id3Track,
  13015. textTrack
  13016. } = demuxResult;
  13017. const videoData = videoTrack.pesData;
  13018. const audioData = audioTrack.pesData;
  13019. const id3Data = id3Track.pesData;
  13020. // try to parse last PES packets
  13021. let pes;
  13022. if (videoData && (pes = parsePES(videoData, this.logger))) {
  13023. if (this.videoParser === null) {
  13024. switch (videoTrack.segmentCodec) {
  13025. case 'avc':
  13026. this.videoParser = new AvcVideoParser();
  13027. break;
  13028. case 'hevc':
  13029. {
  13030. this.videoParser = new HevcVideoParser();
  13031. }
  13032. break;
  13033. }
  13034. }
  13035. if (this.videoParser !== null) {
  13036. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  13037. videoTrack.pesData = null;
  13038. }
  13039. } else {
  13040. // either avcData null or PES truncated, keep it for next frag parsing
  13041. videoTrack.pesData = videoData;
  13042. }
  13043. if (audioData && (pes = parsePES(audioData, this.logger))) {
  13044. switch (audioTrack.segmentCodec) {
  13045. case 'aac':
  13046. this.parseAACPES(audioTrack, pes);
  13047. break;
  13048. case 'mp3':
  13049. this.parseMPEGPES(audioTrack, pes);
  13050. break;
  13051. case 'ac3':
  13052. {
  13053. this.parseAC3PES(audioTrack, pes);
  13054. }
  13055. break;
  13056. }
  13057. audioTrack.pesData = null;
  13058. } else {
  13059. if (audioData != null && audioData.size) {
  13060. this.logger.log('last AAC PES packet truncated,might overlap between fragments');
  13061. }
  13062. // either audioData null or PES truncated, keep it for next frag parsing
  13063. audioTrack.pesData = audioData;
  13064. }
  13065. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  13066. this.parseID3PES(id3Track, pes);
  13067. id3Track.pesData = null;
  13068. } else {
  13069. // either id3Data null or PES truncated, keep it for next frag parsing
  13070. id3Track.pesData = id3Data;
  13071. }
  13072. }
  13073. demuxSampleAes(data, keyData, timeOffset) {
  13074. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  13075. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  13076. return this.decrypt(demuxResult, sampleAes);
  13077. }
  13078. decrypt(demuxResult, sampleAes) {
  13079. return new Promise(resolve => {
  13080. const {
  13081. audioTrack,
  13082. videoTrack
  13083. } = demuxResult;
  13084. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  13085. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  13086. if (videoTrack.samples) {
  13087. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  13088. resolve(demuxResult);
  13089. });
  13090. } else {
  13091. resolve(demuxResult);
  13092. }
  13093. });
  13094. } else if (videoTrack.samples) {
  13095. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  13096. resolve(demuxResult);
  13097. });
  13098. }
  13099. });
  13100. }
  13101. destroy() {
  13102. if (this.observer) {
  13103. this.observer.removeAllListeners();
  13104. }
  13105. // @ts-ignore
  13106. this.config = this.logger = this.observer = null;
  13107. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  13108. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = undefined;
  13109. }
  13110. parseAACPES(track, pes) {
  13111. let startOffset = 0;
  13112. const aacOverFlow = this.aacOverFlow;
  13113. let data = pes.data;
  13114. if (aacOverFlow) {
  13115. this.aacOverFlow = null;
  13116. const frameMissingBytes = aacOverFlow.missing;
  13117. const sampleLength = aacOverFlow.sample.unit.byteLength;
  13118. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  13119. if (frameMissingBytes === -1) {
  13120. data = appendUint8Array(aacOverFlow.sample.unit, data);
  13121. } else {
  13122. const frameOverflowBytes = sampleLength - frameMissingBytes;
  13123. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  13124. track.samples.push(aacOverFlow.sample);
  13125. startOffset = aacOverFlow.missing;
  13126. }
  13127. }
  13128. // look for ADTS header (0xFFFx)
  13129. let offset;
  13130. let len;
  13131. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  13132. if (isHeader$1(data, offset)) {
  13133. break;
  13134. }
  13135. }
  13136. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  13137. if (offset !== startOffset) {
  13138. let reason;
  13139. const recoverable = offset < len - 1;
  13140. if (recoverable) {
  13141. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  13142. } else {
  13143. reason = 'No ADTS header found in AAC PES';
  13144. }
  13145. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  13146. if (!recoverable) {
  13147. return;
  13148. }
  13149. }
  13150. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  13151. let pts;
  13152. if (pes.pts !== undefined) {
  13153. pts = pes.pts;
  13154. } else if (aacOverFlow) {
  13155. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  13156. // first sample PTS should be equal to last sample PTS + frameDuration
  13157. const frameDuration = getFrameDuration(track.samplerate);
  13158. pts = aacOverFlow.sample.pts + frameDuration;
  13159. } else {
  13160. this.logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  13161. return;
  13162. }
  13163. // scan for aac samples
  13164. let frameIndex = 0;
  13165. let frame;
  13166. while (offset < len) {
  13167. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  13168. offset += frame.length;
  13169. if (!frame.missing) {
  13170. frameIndex++;
  13171. for (; offset < len - 1; offset++) {
  13172. if (isHeader$1(data, offset)) {
  13173. break;
  13174. }
  13175. }
  13176. } else {
  13177. this.aacOverFlow = frame;
  13178. break;
  13179. }
  13180. }
  13181. }
  13182. parseMPEGPES(track, pes) {
  13183. const data = pes.data;
  13184. const length = data.length;
  13185. let frameIndex = 0;
  13186. let offset = 0;
  13187. const pts = pes.pts;
  13188. if (pts === undefined) {
  13189. this.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  13190. return;
  13191. }
  13192. while (offset < length) {
  13193. if (isHeader(data, offset)) {
  13194. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  13195. if (frame) {
  13196. offset += frame.length;
  13197. frameIndex++;
  13198. } else {
  13199. // logger.log('Unable to parse Mpeg audio frame');
  13200. break;
  13201. }
  13202. } else {
  13203. // nothing found, keep looking
  13204. offset++;
  13205. }
  13206. }
  13207. }
  13208. parseAC3PES(track, pes) {
  13209. {
  13210. const data = pes.data;
  13211. const pts = pes.pts;
  13212. if (pts === undefined) {
  13213. this.logger.warn('[tsdemuxer]: AC3 PES unknown PTS');
  13214. return;
  13215. }
  13216. const length = data.length;
  13217. let frameIndex = 0;
  13218. let offset = 0;
  13219. let parsed;
  13220. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  13221. offset += parsed;
  13222. }
  13223. }
  13224. }
  13225. parseID3PES(id3Track, pes) {
  13226. if (pes.pts === undefined) {
  13227. this.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  13228. return;
  13229. }
  13230. const id3Sample = _extends({}, pes, {
  13231. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  13232. duration: Number.POSITIVE_INFINITY
  13233. });
  13234. id3Track.samples.push(id3Sample);
  13235. }
  13236. }
  13237. function parsePID(data, offset) {
  13238. // pid is a 13-bit field starting at the last bit of TS[1]
  13239. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  13240. }
  13241. function parsePAT(data, offset) {
  13242. // skip the PSI header and parse the first PMT entry
  13243. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  13244. }
  13245. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger) {
  13246. const result = {
  13247. audioPid: -1,
  13248. videoPid: -1,
  13249. id3Pid: -1,
  13250. segmentVideoCodec: 'avc',
  13251. segmentAudioCodec: 'aac'
  13252. };
  13253. const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  13254. const tableEnd = offset + 3 + sectionLength - 4;
  13255. // to determine where the table is, we have to figure out how
  13256. // long the program info descriptors are
  13257. const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  13258. // advance the offset to the first entry in the mapping table
  13259. offset += 12 + programInfoLength;
  13260. while (offset < tableEnd) {
  13261. const pid = parsePID(data, offset);
  13262. const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  13263. switch (data[offset]) {
  13264. case 0xcf:
  13265. // SAMPLE-AES AAC
  13266. if (!isSampleAes) {
  13267. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC', logger);
  13268. break;
  13269. }
  13270. /* falls through */
  13271. case 0x0f:
  13272. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  13273. // logger.log('AAC PID:' + pid);
  13274. if (result.audioPid === -1) {
  13275. result.audioPid = pid;
  13276. }
  13277. break;
  13278. // Packetized metadata (ID3)
  13279. case 0x15:
  13280. // logger.log('ID3 PID:' + pid);
  13281. if (result.id3Pid === -1) {
  13282. result.id3Pid = pid;
  13283. }
  13284. break;
  13285. case 0xdb:
  13286. // SAMPLE-AES AVC
  13287. if (!isSampleAes) {
  13288. logEncryptedSamplesFoundInUnencryptedStream('H.264', logger);
  13289. break;
  13290. }
  13291. /* falls through */
  13292. case 0x1b:
  13293. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  13294. // logger.log('AVC PID:' + pid);
  13295. if (result.videoPid === -1) {
  13296. result.videoPid = pid;
  13297. }
  13298. break;
  13299. // ISO/IEC 11172-3 (MPEG-1 audio)
  13300. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  13301. case 0x03:
  13302. case 0x04:
  13303. // logger.log('MPEG PID:' + pid);
  13304. if (!typeSupported.mpeg && !typeSupported.mp3) {
  13305. logger.log('MPEG audio found, not supported in this browser');
  13306. } else if (result.audioPid === -1) {
  13307. result.audioPid = pid;
  13308. result.segmentAudioCodec = 'mp3';
  13309. }
  13310. break;
  13311. case 0xc1:
  13312. // SAMPLE-AES AC3
  13313. if (!isSampleAes) {
  13314. logEncryptedSamplesFoundInUnencryptedStream('AC-3', logger);
  13315. break;
  13316. }
  13317. /* falls through */
  13318. case 0x81:
  13319. {
  13320. if (!typeSupported.ac3) {
  13321. logger.log('AC-3 audio found, not supported in this browser');
  13322. } else if (result.audioPid === -1) {
  13323. result.audioPid = pid;
  13324. result.segmentAudioCodec = 'ac3';
  13325. }
  13326. }
  13327. break;
  13328. case 0x06:
  13329. // stream_type 6 can mean a lot of different things in case of DVB.
  13330. // We need to look at the descriptors. Right now, we're only interested
  13331. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  13332. // an audio PID yet.
  13333. if (result.audioPid === -1 && esInfoLength > 0) {
  13334. let parsePos = offset + 5;
  13335. let remaining = esInfoLength;
  13336. while (remaining > 2) {
  13337. const descriptorId = data[parsePos];
  13338. switch (descriptorId) {
  13339. case 0x6a:
  13340. // DVB Descriptor for AC-3
  13341. {
  13342. if (typeSupported.ac3 !== true) {
  13343. logger.log('AC-3 audio found, not supported in this browser for now');
  13344. } else {
  13345. result.audioPid = pid;
  13346. result.segmentAudioCodec = 'ac3';
  13347. }
  13348. }
  13349. break;
  13350. }
  13351. const descriptorLen = data[parsePos + 1] + 2;
  13352. parsePos += descriptorLen;
  13353. remaining -= descriptorLen;
  13354. }
  13355. }
  13356. break;
  13357. case 0xc2: // SAMPLE-AES EC3
  13358. /* falls through */
  13359. case 0x87:
  13360. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'), undefined, logger);
  13361. return result;
  13362. case 0x24:
  13363. // ITU-T Rec. H.265 and ISO/IEC 23008-2 (HEVC)
  13364. {
  13365. if (result.videoPid === -1) {
  13366. result.videoPid = pid;
  13367. result.segmentVideoCodec = 'hevc';
  13368. logger.log('HEVC in M2TS found');
  13369. }
  13370. }
  13371. break;
  13372. }
  13373. // move to the next table entry
  13374. // skip past the elementary stream descriptors, if present
  13375. offset += esInfoLength + 5;
  13376. }
  13377. return result;
  13378. }
  13379. function emitParsingError(observer, error, levelRetry, logger) {
  13380. logger.warn(`parsing error: ${error.message}`);
  13381. observer.emit(Events.ERROR, Events.ERROR, {
  13382. type: ErrorTypes.MEDIA_ERROR,
  13383. details: ErrorDetails.FRAG_PARSING_ERROR,
  13384. fatal: false,
  13385. levelRetry,
  13386. error,
  13387. reason: error.message
  13388. });
  13389. }
  13390. function logEncryptedSamplesFoundInUnencryptedStream(type, logger) {
  13391. logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  13392. }
  13393. function parsePES(stream, logger) {
  13394. let i = 0;
  13395. let frag;
  13396. let pesLen;
  13397. let pesHdrLen;
  13398. let pesPts;
  13399. let pesDts;
  13400. const data = stream.data;
  13401. // safety check
  13402. if (!stream || stream.size === 0) {
  13403. return null;
  13404. }
  13405. // we might need up to 19 bytes to read PES header
  13406. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  13407. // usually only one merge is needed (and this is rare ...)
  13408. while (data[0].length < 19 && data.length > 1) {
  13409. data[0] = appendUint8Array(data[0], data[1]);
  13410. data.splice(1, 1);
  13411. }
  13412. // retrieve PTS/DTS from first fragment
  13413. frag = data[0];
  13414. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  13415. if (pesPrefix === 1) {
  13416. pesLen = (frag[4] << 8) + frag[5];
  13417. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  13418. // minus 6 : PES header size
  13419. if (pesLen && pesLen > stream.size - 6) {
  13420. return null;
  13421. }
  13422. const pesFlags = frag[7];
  13423. if (pesFlags & 0xc0) {
  13424. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  13425. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  13426. as Bitwise operators treat their operands as a sequence of 32 bits */
  13427. pesPts = (frag[9] & 0x0e) * 536870912 +
  13428. // 1 << 29
  13429. (frag[10] & 0xff) * 4194304 +
  13430. // 1 << 22
  13431. (frag[11] & 0xfe) * 16384 +
  13432. // 1 << 14
  13433. (frag[12] & 0xff) * 128 +
  13434. // 1 << 7
  13435. (frag[13] & 0xfe) / 2;
  13436. if (pesFlags & 0x40) {
  13437. pesDts = (frag[14] & 0x0e) * 536870912 +
  13438. // 1 << 29
  13439. (frag[15] & 0xff) * 4194304 +
  13440. // 1 << 22
  13441. (frag[16] & 0xfe) * 16384 +
  13442. // 1 << 14
  13443. (frag[17] & 0xff) * 128 +
  13444. // 1 << 7
  13445. (frag[18] & 0xfe) / 2;
  13446. if (pesPts - pesDts > 60 * 90000) {
  13447. logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);
  13448. pesPts = pesDts;
  13449. }
  13450. } else {
  13451. pesDts = pesPts;
  13452. }
  13453. }
  13454. pesHdrLen = frag[8];
  13455. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  13456. let payloadStartOffset = pesHdrLen + 9;
  13457. if (stream.size <= payloadStartOffset) {
  13458. return null;
  13459. }
  13460. stream.size -= payloadStartOffset;
  13461. // reassemble PES packet
  13462. const pesData = new Uint8Array(stream.size);
  13463. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  13464. frag = data[j];
  13465. let len = frag.byteLength;
  13466. if (payloadStartOffset) {
  13467. if (payloadStartOffset > len) {
  13468. // trim full frag if PES header bigger than frag
  13469. payloadStartOffset -= len;
  13470. continue;
  13471. } else {
  13472. // trim partial frag if PES header smaller than frag
  13473. frag = frag.subarray(payloadStartOffset);
  13474. len -= payloadStartOffset;
  13475. payloadStartOffset = 0;
  13476. }
  13477. }
  13478. pesData.set(frag, i);
  13479. i += len;
  13480. }
  13481. if (pesLen) {
  13482. // payload size : remove PES header + PES extension
  13483. pesLen -= pesHdrLen + 3;
  13484. }
  13485. return {
  13486. data: pesData,
  13487. pts: pesPts,
  13488. dts: pesDts,
  13489. len: pesLen
  13490. };
  13491. }
  13492. return null;
  13493. }
  13494. /**
  13495. * AAC helper
  13496. */
  13497. class AAC {
  13498. static getSilentFrame(codec, channelCount) {
  13499. switch (codec) {
  13500. case 'mp4a.40.2':
  13501. if (channelCount === 1) {
  13502. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  13503. } else if (channelCount === 2) {
  13504. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  13505. } else if (channelCount === 3) {
  13506. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  13507. } else if (channelCount === 4) {
  13508. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  13509. } else if (channelCount === 5) {
  13510. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  13511. } else if (channelCount === 6) {
  13512. 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]);
  13513. }
  13514. break;
  13515. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  13516. default:
  13517. if (channelCount === 1) {
  13518. // 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
  13519. 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]);
  13520. } else if (channelCount === 2) {
  13521. // 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
  13522. 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]);
  13523. } else if (channelCount === 3) {
  13524. // 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
  13525. 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]);
  13526. }
  13527. break;
  13528. }
  13529. return undefined;
  13530. }
  13531. }
  13532. /**
  13533. * Generate MP4 Box
  13534. */
  13535. const UINT32_MAX = Math.pow(2, 32) - 1;
  13536. class MP4 {
  13537. static init() {
  13538. MP4.types = {
  13539. avc1: [],
  13540. // codingname
  13541. avcC: [],
  13542. hvc1: [],
  13543. hvcC: [],
  13544. btrt: [],
  13545. dinf: [],
  13546. dref: [],
  13547. esds: [],
  13548. ftyp: [],
  13549. hdlr: [],
  13550. mdat: [],
  13551. mdhd: [],
  13552. mdia: [],
  13553. mfhd: [],
  13554. minf: [],
  13555. moof: [],
  13556. moov: [],
  13557. mp4a: [],
  13558. '.mp3': [],
  13559. dac3: [],
  13560. 'ac-3': [],
  13561. mvex: [],
  13562. mvhd: [],
  13563. pasp: [],
  13564. sdtp: [],
  13565. stbl: [],
  13566. stco: [],
  13567. stsc: [],
  13568. stsd: [],
  13569. stsz: [],
  13570. stts: [],
  13571. tfdt: [],
  13572. tfhd: [],
  13573. traf: [],
  13574. trak: [],
  13575. trun: [],
  13576. trex: [],
  13577. tkhd: [],
  13578. vmhd: [],
  13579. smhd: []
  13580. };
  13581. let i;
  13582. for (i in MP4.types) {
  13583. if (MP4.types.hasOwnProperty(i)) {
  13584. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  13585. }
  13586. }
  13587. const videoHdlr = new Uint8Array([0x00,
  13588. // version 0
  13589. 0x00, 0x00, 0x00,
  13590. // flags
  13591. 0x00, 0x00, 0x00, 0x00,
  13592. // pre_defined
  13593. 0x76, 0x69, 0x64, 0x65,
  13594. // handler_type: 'vide'
  13595. 0x00, 0x00, 0x00, 0x00,
  13596. // reserved
  13597. 0x00, 0x00, 0x00, 0x00,
  13598. // reserved
  13599. 0x00, 0x00, 0x00, 0x00,
  13600. // reserved
  13601. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  13602. ]);
  13603. const audioHdlr = new Uint8Array([0x00,
  13604. // version 0
  13605. 0x00, 0x00, 0x00,
  13606. // flags
  13607. 0x00, 0x00, 0x00, 0x00,
  13608. // pre_defined
  13609. 0x73, 0x6f, 0x75, 0x6e,
  13610. // handler_type: 'soun'
  13611. 0x00, 0x00, 0x00, 0x00,
  13612. // reserved
  13613. 0x00, 0x00, 0x00, 0x00,
  13614. // reserved
  13615. 0x00, 0x00, 0x00, 0x00,
  13616. // reserved
  13617. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  13618. ]);
  13619. MP4.HDLR_TYPES = {
  13620. video: videoHdlr,
  13621. audio: audioHdlr
  13622. };
  13623. const dref = new Uint8Array([0x00,
  13624. // version 0
  13625. 0x00, 0x00, 0x00,
  13626. // flags
  13627. 0x00, 0x00, 0x00, 0x01,
  13628. // entry_count
  13629. 0x00, 0x00, 0x00, 0x0c,
  13630. // entry_size
  13631. 0x75, 0x72, 0x6c, 0x20,
  13632. // 'url' type
  13633. 0x00,
  13634. // version 0
  13635. 0x00, 0x00, 0x01 // entry_flags
  13636. ]);
  13637. const stco = new Uint8Array([0x00,
  13638. // version
  13639. 0x00, 0x00, 0x00,
  13640. // flags
  13641. 0x00, 0x00, 0x00, 0x00 // entry_count
  13642. ]);
  13643. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  13644. MP4.STSZ = new Uint8Array([0x00,
  13645. // version
  13646. 0x00, 0x00, 0x00,
  13647. // flags
  13648. 0x00, 0x00, 0x00, 0x00,
  13649. // sample_size
  13650. 0x00, 0x00, 0x00, 0x00 // sample_count
  13651. ]);
  13652. MP4.VMHD = new Uint8Array([0x00,
  13653. // version
  13654. 0x00, 0x00, 0x01,
  13655. // flags
  13656. 0x00, 0x00,
  13657. // graphicsmode
  13658. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  13659. ]);
  13660. MP4.SMHD = new Uint8Array([0x00,
  13661. // version
  13662. 0x00, 0x00, 0x00,
  13663. // flags
  13664. 0x00, 0x00,
  13665. // balance
  13666. 0x00, 0x00 // reserved
  13667. ]);
  13668. MP4.STSD = new Uint8Array([0x00,
  13669. // version 0
  13670. 0x00, 0x00, 0x00,
  13671. // flags
  13672. 0x00, 0x00, 0x00, 0x01]); // entry_count
  13673. const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  13674. const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  13675. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  13676. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  13677. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  13678. }
  13679. static box(type, ...payload) {
  13680. let size = 8;
  13681. let i = payload.length;
  13682. const len = i;
  13683. // calculate the total size we need to allocate
  13684. while (i--) {
  13685. size += payload[i].byteLength;
  13686. }
  13687. const result = new Uint8Array(size);
  13688. result[0] = size >> 24 & 0xff;
  13689. result[1] = size >> 16 & 0xff;
  13690. result[2] = size >> 8 & 0xff;
  13691. result[3] = size & 0xff;
  13692. result.set(type, 4);
  13693. // copy the payload into the result
  13694. for (i = 0, size = 8; i < len; i++) {
  13695. // copy payload[i] array @ offset size
  13696. result.set(payload[i], size);
  13697. size += payload[i].byteLength;
  13698. }
  13699. return result;
  13700. }
  13701. static hdlr(type) {
  13702. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  13703. }
  13704. static mdat(data) {
  13705. return MP4.box(MP4.types.mdat, data);
  13706. }
  13707. static mdhd(timescale, duration) {
  13708. duration *= timescale;
  13709. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13710. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13711. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  13712. // version 1
  13713. 0x00, 0x00, 0x00,
  13714. // flags
  13715. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13716. // creation_time
  13717. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13718. // modification_time
  13719. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  13720. // timescale
  13721. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  13722. // 'und' language (undetermined)
  13723. 0x00, 0x00]));
  13724. }
  13725. static mdia(track) {
  13726. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  13727. }
  13728. static mfhd(sequenceNumber) {
  13729. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  13730. // flags
  13731. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  13732. ]));
  13733. }
  13734. static minf(track) {
  13735. if (track.type === 'audio') {
  13736. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  13737. } else {
  13738. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  13739. }
  13740. }
  13741. static moof(sn, baseMediaDecodeTime, track) {
  13742. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  13743. }
  13744. static moov(tracks) {
  13745. let i = tracks.length;
  13746. const boxes = [];
  13747. while (i--) {
  13748. boxes[i] = MP4.trak(tracks[i]);
  13749. }
  13750. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  13751. }
  13752. static mvex(tracks) {
  13753. let i = tracks.length;
  13754. const boxes = [];
  13755. while (i--) {
  13756. boxes[i] = MP4.trex(tracks[i]);
  13757. }
  13758. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  13759. }
  13760. static mvhd(timescale, duration) {
  13761. duration *= timescale;
  13762. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13763. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13764. const bytes = new Uint8Array([0x01,
  13765. // version 1
  13766. 0x00, 0x00, 0x00,
  13767. // flags
  13768. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13769. // creation_time
  13770. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13771. // modification_time
  13772. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  13773. // timescale
  13774. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  13775. // 1.0 rate
  13776. 0x01, 0x00,
  13777. // 1.0 volume
  13778. 0x00, 0x00,
  13779. // reserved
  13780. 0x00, 0x00, 0x00, 0x00,
  13781. // reserved
  13782. 0x00, 0x00, 0x00, 0x00,
  13783. // reserved
  13784. 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,
  13785. // transformation: unity matrix
  13786. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13787. // pre_defined
  13788. 0xff, 0xff, 0xff, 0xff // next_track_ID
  13789. ]);
  13790. return MP4.box(MP4.types.mvhd, bytes);
  13791. }
  13792. static sdtp(track) {
  13793. const samples = track.samples || [];
  13794. const bytes = new Uint8Array(4 + samples.length);
  13795. let i;
  13796. let flags;
  13797. // leave the full box header (4 bytes) all zero
  13798. // write the sample table
  13799. for (i = 0; i < samples.length; i++) {
  13800. flags = samples[i].flags;
  13801. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  13802. }
  13803. return MP4.box(MP4.types.sdtp, bytes);
  13804. }
  13805. static stbl(track) {
  13806. 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));
  13807. }
  13808. static avc1(track) {
  13809. let sps = [];
  13810. let pps = [];
  13811. let i;
  13812. let data;
  13813. let len;
  13814. // assemble the SPSs
  13815. for (i = 0; i < track.sps.length; i++) {
  13816. data = track.sps[i];
  13817. len = data.byteLength;
  13818. sps.push(len >>> 8 & 0xff);
  13819. sps.push(len & 0xff);
  13820. // SPS
  13821. sps = sps.concat(Array.prototype.slice.call(data));
  13822. }
  13823. // assemble the PPSs
  13824. for (i = 0; i < track.pps.length; i++) {
  13825. data = track.pps[i];
  13826. len = data.byteLength;
  13827. pps.push(len >>> 8 & 0xff);
  13828. pps.push(len & 0xff);
  13829. pps = pps.concat(Array.prototype.slice.call(data));
  13830. }
  13831. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  13832. // version
  13833. sps[3],
  13834. // profile
  13835. sps[4],
  13836. // profile compat
  13837. sps[5],
  13838. // level
  13839. 0xfc | 3,
  13840. // lengthSizeMinusOne, hard-coded to 4 bytes
  13841. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  13842. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  13843. ]).concat(pps))); // "PPS"
  13844. const width = track.width;
  13845. const height = track.height;
  13846. const hSpacing = track.pixelRatio[0];
  13847. const vSpacing = track.pixelRatio[1];
  13848. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  13849. // reserved
  13850. 0x00, 0x00, 0x00,
  13851. // reserved
  13852. 0x00, 0x01,
  13853. // data_reference_index
  13854. 0x00, 0x00,
  13855. // pre_defined
  13856. 0x00, 0x00,
  13857. // reserved
  13858. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13859. // pre_defined
  13860. width >> 8 & 0xff, width & 0xff,
  13861. // width
  13862. height >> 8 & 0xff, height & 0xff,
  13863. // height
  13864. 0x00, 0x48, 0x00, 0x00,
  13865. // horizresolution
  13866. 0x00, 0x48, 0x00, 0x00,
  13867. // vertresolution
  13868. 0x00, 0x00, 0x00, 0x00,
  13869. // reserved
  13870. 0x00, 0x01,
  13871. // frame_count
  13872. 0x12, 0x64, 0x61, 0x69, 0x6c,
  13873. // dailymotion/hls.js
  13874. 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,
  13875. // compressorname
  13876. 0x00, 0x18,
  13877. // depth = 24
  13878. 0x11, 0x11]),
  13879. // pre_defined = -1
  13880. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  13881. // bufferSizeDB
  13882. 0x00, 0x2d, 0xc6, 0xc0,
  13883. // maxBitrate
  13884. 0x00, 0x2d, 0xc6, 0xc0])),
  13885. // avgBitrate
  13886. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  13887. // hSpacing
  13888. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  13889. // vSpacing
  13890. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  13891. }
  13892. static esds(track) {
  13893. const config = track.config;
  13894. return new Uint8Array([0x00,
  13895. // version 0
  13896. 0x00, 0x00, 0x00,
  13897. // flags
  13898. 0x03,
  13899. // descriptor_type
  13900. 0x19,
  13901. // length
  13902. 0x00, 0x01,
  13903. // es_id
  13904. 0x00,
  13905. // stream_priority
  13906. 0x04,
  13907. // descriptor_type
  13908. 0x11,
  13909. // length
  13910. 0x40,
  13911. // codec : mpeg4_audio
  13912. 0x15,
  13913. // stream_type
  13914. 0x00, 0x00, 0x00,
  13915. // buffer_size
  13916. 0x00, 0x00, 0x00, 0x00,
  13917. // maxBitrate
  13918. 0x00, 0x00, 0x00, 0x00,
  13919. // avgBitrate
  13920. 0x05,
  13921. // descriptor_type
  13922. 0x02,
  13923. // length
  13924. ...config, 0x06, 0x01, 0x02 // GASpecificConfig)); // length + audio config descriptor
  13925. ]);
  13926. }
  13927. static audioStsd(track) {
  13928. const samplerate = track.samplerate || 0;
  13929. return new Uint8Array([0x00, 0x00, 0x00,
  13930. // reserved
  13931. 0x00, 0x00, 0x00,
  13932. // reserved
  13933. 0x00, 0x01,
  13934. // data_reference_index
  13935. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13936. // reserved
  13937. 0x00, track.channelCount || 0,
  13938. // channelcount
  13939. 0x00, 0x10,
  13940. // sampleSize:16bits
  13941. 0x00, 0x00, 0x00, 0x00,
  13942. // reserved2
  13943. samplerate >> 8 & 0xff, samplerate & 0xff,
  13944. //
  13945. 0x00, 0x00]);
  13946. }
  13947. static mp4a(track) {
  13948. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  13949. }
  13950. static mp3(track) {
  13951. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  13952. }
  13953. static ac3(track) {
  13954. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  13955. }
  13956. static stsd(track) {
  13957. const {
  13958. segmentCodec
  13959. } = track;
  13960. if (track.type === 'audio') {
  13961. if (segmentCodec === 'aac') {
  13962. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  13963. }
  13964. if (segmentCodec === 'ac3' && track.config) {
  13965. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  13966. }
  13967. if (segmentCodec === 'mp3' && track.codec === 'mp3') {
  13968. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  13969. }
  13970. } else {
  13971. if (track.pps && track.sps) {
  13972. if (segmentCodec === 'avc') {
  13973. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  13974. }
  13975. if (segmentCodec === 'hevc' && track.vps) {
  13976. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track));
  13977. }
  13978. } else {
  13979. throw new Error(`video track missing pps or sps`);
  13980. }
  13981. }
  13982. throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);
  13983. }
  13984. static tkhd(track) {
  13985. const id = track.id;
  13986. const duration = (track.duration || 0) * (track.timescale || 0);
  13987. const width = track.width || 0;
  13988. const height = track.height || 0;
  13989. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13990. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13991. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  13992. // version 1
  13993. 0x00, 0x00, 0x07,
  13994. // flags
  13995. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13996. // creation_time
  13997. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13998. // modification_time
  13999. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14000. // track_ID
  14001. 0x00, 0x00, 0x00, 0x00,
  14002. // reserved
  14003. 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,
  14004. // reserved
  14005. 0x00, 0x00,
  14006. // layer
  14007. 0x00, 0x00,
  14008. // alternate_group
  14009. 0x00, 0x00,
  14010. // non-audio track volume
  14011. 0x00, 0x00,
  14012. // reserved
  14013. 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,
  14014. // transformation: unity matrix
  14015. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  14016. // width
  14017. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  14018. ]));
  14019. }
  14020. static traf(track, baseMediaDecodeTime) {
  14021. const sampleDependencyTable = MP4.sdtp(track);
  14022. const id = track.id;
  14023. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  14024. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  14025. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  14026. // version 0
  14027. 0x00, 0x00, 0x00,
  14028. // flags
  14029. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  14030. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  14031. // version 1
  14032. 0x00, 0x00, 0x00,
  14033. // flags
  14034. 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 +
  14035. // tfhd
  14036. 20 +
  14037. // tfdt
  14038. 8 +
  14039. // traf header
  14040. 16 +
  14041. // mfhd
  14042. 8 +
  14043. // moof header
  14044. 8),
  14045. // mdat header
  14046. sampleDependencyTable);
  14047. }
  14048. /**
  14049. * Generate a track box.
  14050. * @param track a track definition
  14051. */
  14052. static trak(track) {
  14053. track.duration = track.duration || 0xffffffff;
  14054. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  14055. }
  14056. static trex(track) {
  14057. const id = track.id;
  14058. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  14059. // version 0
  14060. 0x00, 0x00, 0x00,
  14061. // flags
  14062. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14063. // track_ID
  14064. 0x00, 0x00, 0x00, 0x01,
  14065. // default_sample_description_index
  14066. 0x00, 0x00, 0x00, 0x00,
  14067. // default_sample_duration
  14068. 0x00, 0x00, 0x00, 0x00,
  14069. // default_sample_size
  14070. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  14071. ]));
  14072. }
  14073. static trun(track, offset) {
  14074. const samples = track.samples || [];
  14075. const len = samples.length;
  14076. const arraylen = 12 + 16 * len;
  14077. const array = new Uint8Array(arraylen);
  14078. let i;
  14079. let sample;
  14080. let duration;
  14081. let size;
  14082. let flags;
  14083. let cts;
  14084. offset += 8 + arraylen;
  14085. array.set([track.type === 'video' ? 0x01 : 0x00,
  14086. // version 1 for video with signed-int sample_composition_time_offset
  14087. 0x00, 0x0f, 0x01,
  14088. // flags
  14089. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  14090. // sample_count
  14091. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  14092. ], 0);
  14093. for (i = 0; i < len; i++) {
  14094. sample = samples[i];
  14095. duration = sample.duration;
  14096. size = sample.size;
  14097. flags = sample.flags;
  14098. cts = sample.cts;
  14099. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  14100. // sample_duration
  14101. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  14102. // sample_size
  14103. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  14104. // sample_flags
  14105. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  14106. ], 12 + 16 * i);
  14107. }
  14108. return MP4.box(MP4.types.trun, array);
  14109. }
  14110. static initSegment(tracks) {
  14111. if (!MP4.types) {
  14112. MP4.init();
  14113. }
  14114. const movie = MP4.moov(tracks);
  14115. const result = appendUint8Array(MP4.FTYP, movie);
  14116. return result;
  14117. }
  14118. static hvc1(track) {
  14119. const ps = track.params;
  14120. const units = [track.vps, track.sps, track.pps];
  14121. const NALuLengthSize = 4;
  14122. const config = new Uint8Array([0x01, ps.general_profile_space << 6 | (ps.general_tier_flag ? 32 : 0) | ps.general_profile_idc, ps.general_profile_compatibility_flags[0], ps.general_profile_compatibility_flags[1], ps.general_profile_compatibility_flags[2], ps.general_profile_compatibility_flags[3], ps.general_constraint_indicator_flags[0], ps.general_constraint_indicator_flags[1], ps.general_constraint_indicator_flags[2], ps.general_constraint_indicator_flags[3], ps.general_constraint_indicator_flags[4], ps.general_constraint_indicator_flags[5], ps.general_level_idc, 240 | ps.min_spatial_segmentation_idc >> 8, 255 & ps.min_spatial_segmentation_idc, 252 | ps.parallelismType, 252 | ps.chroma_format_idc, 248 | ps.bit_depth_luma_minus8, 248 | ps.bit_depth_chroma_minus8, 0x00, parseInt(ps.frame_rate.fps), NALuLengthSize - 1 | ps.temporal_id_nested << 2 | ps.num_temporal_layers << 3 | (ps.frame_rate.fixed ? 64 : 0), units.length]);
  14123. // compute hvcC size in bytes
  14124. let length = config.length;
  14125. for (let i = 0; i < units.length; i += 1) {
  14126. length += 3;
  14127. for (let j = 0; j < units[i].length; j += 1) {
  14128. length += 2 + units[i][j].length;
  14129. }
  14130. }
  14131. const hvcC = new Uint8Array(length);
  14132. hvcC.set(config, 0);
  14133. length = config.length;
  14134. // append parameter set units: one vps, one or more sps and pps
  14135. const iMax = units.length - 1;
  14136. for (let i = 0; i < units.length; i += 1) {
  14137. hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0x00, units[i].length]), length);
  14138. length += 3;
  14139. for (let j = 0; j < units[i].length; j += 1) {
  14140. hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);
  14141. length += 2;
  14142. hvcC.set(units[i][j], length);
  14143. length += units[i][j].length;
  14144. }
  14145. }
  14146. const hvcc = MP4.box(MP4.types.hvcC, hvcC);
  14147. const width = track.width;
  14148. const height = track.height;
  14149. const hSpacing = track.pixelRatio[0];
  14150. const vSpacing = track.pixelRatio[1];
  14151. return MP4.box(MP4.types.hvc1, new Uint8Array([0x00, 0x00, 0x00,
  14152. // reserved
  14153. 0x00, 0x00, 0x00,
  14154. // reserved
  14155. 0x00, 0x01,
  14156. // data_reference_index
  14157. 0x00, 0x00,
  14158. // pre_defined
  14159. 0x00, 0x00,
  14160. // reserved
  14161. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14162. // pre_defined
  14163. width >> 8 & 0xff, width & 0xff,
  14164. // width
  14165. height >> 8 & 0xff, height & 0xff,
  14166. // height
  14167. 0x00, 0x48, 0x00, 0x00,
  14168. // horizresolution
  14169. 0x00, 0x48, 0x00, 0x00,
  14170. // vertresolution
  14171. 0x00, 0x00, 0x00, 0x00,
  14172. // reserved
  14173. 0x00, 0x01,
  14174. // frame_count
  14175. 0x12, 0x64, 0x61, 0x69, 0x6c,
  14176. // dailymotion/hls.js
  14177. 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,
  14178. // compressorname
  14179. 0x00, 0x18,
  14180. // depth = 24
  14181. 0x11, 0x11]),
  14182. // pre_defined = -1
  14183. hvcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  14184. // bufferSizeDB
  14185. 0x00, 0x2d, 0xc6, 0xc0,
  14186. // maxBitrate
  14187. 0x00, 0x2d, 0xc6, 0xc0])),
  14188. // avgBitrate
  14189. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  14190. // hSpacing
  14191. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  14192. // vSpacing
  14193. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  14194. }
  14195. }
  14196. MP4.types = void 0;
  14197. MP4.HDLR_TYPES = void 0;
  14198. MP4.STTS = void 0;
  14199. MP4.STSC = void 0;
  14200. MP4.STCO = void 0;
  14201. MP4.STSZ = void 0;
  14202. MP4.VMHD = void 0;
  14203. MP4.SMHD = void 0;
  14204. MP4.STSD = void 0;
  14205. MP4.FTYP = void 0;
  14206. MP4.DINF = void 0;
  14207. const MPEG_TS_CLOCK_FREQ_HZ = 90000;
  14208. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  14209. const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  14210. return round ? Math.round(result) : result;
  14211. }
  14212. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  14213. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  14214. }
  14215. function toMsFromMpegTsClock(baseTime, round = false) {
  14216. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  14217. }
  14218. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  14219. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  14220. }
  14221. const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  14222. const AAC_SAMPLES_PER_FRAME = 1024;
  14223. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  14224. const AC3_SAMPLES_PER_FRAME = 1536;
  14225. let chromeVersion = null;
  14226. let safariWebkitVersion = null;
  14227. function createMp4Sample(isKeyframe, duration, size, cts) {
  14228. return {
  14229. duration,
  14230. size,
  14231. cts,
  14232. flags: {
  14233. isLeading: 0,
  14234. isDependedOn: 0,
  14235. hasRedundancy: 0,
  14236. degradPrio: 0,
  14237. dependsOn: isKeyframe ? 2 : 1,
  14238. isNonSync: isKeyframe ? 0 : 1
  14239. }
  14240. };
  14241. }
  14242. class MP4Remuxer extends Logger {
  14243. constructor(observer, config, typeSupported, logger) {
  14244. super('mp4-remuxer', logger);
  14245. this.observer = void 0;
  14246. this.config = void 0;
  14247. this.typeSupported = void 0;
  14248. this.ISGenerated = false;
  14249. this._initPTS = null;
  14250. this._initDTS = null;
  14251. this.nextVideoTs = null;
  14252. this.nextAudioTs = null;
  14253. this.videoSampleDuration = null;
  14254. this.isAudioContiguous = false;
  14255. this.isVideoContiguous = false;
  14256. this.videoTrackConfig = void 0;
  14257. this.observer = observer;
  14258. this.config = config;
  14259. this.typeSupported = typeSupported;
  14260. this.ISGenerated = false;
  14261. if (chromeVersion === null) {
  14262. const userAgent = navigator.userAgent || '';
  14263. const result = userAgent.match(/Chrome\/(\d+)/i);
  14264. chromeVersion = result ? parseInt(result[1]) : 0;
  14265. }
  14266. if (safariWebkitVersion === null) {
  14267. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  14268. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  14269. }
  14270. }
  14271. destroy() {
  14272. // @ts-ignore
  14273. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  14274. }
  14275. resetTimeStamp(defaultTimeStamp) {
  14276. this.log('initPTS & initDTS reset');
  14277. this._initPTS = this._initDTS = defaultTimeStamp;
  14278. }
  14279. resetNextTimestamp() {
  14280. this.log('reset next timestamp');
  14281. this.isVideoContiguous = false;
  14282. this.isAudioContiguous = false;
  14283. }
  14284. resetInitSegment() {
  14285. this.log('ISGenerated flag reset');
  14286. this.ISGenerated = false;
  14287. this.videoTrackConfig = undefined;
  14288. }
  14289. getVideoStartPts(videoSamples) {
  14290. // Get the minimum PTS value relative to the first sample's PTS, normalized for 33-bit wrapping
  14291. let rolloverDetected = false;
  14292. const firstPts = videoSamples[0].pts;
  14293. const startPTS = videoSamples.reduce((minPTS, sample) => {
  14294. let pts = sample.pts;
  14295. let delta = pts - minPTS;
  14296. if (delta < -4294967296) {
  14297. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  14298. rolloverDetected = true;
  14299. pts = normalizePts(pts, firstPts);
  14300. delta = pts - minPTS;
  14301. }
  14302. if (delta > 0) {
  14303. return minPTS;
  14304. }
  14305. return pts;
  14306. }, firstPts);
  14307. if (rolloverDetected) {
  14308. this.debug('PTS rollover detected');
  14309. }
  14310. return startPTS;
  14311. }
  14312. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  14313. let video;
  14314. let audio;
  14315. let initSegment;
  14316. let text;
  14317. let id3;
  14318. let independent;
  14319. let audioTimeOffset = timeOffset;
  14320. let videoTimeOffset = timeOffset;
  14321. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  14322. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  14323. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  14324. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  14325. // then we can remux one track without waiting for the other.
  14326. const hasAudio = audioTrack.pid > -1;
  14327. const hasVideo = videoTrack.pid > -1;
  14328. const length = videoTrack.samples.length;
  14329. const enoughAudioSamples = audioTrack.samples.length > 0;
  14330. const enoughVideoSamples = flush && length > 0 || length > 1;
  14331. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  14332. if (canRemuxAvc) {
  14333. if (this.ISGenerated) {
  14334. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  14335. const config = this.videoTrackConfig;
  14336. if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  14337. this.resetInitSegment();
  14338. }
  14339. }
  14340. if (!this.ISGenerated) {
  14341. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14342. }
  14343. const isVideoContiguous = this.isVideoContiguous;
  14344. let firstKeyFrameIndex = -1;
  14345. let firstKeyFramePTS;
  14346. if (enoughVideoSamples) {
  14347. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  14348. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  14349. independent = true;
  14350. if (firstKeyFrameIndex > 0) {
  14351. this.warn(`Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  14352. const startPTS = this.getVideoStartPts(videoTrack.samples);
  14353. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  14354. videoTrack.dropped += firstKeyFrameIndex;
  14355. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  14356. firstKeyFramePTS = videoTimeOffset;
  14357. } else if (firstKeyFrameIndex === -1) {
  14358. this.warn(`No keyframe found out of ${length} video samples`);
  14359. independent = false;
  14360. }
  14361. }
  14362. }
  14363. if (this.ISGenerated) {
  14364. if (enoughAudioSamples && enoughVideoSamples) {
  14365. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  14366. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  14367. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  14368. // drift between audio and video streams
  14369. const startPTS = this.getVideoStartPts(videoTrack.samples);
  14370. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  14371. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  14372. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  14373. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  14374. }
  14375. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  14376. if (enoughAudioSamples) {
  14377. // if initSegment was generated without audio samples, regenerate it again
  14378. if (!audioTrack.samplerate) {
  14379. this.warn('regenerate InitSegment as audio detected');
  14380. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14381. }
  14382. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  14383. if (enoughVideoSamples) {
  14384. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  14385. // if initSegment was generated without video samples, regenerate it again
  14386. if (!videoTrack.inputTimeScale) {
  14387. this.warn('regenerate InitSegment as video detected');
  14388. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14389. }
  14390. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  14391. }
  14392. } else if (enoughVideoSamples) {
  14393. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  14394. }
  14395. if (video) {
  14396. video.firstKeyFrame = firstKeyFrameIndex;
  14397. video.independent = firstKeyFrameIndex !== -1;
  14398. video.firstKeyFramePTS = firstKeyFramePTS;
  14399. }
  14400. }
  14401. }
  14402. // Allow ID3 and text to remux, even if more audio/video samples are required
  14403. if (this.ISGenerated && this._initPTS && this._initDTS) {
  14404. if (id3Track.samples.length) {
  14405. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  14406. }
  14407. if (textTrack.samples.length) {
  14408. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  14409. }
  14410. }
  14411. return {
  14412. audio,
  14413. video,
  14414. initSegment,
  14415. independent,
  14416. text,
  14417. id3
  14418. };
  14419. }
  14420. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  14421. const audioSamples = audioTrack.samples;
  14422. const videoSamples = videoTrack.samples;
  14423. const typeSupported = this.typeSupported;
  14424. const tracks = {};
  14425. const _initPTS = this._initPTS;
  14426. let computePTSDTS = !_initPTS || accurateTimeOffset;
  14427. let container = 'audio/mp4';
  14428. let initPTS;
  14429. let initDTS;
  14430. let timescale;
  14431. let trackId;
  14432. if (computePTSDTS) {
  14433. initPTS = initDTS = Infinity;
  14434. }
  14435. if (audioTrack.config && audioSamples.length) {
  14436. // let's use audio sampling rate as MP4 time scale.
  14437. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  14438. // using audio sampling rate here helps having an integer MP4 frame duration
  14439. // this avoids potential rounding issue and AV sync issue
  14440. audioTrack.timescale = audioTrack.samplerate;
  14441. switch (audioTrack.segmentCodec) {
  14442. case 'mp3':
  14443. if (typeSupported.mpeg) {
  14444. // Chrome and Safari
  14445. container = 'audio/mpeg';
  14446. audioTrack.codec = '';
  14447. } else if (typeSupported.mp3) {
  14448. // Firefox
  14449. audioTrack.codec = 'mp3';
  14450. }
  14451. break;
  14452. case 'ac3':
  14453. audioTrack.codec = 'ac-3';
  14454. break;
  14455. }
  14456. tracks.audio = {
  14457. id: 'audio',
  14458. container: container,
  14459. codec: audioTrack.codec,
  14460. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  14461. metadata: {
  14462. channelCount: audioTrack.channelCount
  14463. }
  14464. };
  14465. if (computePTSDTS) {
  14466. trackId = audioTrack.id;
  14467. timescale = audioTrack.inputTimeScale;
  14468. if (!_initPTS || timescale !== _initPTS.timescale) {
  14469. // remember first PTS of this demuxing context. for audio, PTS = DTS
  14470. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  14471. } else {
  14472. computePTSDTS = false;
  14473. }
  14474. }
  14475. }
  14476. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  14477. // let's use input time scale as MP4 video timescale
  14478. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  14479. videoTrack.timescale = videoTrack.inputTimeScale;
  14480. tracks.video = {
  14481. id: 'main',
  14482. container: 'video/mp4',
  14483. codec: videoTrack.codec,
  14484. initSegment: MP4.initSegment([videoTrack]),
  14485. metadata: {
  14486. width: videoTrack.width,
  14487. height: videoTrack.height
  14488. }
  14489. };
  14490. if (computePTSDTS) {
  14491. trackId = videoTrack.id;
  14492. timescale = videoTrack.inputTimeScale;
  14493. if (!_initPTS || timescale !== _initPTS.timescale) {
  14494. const startPTS = this.getVideoStartPts(videoSamples);
  14495. const startOffset = Math.round(timescale * timeOffset);
  14496. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  14497. initPTS = Math.min(initPTS, startPTS - startOffset);
  14498. } else {
  14499. computePTSDTS = false;
  14500. }
  14501. }
  14502. this.videoTrackConfig = {
  14503. width: videoTrack.width,
  14504. height: videoTrack.height,
  14505. pixelRatio: videoTrack.pixelRatio
  14506. };
  14507. }
  14508. if (Object.keys(tracks).length) {
  14509. this.ISGenerated = true;
  14510. if (computePTSDTS) {
  14511. this._initPTS = {
  14512. baseTime: initPTS,
  14513. timescale: timescale
  14514. };
  14515. this._initDTS = {
  14516. baseTime: initDTS,
  14517. timescale: timescale
  14518. };
  14519. } else {
  14520. initPTS = timescale = undefined;
  14521. }
  14522. return {
  14523. tracks,
  14524. initPTS,
  14525. timescale,
  14526. trackId
  14527. };
  14528. }
  14529. }
  14530. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  14531. const timeScale = track.inputTimeScale;
  14532. const inputSamples = track.samples;
  14533. const outputSamples = [];
  14534. const nbSamples = inputSamples.length;
  14535. const initPTS = this._initPTS;
  14536. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  14537. let nextVideoTs = this.nextVideoTs;
  14538. let offset = 8;
  14539. let mp4SampleDuration = this.videoSampleDuration;
  14540. let firstDTS;
  14541. let lastDTS;
  14542. let minPTS = Number.POSITIVE_INFINITY;
  14543. let maxPTS = Number.NEGATIVE_INFINITY;
  14544. let sortSamples = false;
  14545. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  14546. if (!contiguous || nextVideoTs === null) {
  14547. const pts = initTime + timeOffset * timeScale;
  14548. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  14549. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15000) {
  14550. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  14551. contiguous = true;
  14552. } else {
  14553. // if not contiguous, let's use target timeOffset
  14554. nextVideoTs = pts - cts - initTime;
  14555. }
  14556. }
  14557. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  14558. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  14559. const nextVideoPts = nextVideoTs + initTime;
  14560. for (let i = 0; i < nbSamples; i++) {
  14561. const sample = inputSamples[i];
  14562. sample.pts = normalizePts(sample.pts, nextVideoPts);
  14563. sample.dts = normalizePts(sample.dts, nextVideoPts);
  14564. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  14565. sortSamples = true;
  14566. }
  14567. }
  14568. // sort video samples by DTS then PTS then demux id order
  14569. if (sortSamples) {
  14570. inputSamples.sort(function (a, b) {
  14571. const deltadts = a.dts - b.dts;
  14572. const deltapts = a.pts - b.pts;
  14573. return deltadts || deltapts;
  14574. });
  14575. }
  14576. // Get first/last DTS
  14577. firstDTS = inputSamples[0].dts;
  14578. lastDTS = inputSamples[inputSamples.length - 1].dts;
  14579. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  14580. // set this constant duration as being the avg delta between consecutive DTS.
  14581. const inputDuration = lastDTS - firstDTS;
  14582. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  14583. // if fragment are contiguous, detect hole/overlapping between fragments
  14584. if (contiguous) {
  14585. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  14586. const delta = firstDTS - nextVideoPts;
  14587. const foundHole = delta > averageSampleDuration;
  14588. const foundOverlap = delta < -1;
  14589. if (foundHole || foundOverlap) {
  14590. if (foundHole) {
  14591. this.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  14592. } else {
  14593. this.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  14594. }
  14595. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  14596. firstDTS = nextVideoPts;
  14597. const firstPTS = inputSamples[0].pts - delta;
  14598. if (foundHole) {
  14599. inputSamples[0].dts = firstDTS;
  14600. inputSamples[0].pts = firstPTS;
  14601. } else {
  14602. let isPTSOrderRetained = true;
  14603. for (let i = 0; i < inputSamples.length; i++) {
  14604. if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {
  14605. break;
  14606. }
  14607. const prevPTS = inputSamples[i].pts;
  14608. inputSamples[i].dts -= delta;
  14609. inputSamples[i].pts -= delta;
  14610. // check to see if this sample's PTS order has changed
  14611. // relative to the next one
  14612. if (i < inputSamples.length - 1) {
  14613. const nextSamplePTS = inputSamples[i + 1].pts;
  14614. const currentSamplePTS = inputSamples[i].pts;
  14615. const currentOrder = nextSamplePTS <= currentSamplePTS;
  14616. const prevOrder = nextSamplePTS <= prevPTS;
  14617. isPTSOrderRetained = currentOrder == prevOrder;
  14618. }
  14619. }
  14620. }
  14621. this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  14622. }
  14623. }
  14624. }
  14625. firstDTS = Math.max(0, firstDTS);
  14626. let nbNalu = 0;
  14627. let naluLen = 0;
  14628. let dtsStep = firstDTS;
  14629. for (let i = 0; i < nbSamples; i++) {
  14630. // compute total/avc sample length and nb of NAL units
  14631. const sample = inputSamples[i];
  14632. const units = sample.units;
  14633. const nbUnits = units.length;
  14634. let sampleLen = 0;
  14635. for (let j = 0; j < nbUnits; j++) {
  14636. sampleLen += units[j].data.length;
  14637. }
  14638. naluLen += sampleLen;
  14639. nbNalu += nbUnits;
  14640. sample.length = sampleLen;
  14641. // ensure sample monotonic DTS
  14642. if (sample.dts < dtsStep) {
  14643. sample.dts = dtsStep;
  14644. dtsStep += averageSampleDuration / 4 | 0 || 1;
  14645. } else {
  14646. dtsStep = sample.dts;
  14647. }
  14648. minPTS = Math.min(sample.pts, minPTS);
  14649. maxPTS = Math.max(sample.pts, maxPTS);
  14650. }
  14651. lastDTS = inputSamples[nbSamples - 1].dts;
  14652. /* concatenate the video data and construct the mdat in place
  14653. (need 8 more bytes to fill length and mpdat type) */
  14654. const mdatSize = naluLen + 4 * nbNalu + 8;
  14655. let mdat;
  14656. try {
  14657. mdat = new Uint8Array(mdatSize);
  14658. } catch (err) {
  14659. this.observer.emit(Events.ERROR, Events.ERROR, {
  14660. type: ErrorTypes.MUX_ERROR,
  14661. details: ErrorDetails.REMUX_ALLOC_ERROR,
  14662. fatal: false,
  14663. error: err,
  14664. bytes: mdatSize,
  14665. reason: `fail allocating video mdat ${mdatSize}`
  14666. });
  14667. return;
  14668. }
  14669. const view = new DataView(mdat.buffer);
  14670. view.setUint32(0, mdatSize);
  14671. mdat.set(MP4.types.mdat, 4);
  14672. let stretchedLastFrame = false;
  14673. let minDtsDelta = Number.POSITIVE_INFINITY;
  14674. let minPtsDelta = Number.POSITIVE_INFINITY;
  14675. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  14676. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  14677. for (let i = 0; i < nbSamples; i++) {
  14678. const VideoSample = inputSamples[i];
  14679. const VideoSampleUnits = VideoSample.units;
  14680. let mp4SampleLength = 0;
  14681. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  14682. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  14683. const unit = VideoSampleUnits[j];
  14684. const unitData = unit.data;
  14685. const unitDataLen = unit.data.byteLength;
  14686. view.setUint32(offset, unitDataLen);
  14687. offset += 4;
  14688. mdat.set(unitData, offset);
  14689. offset += unitDataLen;
  14690. mp4SampleLength += 4 + unitDataLen;
  14691. }
  14692. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  14693. let ptsDelta;
  14694. if (i < nbSamples - 1) {
  14695. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  14696. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  14697. } else {
  14698. const config = this.config;
  14699. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  14700. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  14701. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  14702. // In some cases, a segment's audio track duration may exceed the video track duration.
  14703. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  14704. // see if the delta to the next segment is longer than maxBufferHole.
  14705. // If so, playback would potentially get stuck, so we artificially inflate
  14706. // the duration of the last frame to minimize any potential gap between segments.
  14707. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  14708. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  14709. if (deltaToFrameEnd > gapTolerance) {
  14710. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  14711. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  14712. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  14713. if (mp4SampleDuration < 0) {
  14714. mp4SampleDuration = lastFrameDuration;
  14715. } else {
  14716. stretchedLastFrame = true;
  14717. }
  14718. this.log(`It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  14719. } else {
  14720. mp4SampleDuration = lastFrameDuration;
  14721. }
  14722. } else {
  14723. mp4SampleDuration = lastFrameDuration;
  14724. }
  14725. }
  14726. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  14727. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  14728. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  14729. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  14730. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  14731. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  14732. }
  14733. if (outputSamples.length) {
  14734. if (chromeVersion) {
  14735. if (chromeVersion < 70) {
  14736. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  14737. // https://code.google.com/p/chromium/issues/detail?id=229412
  14738. const flags = outputSamples[0].flags;
  14739. flags.dependsOn = 2;
  14740. flags.isNonSync = 0;
  14741. }
  14742. } else if (safariWebkitVersion) {
  14743. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  14744. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  14745. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  14746. this.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  14747. let dts = firstDTS;
  14748. for (let i = 0, len = outputSamples.length; i < len; i++) {
  14749. const nextDts = dts + outputSamples[i].duration;
  14750. const pts = dts + outputSamples[i].cts;
  14751. if (i < len - 1) {
  14752. const nextPts = nextDts + outputSamples[i + 1].cts;
  14753. outputSamples[i].duration = nextPts - pts;
  14754. } else {
  14755. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  14756. }
  14757. outputSamples[i].cts = 0;
  14758. dts = nextDts;
  14759. }
  14760. }
  14761. }
  14762. }
  14763. // next AVC/HEVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  14764. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  14765. const endDTS = lastDTS + mp4SampleDuration;
  14766. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  14767. this.videoSampleDuration = mp4SampleDuration;
  14768. this.isVideoContiguous = true;
  14769. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  14770. samples: outputSamples
  14771. }));
  14772. const type = 'video';
  14773. const data = {
  14774. data1: moof,
  14775. data2: mdat,
  14776. startPTS: (minPTS - initTime) / timeScale,
  14777. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  14778. startDTS: (firstDTS - initTime) / timeScale,
  14779. endDTS: nextVideoTs / timeScale,
  14780. type,
  14781. hasAudio: false,
  14782. hasVideo: true,
  14783. nb: outputSamples.length,
  14784. dropped: track.dropped
  14785. };
  14786. track.samples = [];
  14787. track.dropped = 0;
  14788. return data;
  14789. }
  14790. getSamplesPerFrame(track) {
  14791. switch (track.segmentCodec) {
  14792. case 'mp3':
  14793. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  14794. case 'ac3':
  14795. return AC3_SAMPLES_PER_FRAME;
  14796. default:
  14797. return AAC_SAMPLES_PER_FRAME;
  14798. }
  14799. }
  14800. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  14801. const inputTimeScale = track.inputTimeScale;
  14802. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  14803. const scaleFactor = inputTimeScale / mp4timeScale;
  14804. const mp4SampleDuration = this.getSamplesPerFrame(track);
  14805. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  14806. const initPTS = this._initPTS;
  14807. const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  14808. const outputSamples = [];
  14809. const alignedWithVideo = videoTimeOffset !== undefined;
  14810. let inputSamples = track.samples;
  14811. let offset = rawMPEG ? 0 : 8;
  14812. let nextAudioTs = this.nextAudioTs || -1;
  14813. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  14814. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  14815. // for sake of clarity:
  14816. // consecutive fragments are frags with
  14817. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  14818. // - less than 20 audio frames distance
  14819. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  14820. // this helps ensuring audio continuity
  14821. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  14822. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  14823. const timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  14824. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9000 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  14825. // compute normalized PTS
  14826. inputSamples.forEach(function (sample) {
  14827. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  14828. });
  14829. if (!contiguous || nextAudioTs < 0) {
  14830. // filter out sample with negative PTS that are not playable anyway
  14831. // if we don't remove these negative samples, they will shift all audio samples forward.
  14832. // leading to audio overlap between current / next fragment
  14833. inputSamples = inputSamples.filter(sample => sample.pts >= 0);
  14834. // in case all samples have negative PTS, and have been filtered out, return now
  14835. if (!inputSamples.length) {
  14836. return;
  14837. }
  14838. if (videoTimeOffset === 0) {
  14839. // Set the start to match video so that start gaps larger than inputSampleDuration are filled with silence
  14840. nextAudioTs = 0;
  14841. } else if (accurateTimeOffset && !alignedWithVideo) {
  14842. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  14843. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  14844. } else {
  14845. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  14846. nextAudioTs = inputSamples[0].pts - initTime;
  14847. }
  14848. }
  14849. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  14850. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  14851. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  14852. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  14853. // frame.
  14854. if (track.segmentCodec === 'aac') {
  14855. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  14856. for (let i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  14857. // First, let's see how far off this frame is from where we expect it to be
  14858. const sample = inputSamples[i];
  14859. const pts = sample.pts;
  14860. const delta = pts - nextPts;
  14861. const duration = Math.abs(1000 * delta / inputTimeScale);
  14862. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  14863. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  14864. if (i === 0) {
  14865. this.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps marker by ${Math.round(1000 * delta / inputTimeScale)} ms.`);
  14866. this.nextAudioTs = nextAudioTs = pts - initTime;
  14867. nextPts = pts;
  14868. }
  14869. } // eslint-disable-line brace-style
  14870. // Insert missing frames if:
  14871. // 1: We're more than maxAudioFramesDrift frame away
  14872. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  14873. // 3: currentTime (aka nextPtsNorm) is not 0
  14874. // 4: remuxing with video (videoTimeOffset !== undefined)
  14875. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  14876. let missing = Math.round(delta / inputSampleDuration);
  14877. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  14878. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  14879. nextPts = pts - missing * inputSampleDuration;
  14880. while (nextPts < 0 && missing && inputSampleDuration) {
  14881. missing--;
  14882. nextPts += inputSampleDuration;
  14883. }
  14884. if (i === 0) {
  14885. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  14886. }
  14887. this.warn(`Injecting ${missing} audio frames @ ${((nextPts - initTime) / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);
  14888. for (let j = 0; j < missing; j++) {
  14889. let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  14890. if (!fillFrame) {
  14891. this.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  14892. fillFrame = sample.unit.subarray();
  14893. }
  14894. inputSamples.splice(i, 0, {
  14895. unit: fillFrame,
  14896. pts: nextPts
  14897. });
  14898. nextPts += inputSampleDuration;
  14899. i++;
  14900. }
  14901. }
  14902. sample.pts = nextPts;
  14903. nextPts += inputSampleDuration;
  14904. }
  14905. }
  14906. let firstPTS = null;
  14907. let lastPTS = null;
  14908. let mdat;
  14909. let mdatSize = 0;
  14910. let sampleLength = inputSamples.length;
  14911. while (sampleLength--) {
  14912. mdatSize += inputSamples[sampleLength].unit.byteLength;
  14913. }
  14914. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  14915. const audioSample = inputSamples[j];
  14916. const unit = audioSample.unit;
  14917. let pts = audioSample.pts;
  14918. if (lastPTS !== null) {
  14919. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  14920. // the previous sample
  14921. const prevSample = outputSamples[j - 1];
  14922. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  14923. } else {
  14924. if (contiguous && track.segmentCodec === 'aac') {
  14925. // set PTS/DTS to expected PTS/DTS
  14926. pts = nextAudioTs + initTime;
  14927. }
  14928. // remember first PTS of our audioSamples
  14929. firstPTS = pts;
  14930. if (mdatSize > 0) {
  14931. /* concatenate the audio data and construct the mdat in place
  14932. (need 8 more bytes to fill length and mdat type) */
  14933. mdatSize += offset;
  14934. try {
  14935. mdat = new Uint8Array(mdatSize);
  14936. } catch (err) {
  14937. this.observer.emit(Events.ERROR, Events.ERROR, {
  14938. type: ErrorTypes.MUX_ERROR,
  14939. details: ErrorDetails.REMUX_ALLOC_ERROR,
  14940. fatal: false,
  14941. error: err,
  14942. bytes: mdatSize,
  14943. reason: `fail allocating audio mdat ${mdatSize}`
  14944. });
  14945. return;
  14946. }
  14947. if (!rawMPEG) {
  14948. const view = new DataView(mdat.buffer);
  14949. view.setUint32(0, mdatSize);
  14950. mdat.set(MP4.types.mdat, 4);
  14951. }
  14952. } else {
  14953. // no audio samples
  14954. return;
  14955. }
  14956. }
  14957. mdat.set(unit, offset);
  14958. const unitLen = unit.byteLength;
  14959. offset += unitLen;
  14960. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  14961. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  14962. // becomes the PTS diff with the previous sample
  14963. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  14964. lastPTS = pts;
  14965. }
  14966. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  14967. const nbSamples = outputSamples.length;
  14968. if (!nbSamples) {
  14969. return;
  14970. }
  14971. // The next audio sample PTS should be equal to last sample PTS + duration
  14972. const lastSample = outputSamples[outputSamples.length - 1];
  14973. nextAudioTs = lastPTS - initTime;
  14974. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  14975. // Set the track samples from inputSamples to outputSamples before remuxing
  14976. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  14977. samples: outputSamples
  14978. }));
  14979. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  14980. track.samples = [];
  14981. const start = (firstPTS - initTime) / inputTimeScale;
  14982. const end = nextAudioTs / inputTimeScale;
  14983. const type = 'audio';
  14984. const audioData = {
  14985. data1: moof,
  14986. data2: mdat,
  14987. startPTS: start,
  14988. endPTS: end,
  14989. startDTS: start,
  14990. endDTS: end,
  14991. type,
  14992. hasAudio: true,
  14993. hasVideo: false,
  14994. nb: nbSamples
  14995. };
  14996. this.isAudioContiguous = true;
  14997. return audioData;
  14998. }
  14999. }
  15000. function normalizePts(value, reference) {
  15001. let offset;
  15002. if (reference === null) {
  15003. return value;
  15004. }
  15005. if (reference < value) {
  15006. // - 2^33
  15007. offset = -8589934592;
  15008. } else {
  15009. // + 2^33
  15010. offset = 8589934592;
  15011. }
  15012. /* PTS is 33bit (from 0 to 2^33 -1)
  15013. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  15014. PTS looping occured. fill the gap */
  15015. while (Math.abs(value - reference) > 4294967296) {
  15016. value += offset;
  15017. }
  15018. return value;
  15019. }
  15020. function findKeyframeIndex(samples) {
  15021. for (let i = 0; i < samples.length; i++) {
  15022. if (samples[i].key) {
  15023. return i;
  15024. }
  15025. }
  15026. return -1;
  15027. }
  15028. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  15029. const length = track.samples.length;
  15030. if (!length) {
  15031. return;
  15032. }
  15033. const inputTimeScale = track.inputTimeScale;
  15034. for (let index = 0; index < length; index++) {
  15035. const sample = track.samples[index];
  15036. // setting id3 pts, dts to relative time
  15037. // using this._initPTS and this._initDTS to calculate relative time
  15038. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15039. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15040. }
  15041. const samples = track.samples;
  15042. track.samples = [];
  15043. return {
  15044. samples
  15045. };
  15046. }
  15047. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  15048. const length = track.samples.length;
  15049. if (!length) {
  15050. return;
  15051. }
  15052. const inputTimeScale = track.inputTimeScale;
  15053. for (let index = 0; index < length; index++) {
  15054. const sample = track.samples[index];
  15055. // setting text pts, dts to relative time
  15056. // using this._initPTS and this._initDTS to calculate relative time
  15057. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15058. }
  15059. track.samples.sort((a, b) => a.pts - b.pts);
  15060. const samples = track.samples;
  15061. track.samples = [];
  15062. return {
  15063. samples
  15064. };
  15065. }
  15066. class PassThroughRemuxer extends Logger {
  15067. constructor(observer, config, typeSupported, logger) {
  15068. super('passthrough-remuxer', logger);
  15069. this.emitInitSegment = false;
  15070. this.audioCodec = void 0;
  15071. this.videoCodec = void 0;
  15072. this.initData = void 0;
  15073. this.initPTS = null;
  15074. this.initTracks = void 0;
  15075. this.lastEndTime = null;
  15076. this.isVideoContiguous = false;
  15077. }
  15078. destroy() {}
  15079. resetTimeStamp(defaultInitPTS) {
  15080. this.lastEndTime = null;
  15081. const initPTS = this.initPTS;
  15082. if (initPTS && defaultInitPTS) {
  15083. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  15084. return;
  15085. }
  15086. }
  15087. this.initPTS = defaultInitPTS;
  15088. }
  15089. resetNextTimestamp() {
  15090. this.isVideoContiguous = false;
  15091. this.lastEndTime = null;
  15092. }
  15093. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  15094. this.audioCodec = audioCodec;
  15095. this.videoCodec = videoCodec;
  15096. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  15097. this.emitInitSegment = true;
  15098. }
  15099. generateInitSegment(initSegment) {
  15100. let {
  15101. audioCodec,
  15102. videoCodec
  15103. } = this;
  15104. if (!(initSegment != null && initSegment.byteLength)) {
  15105. this.initTracks = undefined;
  15106. this.initData = undefined;
  15107. return;
  15108. }
  15109. const initData = this.initData = parseInitSegment(initSegment);
  15110. // Get codec from initSegment
  15111. if (initData.audio) {
  15112. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  15113. }
  15114. if (initData.video) {
  15115. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  15116. }
  15117. const tracks = {};
  15118. if (initData.audio && initData.video) {
  15119. tracks.audiovideo = {
  15120. container: 'video/mp4',
  15121. codec: audioCodec + ',' + videoCodec,
  15122. supplemental: initData.video.supplemental,
  15123. initSegment,
  15124. id: 'main'
  15125. };
  15126. } else if (initData.audio) {
  15127. tracks.audio = {
  15128. container: 'audio/mp4',
  15129. codec: audioCodec,
  15130. initSegment,
  15131. id: 'audio'
  15132. };
  15133. } else if (initData.video) {
  15134. tracks.video = {
  15135. container: 'video/mp4',
  15136. codec: videoCodec,
  15137. supplemental: initData.video.supplemental,
  15138. initSegment,
  15139. id: 'main'
  15140. };
  15141. } else {
  15142. this.warn('initSegment does not contain moov or trak boxes.');
  15143. }
  15144. this.initTracks = tracks;
  15145. }
  15146. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  15147. var _initData, _initData2;
  15148. let {
  15149. initPTS,
  15150. lastEndTime
  15151. } = this;
  15152. const result = {
  15153. audio: undefined,
  15154. video: undefined,
  15155. text: textTrack,
  15156. id3: id3Track,
  15157. initSegment: undefined
  15158. };
  15159. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  15160. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  15161. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  15162. if (!isFiniteNumber(lastEndTime)) {
  15163. lastEndTime = this.lastEndTime = timeOffset || 0;
  15164. }
  15165. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  15166. // audio or video (or both); adding it to video was an arbitrary choice.
  15167. const data = videoTrack.samples;
  15168. if (!(data != null && data.length)) {
  15169. return result;
  15170. }
  15171. const initSegment = {
  15172. initPTS: undefined,
  15173. timescale: undefined,
  15174. trackId: undefined
  15175. };
  15176. let initData = this.initData;
  15177. if (!((_initData = initData) != null && _initData.length)) {
  15178. this.generateInitSegment(data);
  15179. initData = this.initData;
  15180. }
  15181. if (!((_initData2 = initData) != null && _initData2.length)) {
  15182. // We can't remux if the initSegment could not be generated
  15183. this.warn('Failed to generate initSegment.');
  15184. return result;
  15185. }
  15186. if (this.emitInitSegment) {
  15187. initSegment.tracks = this.initTracks;
  15188. this.emitInitSegment = false;
  15189. }
  15190. const trackSampleData = getSampleData(data, initData, this);
  15191. const audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  15192. const videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  15193. const videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  15194. const audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  15195. const videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  15196. const audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  15197. let baseOffsetSamples;
  15198. let decodeTime = timeOffset;
  15199. let duration = 0;
  15200. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  15201. initSegment.trackId = initData.audio.id;
  15202. baseOffsetSamples = audioSampleTimestamps;
  15203. duration = audioEndTime - audioStartTime;
  15204. } else if (videoSampleTimestamps) {
  15205. initSegment.trackId = initData.video.id;
  15206. baseOffsetSamples = videoSampleTimestamps;
  15207. duration = videoEndTime - videoStartTime;
  15208. }
  15209. if (baseOffsetSamples) {
  15210. const timescale = baseOffsetSamples.timescale;
  15211. decodeTime = baseOffsetSamples.start / timescale;
  15212. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  15213. initSegment.timescale = timescale;
  15214. if (!initPTS) {
  15215. this.initPTS = initPTS = {
  15216. baseTime: initSegment.initPTS,
  15217. timescale,
  15218. trackId: initSegment.trackId
  15219. };
  15220. }
  15221. }
  15222. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  15223. initSegment.initPTS = decodeTime - timeOffset;
  15224. initSegment.timescale = 1;
  15225. if (initPTS && initPTS.timescale === 1) {
  15226. this.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);
  15227. }
  15228. this.initPTS = initPTS = {
  15229. baseTime: initSegment.initPTS,
  15230. timescale: 1
  15231. };
  15232. }
  15233. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  15234. const endTime = startTime + duration;
  15235. if (duration > 0) {
  15236. this.lastEndTime = endTime;
  15237. } else {
  15238. this.warn('Duration parsed from mp4 should be greater than zero');
  15239. this.resetNextTimestamp();
  15240. }
  15241. const hasAudio = !!initData.audio;
  15242. const hasVideo = !!initData.video;
  15243. let type = '';
  15244. if (hasAudio) {
  15245. type += 'audio';
  15246. }
  15247. if (hasVideo) {
  15248. type += 'video';
  15249. }
  15250. const track = {
  15251. data1: data,
  15252. startPTS: startTime,
  15253. startDTS: startTime,
  15254. endPTS: endTime,
  15255. endDTS: endTime,
  15256. type,
  15257. hasAudio,
  15258. hasVideo,
  15259. nb: 1,
  15260. dropped: 0
  15261. };
  15262. result.audio = hasAudio && !hasVideo ? track : undefined;
  15263. result.video = hasVideo ? track : undefined;
  15264. const videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  15265. if (videoSampleCount) {
  15266. const firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  15267. const independent = firstKeyFrame !== -1;
  15268. track.nb = videoSampleCount;
  15269. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  15270. track.independent = independent;
  15271. track.firstKeyFrame = firstKeyFrame;
  15272. if (independent && videoSampleTimestamps.keyFrameStart) {
  15273. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  15274. }
  15275. if (!this.isVideoContiguous) {
  15276. result.independent = independent;
  15277. }
  15278. this.isVideoContiguous || (this.isVideoContiguous = independent);
  15279. if (track.dropped) {
  15280. this.warn(`fmp4 does not start with IDR: firstIDR ${firstKeyFrame}/${videoSampleCount} dropped: ${track.dropped} start: ${track.firstKeyFramePTS || 'NA'}`);
  15281. }
  15282. }
  15283. result.initSegment = initSegment;
  15284. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  15285. if (textTrack.samples.length) {
  15286. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  15287. }
  15288. return result;
  15289. }
  15290. }
  15291. function toStartEndOrDefault(trackTimes, defaultValue, end = false) {
  15292. return (trackTimes == null ? void 0 : trackTimes.start) !== undefined ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  15293. }
  15294. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  15295. if (initPTS === null) {
  15296. return true;
  15297. }
  15298. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  15299. const minDuration = Math.max(duration, 1);
  15300. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  15301. return Math.abs(startTime - timeOffset) > minDuration;
  15302. }
  15303. function getParsedTrackCodec(track, type, logger) {
  15304. const parsedCodec = track == null ? void 0 : track.codec;
  15305. if (parsedCodec && parsedCodec.length > 4) {
  15306. return parsedCodec;
  15307. }
  15308. if (type === ElementaryStreamTypes.AUDIO) {
  15309. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  15310. return parsedCodec;
  15311. }
  15312. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  15313. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  15314. const preferManagedMediaSource = false;
  15315. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  15316. }
  15317. logger.warn(`Unhandled audio codec "${parsedCodec}" in mp4 MAP`);
  15318. return parsedCodec || 'mp4a';
  15319. }
  15320. // Provide defaults based on codec type
  15321. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  15322. logger.warn(`Unhandled video codec "${parsedCodec}" in mp4 MAP`);
  15323. return parsedCodec || 'avc1';
  15324. }
  15325. let now;
  15326. // performance.now() not available on WebWorker, at least on Safari Desktop
  15327. try {
  15328. now = self.performance.now.bind(self.performance);
  15329. } catch (err) {
  15330. now = Date.now;
  15331. }
  15332. const muxConfig = [{
  15333. demux: MP4Demuxer,
  15334. remux: PassThroughRemuxer
  15335. }, {
  15336. demux: TSDemuxer,
  15337. remux: MP4Remuxer
  15338. }, {
  15339. demux: AACDemuxer,
  15340. remux: MP4Remuxer
  15341. }, {
  15342. demux: MP3Demuxer,
  15343. remux: MP4Remuxer
  15344. }];
  15345. {
  15346. muxConfig.splice(2, 0, {
  15347. demux: AC3Demuxer,
  15348. remux: MP4Remuxer
  15349. });
  15350. }
  15351. class Transmuxer {
  15352. constructor(observer, typeSupported, config, vendor, id, logger) {
  15353. this.asyncResult = false;
  15354. this.logger = void 0;
  15355. this.observer = void 0;
  15356. this.typeSupported = void 0;
  15357. this.config = void 0;
  15358. this.id = void 0;
  15359. this.demuxer = void 0;
  15360. this.remuxer = void 0;
  15361. this.decrypter = void 0;
  15362. this.probe = void 0;
  15363. this.decryptionPromise = null;
  15364. this.transmuxConfig = void 0;
  15365. this.currentTransmuxState = void 0;
  15366. this.observer = observer;
  15367. this.typeSupported = typeSupported;
  15368. this.config = config;
  15369. this.id = id;
  15370. this.logger = logger;
  15371. }
  15372. configure(transmuxConfig) {
  15373. this.transmuxConfig = transmuxConfig;
  15374. if (this.decrypter) {
  15375. this.decrypter.reset();
  15376. }
  15377. }
  15378. push(data, decryptdata, chunkMeta, state) {
  15379. const stats = chunkMeta.transmuxing;
  15380. stats.executeStart = now();
  15381. let uintData = new Uint8Array(data);
  15382. const {
  15383. currentTransmuxState,
  15384. transmuxConfig
  15385. } = this;
  15386. if (state) {
  15387. this.currentTransmuxState = state;
  15388. }
  15389. const {
  15390. contiguous,
  15391. discontinuity,
  15392. trackSwitch,
  15393. accurateTimeOffset,
  15394. timeOffset,
  15395. initSegmentChange
  15396. } = state || currentTransmuxState;
  15397. const {
  15398. audioCodec,
  15399. videoCodec,
  15400. defaultInitPts,
  15401. duration,
  15402. initSegmentData
  15403. } = transmuxConfig;
  15404. const keyData = getEncryptionType(uintData, decryptdata);
  15405. if (keyData && isFullSegmentEncryption(keyData.method)) {
  15406. const decrypter = this.getDecrypter();
  15407. const aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  15408. // Software decryption is synchronous; webCrypto is not
  15409. if (decrypter.isSync()) {
  15410. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  15411. // data is handled in the flush() call
  15412. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  15413. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  15414. const loadingParts = chunkMeta.part > -1;
  15415. if (loadingParts) {
  15416. const _data = decrypter.flush();
  15417. decryptedData = _data ? _data.buffer : _data;
  15418. }
  15419. if (!decryptedData) {
  15420. stats.executeEnd = now();
  15421. return emptyResult(chunkMeta);
  15422. }
  15423. uintData = new Uint8Array(decryptedData);
  15424. } else {
  15425. this.asyncResult = true;
  15426. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then(decryptedData => {
  15427. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  15428. // the decrypted data has been transmuxed
  15429. const result = this.push(decryptedData, null, chunkMeta);
  15430. this.decryptionPromise = null;
  15431. return result;
  15432. });
  15433. return this.decryptionPromise;
  15434. }
  15435. }
  15436. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  15437. if (resetMuxers) {
  15438. const error = this.configureTransmuxer(uintData);
  15439. if (error) {
  15440. this.logger.warn(`[transmuxer] ${error.message}`);
  15441. this.observer.emit(Events.ERROR, Events.ERROR, {
  15442. type: ErrorTypes.MEDIA_ERROR,
  15443. details: ErrorDetails.FRAG_PARSING_ERROR,
  15444. fatal: false,
  15445. error,
  15446. reason: error.message
  15447. });
  15448. stats.executeEnd = now();
  15449. return emptyResult(chunkMeta);
  15450. }
  15451. }
  15452. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  15453. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  15454. }
  15455. if (discontinuity || initSegmentChange || resetMuxers) {
  15456. this.resetInitialTimestamp(defaultInitPts);
  15457. }
  15458. if (!contiguous) {
  15459. this.resetContiguity();
  15460. }
  15461. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  15462. this.asyncResult = isPromise(result);
  15463. const currentState = this.currentTransmuxState;
  15464. currentState.contiguous = true;
  15465. currentState.discontinuity = false;
  15466. currentState.trackSwitch = false;
  15467. stats.executeEnd = now();
  15468. return result;
  15469. }
  15470. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  15471. flush(chunkMeta) {
  15472. const stats = chunkMeta.transmuxing;
  15473. stats.executeStart = now();
  15474. const {
  15475. decrypter,
  15476. currentTransmuxState,
  15477. decryptionPromise
  15478. } = this;
  15479. if (decryptionPromise) {
  15480. this.asyncResult = true;
  15481. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  15482. // only flushing is required for async decryption
  15483. return decryptionPromise.then(() => {
  15484. return this.flush(chunkMeta);
  15485. });
  15486. }
  15487. const transmuxResults = [];
  15488. const {
  15489. timeOffset
  15490. } = currentTransmuxState;
  15491. if (decrypter) {
  15492. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  15493. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  15494. // or for progressive downloads with small segments)
  15495. const decryptedData = decrypter.flush();
  15496. if (decryptedData) {
  15497. // Push always returns a TransmuxerResult if decryptdata is null
  15498. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  15499. }
  15500. }
  15501. const {
  15502. demuxer,
  15503. remuxer
  15504. } = this;
  15505. if (!demuxer || !remuxer) {
  15506. // If probing failed, then Hls.js has been given content its not able to handle
  15507. stats.executeEnd = now();
  15508. const emptyResults = [emptyResult(chunkMeta)];
  15509. if (this.asyncResult) {
  15510. return Promise.resolve(emptyResults);
  15511. }
  15512. return emptyResults;
  15513. }
  15514. const demuxResultOrPromise = demuxer.flush(timeOffset);
  15515. if (isPromise(demuxResultOrPromise)) {
  15516. this.asyncResult = true;
  15517. // Decrypt final SAMPLE-AES samples
  15518. return demuxResultOrPromise.then(demuxResult => {
  15519. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  15520. return transmuxResults;
  15521. });
  15522. }
  15523. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  15524. if (this.asyncResult) {
  15525. return Promise.resolve(transmuxResults);
  15526. }
  15527. return transmuxResults;
  15528. }
  15529. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  15530. const {
  15531. audioTrack,
  15532. videoTrack,
  15533. id3Track,
  15534. textTrack
  15535. } = demuxResult;
  15536. const {
  15537. accurateTimeOffset,
  15538. timeOffset
  15539. } = this.currentTransmuxState;
  15540. this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : ''} of ${this.id === PlaylistLevelType.MAIN ? 'level' : 'track'} ${chunkMeta.level}`);
  15541. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  15542. transmuxResults.push({
  15543. remuxResult,
  15544. chunkMeta
  15545. });
  15546. chunkMeta.transmuxing.executeEnd = now();
  15547. }
  15548. resetInitialTimestamp(defaultInitPts) {
  15549. const {
  15550. demuxer,
  15551. remuxer
  15552. } = this;
  15553. if (!demuxer || !remuxer) {
  15554. return;
  15555. }
  15556. demuxer.resetTimeStamp(defaultInitPts);
  15557. remuxer.resetTimeStamp(defaultInitPts);
  15558. }
  15559. resetContiguity() {
  15560. const {
  15561. demuxer,
  15562. remuxer
  15563. } = this;
  15564. if (!demuxer || !remuxer) {
  15565. return;
  15566. }
  15567. demuxer.resetContiguity();
  15568. remuxer.resetNextTimestamp();
  15569. }
  15570. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  15571. const {
  15572. demuxer,
  15573. remuxer
  15574. } = this;
  15575. if (!demuxer || !remuxer) {
  15576. return;
  15577. }
  15578. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  15579. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  15580. }
  15581. destroy() {
  15582. if (this.demuxer) {
  15583. this.demuxer.destroy();
  15584. this.demuxer = undefined;
  15585. }
  15586. if (this.remuxer) {
  15587. this.remuxer.destroy();
  15588. this.remuxer = undefined;
  15589. }
  15590. }
  15591. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  15592. let result;
  15593. if (keyData && keyData.method === 'SAMPLE-AES') {
  15594. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  15595. } else {
  15596. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  15597. }
  15598. return result;
  15599. }
  15600. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  15601. const {
  15602. audioTrack,
  15603. videoTrack,
  15604. id3Track,
  15605. textTrack
  15606. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  15607. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  15608. return {
  15609. remuxResult,
  15610. chunkMeta
  15611. };
  15612. }
  15613. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  15614. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {
  15615. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  15616. return {
  15617. remuxResult,
  15618. chunkMeta
  15619. };
  15620. });
  15621. }
  15622. configureTransmuxer(data) {
  15623. const {
  15624. config,
  15625. observer,
  15626. typeSupported
  15627. } = this;
  15628. // probe for content type
  15629. let mux;
  15630. for (let i = 0, len = muxConfig.length; i < len; i++) {
  15631. var _muxConfig$i$demux;
  15632. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  15633. mux = muxConfig[i];
  15634. break;
  15635. }
  15636. }
  15637. if (!mux) {
  15638. return new Error('Failed to find demuxer by probing fragment data');
  15639. }
  15640. // so let's check that current remuxer and demuxer are still valid
  15641. const demuxer = this.demuxer;
  15642. const remuxer = this.remuxer;
  15643. const Remuxer = mux.remux;
  15644. const Demuxer = mux.demux;
  15645. if (!remuxer || !(remuxer instanceof Remuxer)) {
  15646. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  15647. }
  15648. if (!demuxer || !(demuxer instanceof Demuxer)) {
  15649. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  15650. this.probe = Demuxer.probe;
  15651. }
  15652. }
  15653. needsProbing(discontinuity, trackSwitch) {
  15654. // in case of continuity change, or track switch
  15655. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  15656. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  15657. }
  15658. getDecrypter() {
  15659. let decrypter = this.decrypter;
  15660. if (!decrypter) {
  15661. decrypter = this.decrypter = new Decrypter(this.config);
  15662. }
  15663. return decrypter;
  15664. }
  15665. }
  15666. function getEncryptionType(data, decryptData) {
  15667. let encryptionType = null;
  15668. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  15669. encryptionType = decryptData;
  15670. }
  15671. return encryptionType;
  15672. }
  15673. const emptyResult = chunkMeta => ({
  15674. remuxResult: {},
  15675. chunkMeta
  15676. });
  15677. function isPromise(p) {
  15678. return 'then' in p && p.then instanceof Function;
  15679. }
  15680. class TransmuxConfig {
  15681. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  15682. this.audioCodec = void 0;
  15683. this.videoCodec = void 0;
  15684. this.initSegmentData = void 0;
  15685. this.duration = void 0;
  15686. this.defaultInitPts = void 0;
  15687. this.audioCodec = audioCodec;
  15688. this.videoCodec = videoCodec;
  15689. this.initSegmentData = initSegmentData;
  15690. this.duration = duration;
  15691. this.defaultInitPts = defaultInitPts || null;
  15692. }
  15693. }
  15694. class TransmuxState {
  15695. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  15696. this.discontinuity = void 0;
  15697. this.contiguous = void 0;
  15698. this.accurateTimeOffset = void 0;
  15699. this.trackSwitch = void 0;
  15700. this.timeOffset = void 0;
  15701. this.initSegmentChange = void 0;
  15702. this.discontinuity = discontinuity;
  15703. this.contiguous = contiguous;
  15704. this.accurateTimeOffset = accurateTimeOffset;
  15705. this.trackSwitch = trackSwitch;
  15706. this.timeOffset = timeOffset;
  15707. this.initSegmentChange = initSegmentChange;
  15708. }
  15709. }
  15710. let transmuxerInstanceCount = 0;
  15711. class TransmuxerInterface {
  15712. constructor(_hls, id, onTransmuxComplete, onFlush) {
  15713. this.error = null;
  15714. this.hls = void 0;
  15715. this.id = void 0;
  15716. this.instanceNo = transmuxerInstanceCount++;
  15717. this.observer = void 0;
  15718. this.frag = null;
  15719. this.part = null;
  15720. this.useWorker = void 0;
  15721. this.workerContext = null;
  15722. this.transmuxer = null;
  15723. this.onTransmuxComplete = void 0;
  15724. this.onFlush = void 0;
  15725. this.onWorkerMessage = event => {
  15726. const data = event.data;
  15727. const hls = this.hls;
  15728. if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {
  15729. return;
  15730. }
  15731. switch (data.event) {
  15732. case 'init':
  15733. {
  15734. var _this$workerContext;
  15735. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  15736. if (objectURL) {
  15737. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  15738. self.URL.revokeObjectURL(objectURL);
  15739. }
  15740. break;
  15741. }
  15742. case 'transmuxComplete':
  15743. {
  15744. this.handleTransmuxComplete(data.data);
  15745. break;
  15746. }
  15747. case 'flush':
  15748. {
  15749. this.onFlush(data.data);
  15750. break;
  15751. }
  15752. // pass logs from the worker thread to the main logger
  15753. case 'workerLog':
  15754. {
  15755. if (hls.logger[data.data.logType]) {
  15756. hls.logger[data.data.logType](data.data.message);
  15757. }
  15758. break;
  15759. }
  15760. default:
  15761. {
  15762. data.data = data.data || {};
  15763. data.data.frag = this.frag;
  15764. data.data.part = this.part;
  15765. data.data.id = this.id;
  15766. hls.trigger(data.event, data.data);
  15767. break;
  15768. }
  15769. }
  15770. };
  15771. this.onWorkerError = event => {
  15772. if (!this.hls) {
  15773. return;
  15774. }
  15775. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  15776. this.hls.config.enableWorker = false;
  15777. this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`);
  15778. this.hls.trigger(Events.ERROR, {
  15779. type: ErrorTypes.OTHER_ERROR,
  15780. details: ErrorDetails.INTERNAL_EXCEPTION,
  15781. fatal: false,
  15782. event: 'demuxerWorker',
  15783. error
  15784. });
  15785. };
  15786. const config = _hls.config;
  15787. this.hls = _hls;
  15788. this.id = id;
  15789. this.useWorker = !!config.enableWorker;
  15790. this.onTransmuxComplete = onTransmuxComplete;
  15791. this.onFlush = onFlush;
  15792. const forwardMessage = (ev, data) => {
  15793. data = data || {};
  15794. data.frag = this.frag || undefined;
  15795. if (ev === Events.ERROR) {
  15796. data = data;
  15797. data.parent = this.id;
  15798. data.part = this.part;
  15799. this.error = data.error;
  15800. }
  15801. this.hls.trigger(ev, data);
  15802. };
  15803. // forward events to main thread
  15804. this.observer = new EventEmitter();
  15805. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  15806. this.observer.on(Events.ERROR, forwardMessage);
  15807. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  15808. if (this.useWorker && typeof Worker !== 'undefined') {
  15809. const logger = this.hls.logger;
  15810. const canCreateWorker = config.workerPath || hasUMDWorker();
  15811. if (canCreateWorker) {
  15812. try {
  15813. if (config.workerPath) {
  15814. logger.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  15815. this.workerContext = loadWorker(config.workerPath);
  15816. } else {
  15817. logger.log(`injecting Web Worker for "${id}"`);
  15818. this.workerContext = injectWorker();
  15819. }
  15820. const {
  15821. worker
  15822. } = this.workerContext;
  15823. worker.addEventListener('message', this.onWorkerMessage);
  15824. worker.addEventListener('error', this.onWorkerError);
  15825. worker.postMessage({
  15826. instanceNo: this.instanceNo,
  15827. cmd: 'init',
  15828. typeSupported: m2tsTypeSupported,
  15829. id,
  15830. config: stringify(config)
  15831. });
  15832. } catch (err) {
  15833. logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  15834. this.terminateWorker();
  15835. this.error = null;
  15836. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  15837. }
  15838. return;
  15839. }
  15840. }
  15841. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  15842. }
  15843. reset() {
  15844. this.frag = null;
  15845. this.part = null;
  15846. if (this.workerContext) {
  15847. const instanceNo = this.instanceNo;
  15848. this.instanceNo = transmuxerInstanceCount++;
  15849. const config = this.hls.config;
  15850. const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  15851. this.workerContext.worker.postMessage({
  15852. instanceNo: this.instanceNo,
  15853. cmd: 'reset',
  15854. resetNo: instanceNo,
  15855. typeSupported: m2tsTypeSupported,
  15856. id: this.id,
  15857. config: stringify(config)
  15858. });
  15859. }
  15860. }
  15861. terminateWorker() {
  15862. if (this.workerContext) {
  15863. const {
  15864. worker
  15865. } = this.workerContext;
  15866. this.workerContext = null;
  15867. worker.removeEventListener('message', this.onWorkerMessage);
  15868. worker.removeEventListener('error', this.onWorkerError);
  15869. removeWorkerFromStore(this.hls.config.workerPath);
  15870. }
  15871. }
  15872. destroy() {
  15873. if (this.workerContext) {
  15874. this.terminateWorker();
  15875. // @ts-ignore
  15876. this.onWorkerMessage = this.onWorkerError = null;
  15877. } else {
  15878. const transmuxer = this.transmuxer;
  15879. if (transmuxer) {
  15880. transmuxer.destroy();
  15881. this.transmuxer = null;
  15882. }
  15883. }
  15884. const observer = this.observer;
  15885. if (observer) {
  15886. observer.removeAllListeners();
  15887. }
  15888. this.frag = null;
  15889. this.part = null;
  15890. // @ts-ignore
  15891. this.observer = null;
  15892. // @ts-ignore
  15893. this.hls = null;
  15894. }
  15895. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  15896. var _frag$initSegment, _lastFrag$initSegment;
  15897. chunkMeta.transmuxing.start = self.performance.now();
  15898. const {
  15899. instanceNo,
  15900. transmuxer
  15901. } = this;
  15902. const timeOffset = part ? part.start : frag.start;
  15903. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  15904. const decryptdata = frag.decryptdata;
  15905. const lastFrag = this.frag;
  15906. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  15907. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  15908. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  15909. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  15910. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  15911. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  15912. const now = self.performance.now();
  15913. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  15914. frag.stats.parsing.start = now;
  15915. }
  15916. if (part && (partDiff || !contiguous)) {
  15917. part.stats.parsing.start = now;
  15918. }
  15919. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  15920. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  15921. if (!contiguous || discontinuity || initSegmentChange) {
  15922. this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${frag.type} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : ''} ${this.id === PlaylistLevelType.MAIN ? 'level' : 'track'}: ${chunkMeta.level} id: ${chunkMeta.id}
  15923. discontinuity: ${discontinuity}
  15924. trackSwitch: ${trackSwitch}
  15925. contiguous: ${contiguous}
  15926. accurateTimeOffset: ${accurateTimeOffset}
  15927. timeOffset: ${timeOffset}
  15928. initSegmentChange: ${initSegmentChange}`);
  15929. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  15930. this.configureTransmuxer(config);
  15931. }
  15932. this.frag = frag;
  15933. this.part = part;
  15934. // Frags with sn of 'initSegment' are not transmuxed
  15935. if (this.workerContext) {
  15936. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  15937. this.workerContext.worker.postMessage({
  15938. instanceNo,
  15939. cmd: 'demux',
  15940. data,
  15941. decryptdata,
  15942. chunkMeta,
  15943. state
  15944. }, data instanceof ArrayBuffer ? [data] : []);
  15945. } else if (transmuxer) {
  15946. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  15947. if (isPromise(transmuxResult)) {
  15948. transmuxResult.then(data => {
  15949. this.handleTransmuxComplete(data);
  15950. }).catch(error => {
  15951. this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  15952. });
  15953. } else {
  15954. this.handleTransmuxComplete(transmuxResult);
  15955. }
  15956. }
  15957. }
  15958. flush(chunkMeta) {
  15959. chunkMeta.transmuxing.start = self.performance.now();
  15960. const {
  15961. instanceNo,
  15962. transmuxer
  15963. } = this;
  15964. if (this.workerContext) {
  15965. this.workerContext.worker.postMessage({
  15966. instanceNo,
  15967. cmd: 'flush',
  15968. chunkMeta
  15969. });
  15970. } else if (transmuxer) {
  15971. const transmuxResult = transmuxer.flush(chunkMeta);
  15972. if (isPromise(transmuxResult)) {
  15973. transmuxResult.then(data => {
  15974. this.handleFlushResult(data, chunkMeta);
  15975. }).catch(error => {
  15976. this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  15977. });
  15978. } else {
  15979. this.handleFlushResult(transmuxResult, chunkMeta);
  15980. }
  15981. }
  15982. }
  15983. transmuxerError(error, chunkMeta, reason) {
  15984. if (!this.hls) {
  15985. return;
  15986. }
  15987. this.error = error;
  15988. this.hls.trigger(Events.ERROR, {
  15989. type: ErrorTypes.MEDIA_ERROR,
  15990. details: ErrorDetails.FRAG_PARSING_ERROR,
  15991. chunkMeta,
  15992. frag: this.frag || undefined,
  15993. part: this.part || undefined,
  15994. fatal: false,
  15995. error,
  15996. err: error,
  15997. reason
  15998. });
  15999. }
  16000. handleFlushResult(results, chunkMeta) {
  16001. results.forEach(result => {
  16002. this.handleTransmuxComplete(result);
  16003. });
  16004. this.onFlush(chunkMeta);
  16005. }
  16006. configureTransmuxer(config) {
  16007. const {
  16008. instanceNo,
  16009. transmuxer
  16010. } = this;
  16011. if (this.workerContext) {
  16012. this.workerContext.worker.postMessage({
  16013. instanceNo,
  16014. cmd: 'configure',
  16015. config
  16016. });
  16017. } else if (transmuxer) {
  16018. transmuxer.configure(config);
  16019. }
  16020. }
  16021. handleTransmuxComplete(result) {
  16022. result.chunkMeta.transmuxing.end = self.performance.now();
  16023. this.onTransmuxComplete(result);
  16024. }
  16025. }
  16026. const TICK_INTERVAL$3 = 100; // how often to tick in ms
  16027. class AudioStreamController extends BaseStreamController {
  16028. constructor(hls, fragmentTracker, keyLoader) {
  16029. super(hls, fragmentTracker, keyLoader, 'audio-stream-controller', PlaylistLevelType.AUDIO);
  16030. this.mainAnchor = null;
  16031. this.mainFragLoading = null;
  16032. this.audioOnly = false;
  16033. this.bufferedTrack = null;
  16034. this.switchingTrack = null;
  16035. this.trackId = -1;
  16036. this.waitingData = null;
  16037. this.mainDetails = null;
  16038. this.flushing = false;
  16039. this.bufferFlushed = false;
  16040. this.cachedTrackLoadedData = null;
  16041. this.registerListeners();
  16042. }
  16043. onHandlerDestroying() {
  16044. this.unregisterListeners();
  16045. super.onHandlerDestroying();
  16046. this.resetItem();
  16047. }
  16048. resetItem() {
  16049. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  16050. }
  16051. registerListeners() {
  16052. super.registerListeners();
  16053. const {
  16054. hls
  16055. } = this;
  16056. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16057. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  16058. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  16059. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16060. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  16061. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  16062. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16063. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  16064. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  16065. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  16066. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16067. }
  16068. unregisterListeners() {
  16069. const {
  16070. hls
  16071. } = this;
  16072. if (!hls) {
  16073. return;
  16074. }
  16075. super.unregisterListeners();
  16076. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16077. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  16078. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  16079. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16080. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  16081. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  16082. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16083. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  16084. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  16085. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  16086. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16087. }
  16088. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  16089. onInitPtsFound(event, {
  16090. frag,
  16091. id,
  16092. initPTS,
  16093. timescale
  16094. }) {
  16095. // Always update the new INIT PTS
  16096. // Can change due level switch
  16097. if (id === PlaylistLevelType.MAIN) {
  16098. const cc = frag.cc;
  16099. const inFlightFrag = this.fragCurrent;
  16100. this.initPTS[cc] = {
  16101. baseTime: initPTS,
  16102. timescale
  16103. };
  16104. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);
  16105. this.mainAnchor = frag;
  16106. // If we are waiting, tick immediately to unblock audio fragment transmuxing
  16107. if (this.state === State.WAITING_INIT_PTS) {
  16108. const waitingData = this.waitingData;
  16109. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  16110. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  16111. }
  16112. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  16113. inFlightFrag.abortRequests();
  16114. this.syncWithAnchor(frag, inFlightFrag);
  16115. } else if (this.state === State.IDLE) {
  16116. this.tick();
  16117. }
  16118. }
  16119. }
  16120. getLoadPosition() {
  16121. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  16122. return this.nextLoadPosition;
  16123. }
  16124. return super.getLoadPosition();
  16125. }
  16126. syncWithAnchor(mainAnchor, waitingToAppend) {
  16127. var _this$mainFragLoading;
  16128. // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
  16129. const mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  16130. if (waitingToAppend) {
  16131. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  16132. // Wait for loading frag to complete and INIT_PTS_FOUND
  16133. return;
  16134. }
  16135. }
  16136. const targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  16137. const trackDetails = this.getLevelDetails();
  16138. const pos = this.getLoadPosition();
  16139. const syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  16140. // Only stop waiting for audioFrag.cc if an audio segment of the same discontinuity domain (cc) is found
  16141. if (syncFrag) {
  16142. this.log(`Syncing with main frag at ${syncFrag.start} cc ${syncFrag.cc}`);
  16143. this.startFragRequested = false;
  16144. this.nextLoadPosition = syncFrag.start;
  16145. this.resetLoadingState();
  16146. if (this.state === State.IDLE) {
  16147. this.doTickIdle();
  16148. }
  16149. }
  16150. }
  16151. startLoad(startPosition, skipSeekToStartPosition) {
  16152. if (!this.levels) {
  16153. this.startPosition = startPosition;
  16154. this.state = State.STOPPED;
  16155. return;
  16156. }
  16157. const lastCurrentTime = this.lastCurrentTime;
  16158. this.stopLoad();
  16159. this.setInterval(TICK_INTERVAL$3);
  16160. if (lastCurrentTime > 0 && startPosition === -1) {
  16161. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  16162. startPosition = lastCurrentTime;
  16163. this.state = State.IDLE;
  16164. } else {
  16165. this.state = State.WAITING_TRACK;
  16166. }
  16167. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  16168. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  16169. this.tick();
  16170. }
  16171. doTick() {
  16172. switch (this.state) {
  16173. case State.IDLE:
  16174. this.doTickIdle();
  16175. break;
  16176. case State.WAITING_TRACK:
  16177. {
  16178. const {
  16179. levels,
  16180. trackId
  16181. } = this;
  16182. const currenTrack = levels == null ? void 0 : levels[trackId];
  16183. const details = currenTrack == null ? void 0 : currenTrack.details;
  16184. if (details && !this.waitForLive(currenTrack)) {
  16185. if (this.waitForCdnTuneIn(details)) {
  16186. break;
  16187. }
  16188. this.state = State.WAITING_INIT_PTS;
  16189. }
  16190. break;
  16191. }
  16192. case State.FRAG_LOADING_WAITING_RETRY:
  16193. {
  16194. var _this$media;
  16195. const now = performance.now();
  16196. const retryDate = this.retryDate;
  16197. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  16198. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  16199. const {
  16200. levels,
  16201. trackId
  16202. } = this;
  16203. this.log('RetryDate reached, switch back to IDLE state');
  16204. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  16205. this.state = State.IDLE;
  16206. }
  16207. break;
  16208. }
  16209. case State.WAITING_INIT_PTS:
  16210. {
  16211. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  16212. const waitingData = this.waitingData;
  16213. if (waitingData) {
  16214. const {
  16215. frag,
  16216. part,
  16217. cache,
  16218. complete
  16219. } = waitingData;
  16220. const mainAnchor = this.mainAnchor;
  16221. if (this.initPTS[frag.cc] !== undefined) {
  16222. this.waitingData = null;
  16223. this.state = State.FRAG_LOADING;
  16224. const payload = cache.flush().buffer;
  16225. const data = {
  16226. frag,
  16227. part,
  16228. payload,
  16229. networkDetails: null
  16230. };
  16231. this._handleFragmentLoadProgress(data);
  16232. if (complete) {
  16233. super._handleFragmentLoadComplete(data);
  16234. }
  16235. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  16236. this.syncWithAnchor(mainAnchor, waitingData.frag);
  16237. }
  16238. } else {
  16239. this.state = State.IDLE;
  16240. }
  16241. }
  16242. }
  16243. this.onTickEnd();
  16244. }
  16245. resetLoadingState() {
  16246. const waitingData = this.waitingData;
  16247. if (waitingData) {
  16248. this.fragmentTracker.removeFragment(waitingData.frag);
  16249. this.waitingData = null;
  16250. }
  16251. super.resetLoadingState();
  16252. }
  16253. onTickEnd() {
  16254. const {
  16255. media
  16256. } = this;
  16257. if (!(media != null && media.readyState)) {
  16258. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  16259. return;
  16260. }
  16261. this.lastCurrentTime = media.currentTime;
  16262. }
  16263. doTickIdle() {
  16264. var _this$mainFragLoading2;
  16265. const {
  16266. hls,
  16267. levels,
  16268. media,
  16269. trackId
  16270. } = this;
  16271. const config = hls.config;
  16272. // 1. if buffering is suspended
  16273. // 2. if video not attached AND
  16274. // start fragment already requested OR start frag prefetch not enabled
  16275. // 3. if tracks or track not loaded and selected
  16276. // then exit loop
  16277. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  16278. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  16279. return;
  16280. }
  16281. const levelInfo = levels[trackId];
  16282. const trackDetails = levelInfo.details;
  16283. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  16284. this.state = State.WAITING_TRACK;
  16285. this.startFragRequested = false;
  16286. return;
  16287. }
  16288. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  16289. if (this.bufferFlushed && bufferable) {
  16290. this.bufferFlushed = false;
  16291. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  16292. }
  16293. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  16294. if (bufferInfo === null) {
  16295. return;
  16296. }
  16297. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  16298. hls.trigger(Events.BUFFER_EOS, {
  16299. type: 'audio'
  16300. });
  16301. this.state = State.ENDED;
  16302. return;
  16303. }
  16304. const bufferLen = bufferInfo.len;
  16305. const maxBufLen = hls.maxBufferLength;
  16306. const fragments = trackDetails.fragments;
  16307. const start = fragments[0].start;
  16308. const loadPosition = this.getLoadPosition();
  16309. const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  16310. if (this.switchingTrack && media) {
  16311. const pos = loadPosition;
  16312. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  16313. if (trackDetails.PTSKnown && pos < start) {
  16314. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  16315. if (bufferInfo.end > start || bufferInfo.nextStart) {
  16316. this.log('Alt audio track ahead of main track, seek to start of alt audio track');
  16317. media.currentTime = start + 0.05;
  16318. }
  16319. }
  16320. }
  16321. // if buffer length is less than maxBufLen, or near the end, find a fragment to load
  16322. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  16323. return;
  16324. }
  16325. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  16326. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  16327. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  16328. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  16329. }
  16330. if (!frag) {
  16331. this.bufferFlushed = true;
  16332. return;
  16333. }
  16334. // Request audio segments up to one fragment ahead of main stream-controller
  16335. let mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  16336. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  16337. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  16338. this.mainFragLoading = mainFragLoading = null;
  16339. }
  16340. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  16341. if (frag.start > mainFragLoading.end) {
  16342. // Get buffered frag at target position from tracker (loaded out of sequence)
  16343. const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  16344. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  16345. mainFragLoading = mainFragAtPos;
  16346. this.mainFragLoading = {
  16347. frag: mainFragAtPos,
  16348. targetBufferTime: null
  16349. };
  16350. }
  16351. }
  16352. const atBufferSyncLimit = frag.start > mainFragLoading.end;
  16353. if (atBufferSyncLimit) {
  16354. return;
  16355. }
  16356. }
  16357. }
  16358. this.loadFragment(frag, levelInfo, targetBufferTime);
  16359. }
  16360. onMediaDetaching(event, data) {
  16361. this.bufferFlushed = this.flushing = false;
  16362. super.onMediaDetaching(event, data);
  16363. }
  16364. onAudioTracksUpdated(event, {
  16365. audioTracks
  16366. }) {
  16367. // Reset tranxmuxer is essential for large context switches (Content Steering)
  16368. this.resetTransmuxer();
  16369. this.levels = audioTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  16370. }
  16371. onAudioTrackSwitching(event, data) {
  16372. // if any URL found on new audio track, it is an alternate audio track
  16373. const altAudio = !!data.url;
  16374. this.trackId = data.id;
  16375. const {
  16376. fragCurrent
  16377. } = this;
  16378. if (fragCurrent) {
  16379. fragCurrent.abortRequests();
  16380. this.removeUnbufferedFrags(fragCurrent.start);
  16381. }
  16382. this.resetLoadingState();
  16383. // should we switch tracks ?
  16384. if (altAudio) {
  16385. this.switchingTrack = data;
  16386. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  16387. this.flushAudioIfNeeded(data);
  16388. if (this.state !== State.STOPPED) {
  16389. // switching to audio track, start timer if not already started
  16390. this.setInterval(TICK_INTERVAL$3);
  16391. this.state = State.IDLE;
  16392. this.tick();
  16393. }
  16394. } else {
  16395. // destroy useless transmuxer when switching audio to main
  16396. this.resetTransmuxer();
  16397. this.switchingTrack = null;
  16398. this.bufferedTrack = data;
  16399. this.clearInterval();
  16400. }
  16401. }
  16402. onManifestLoading() {
  16403. super.onManifestLoading();
  16404. this.bufferFlushed = this.flushing = this.audioOnly = false;
  16405. this.resetItem();
  16406. this.trackId = -1;
  16407. }
  16408. onLevelLoaded(event, data) {
  16409. this.mainDetails = data.details;
  16410. const cachedTrackLoadedData = this.cachedTrackLoadedData;
  16411. if (cachedTrackLoadedData) {
  16412. this.cachedTrackLoadedData = null;
  16413. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  16414. }
  16415. }
  16416. onAudioTrackLoaded(event, data) {
  16417. var _trackLevel$details;
  16418. const {
  16419. levels
  16420. } = this;
  16421. const {
  16422. details: newDetails,
  16423. id: trackId,
  16424. groupId,
  16425. track
  16426. } = data;
  16427. if (!levels) {
  16428. this.warn(`Audio tracks reset while loading track ${trackId} "${track.name}" of "${groupId}"`);
  16429. return;
  16430. }
  16431. const mainDetails = this.mainDetails;
  16432. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  16433. this.cachedTrackLoadedData = data;
  16434. if (this.state !== State.STOPPED) {
  16435. this.state = State.WAITING_TRACK;
  16436. }
  16437. return;
  16438. }
  16439. this.cachedTrackLoadedData = null;
  16440. this.log(`Audio track ${trackId} "${track.name}" of "${groupId}" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  16441. const trackLevel = levels[trackId];
  16442. let sliding = 0;
  16443. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  16444. this.checkLiveUpdate(newDetails);
  16445. if (newDetails.deltaUpdateFailed) {
  16446. return;
  16447. }
  16448. if (trackLevel.details) {
  16449. var _this$levelLastLoaded;
  16450. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  16451. }
  16452. if (!newDetails.alignedSliding) {
  16453. // Align audio rendition with the "main" playlist on discontinuity change
  16454. // or program-date-time (PDT)
  16455. alignDiscontinuities(newDetails, mainDetails);
  16456. if (!newDetails.alignedSliding) {
  16457. alignMediaPlaylistByPDT(newDetails, mainDetails);
  16458. }
  16459. sliding = newDetails.fragmentStart;
  16460. }
  16461. }
  16462. trackLevel.details = newDetails;
  16463. this.levelLastLoaded = trackLevel;
  16464. // compute start position if we are aligned with the main playlist
  16465. if (!this.startFragRequested) {
  16466. this.setStartPosition(mainDetails, sliding);
  16467. }
  16468. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  16469. details: newDetails,
  16470. id: trackId,
  16471. groupId: data.groupId
  16472. });
  16473. // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
  16474. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  16475. this.state = State.IDLE;
  16476. }
  16477. // trigger handler right now
  16478. this.tick();
  16479. }
  16480. _handleFragmentLoadProgress(data) {
  16481. var _frag$initSegment;
  16482. const frag = data.frag;
  16483. const {
  16484. part,
  16485. payload
  16486. } = data;
  16487. const {
  16488. config,
  16489. trackId,
  16490. levels
  16491. } = this;
  16492. if (!levels) {
  16493. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  16494. return;
  16495. }
  16496. const track = levels[trackId];
  16497. if (!track) {
  16498. this.warn('Audio track is undefined on fragment load progress');
  16499. return;
  16500. }
  16501. const details = track.details;
  16502. if (!details) {
  16503. this.warn('Audio track details undefined on fragment load progress');
  16504. this.removeUnbufferedFrags(frag.start);
  16505. return;
  16506. }
  16507. const audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
  16508. let transmuxer = this.transmuxer;
  16509. if (!transmuxer) {
  16510. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  16511. }
  16512. // Check if we have video initPTS
  16513. // If not we need to wait for it
  16514. const initPTS = this.initPTS[frag.cc];
  16515. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  16516. if (initPTS !== undefined) {
  16517. // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  16518. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  16519. const accurateTimeOffset = false; // details.PTSKnown || !details.live;
  16520. const partIndex = part ? part.index : -1;
  16521. const partial = partIndex !== -1;
  16522. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  16523. transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  16524. } else {
  16525. this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  16526. const {
  16527. cache
  16528. } = this.waitingData = this.waitingData || {
  16529. frag,
  16530. part,
  16531. cache: new ChunkCache(),
  16532. complete: false
  16533. };
  16534. cache.push(new Uint8Array(payload));
  16535. if (this.state !== State.STOPPED) {
  16536. this.state = State.WAITING_INIT_PTS;
  16537. }
  16538. }
  16539. }
  16540. _handleFragmentLoadComplete(fragLoadedData) {
  16541. if (this.waitingData) {
  16542. this.waitingData.complete = true;
  16543. return;
  16544. }
  16545. super._handleFragmentLoadComplete(fragLoadedData);
  16546. }
  16547. onBufferReset(/* event: Events.BUFFER_RESET */
  16548. ) {
  16549. // reset reference to sourcebuffers
  16550. this.mediaBuffer = null;
  16551. }
  16552. onBufferCreated(event, data) {
  16553. this.bufferFlushed = this.flushing = false;
  16554. const audioTrack = data.tracks.audio;
  16555. if (audioTrack) {
  16556. this.mediaBuffer = audioTrack.buffer || null;
  16557. }
  16558. }
  16559. onFragLoading(event, data) {
  16560. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  16561. this.mainFragLoading = data;
  16562. if (this.state === State.IDLE) {
  16563. this.tick();
  16564. }
  16565. }
  16566. }
  16567. onFragBuffered(event, data) {
  16568. const {
  16569. frag,
  16570. part
  16571. } = data;
  16572. if (frag.type !== PlaylistLevelType.AUDIO) {
  16573. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  16574. this.audioOnly = true;
  16575. this.mainFragLoading = null;
  16576. }
  16577. return;
  16578. }
  16579. if (this.fragContextChanged(frag)) {
  16580. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  16581. // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
  16582. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : 'false'}`);
  16583. return;
  16584. }
  16585. if (isMediaFragment(frag)) {
  16586. this.fragPrevious = frag;
  16587. const track = this.switchingTrack;
  16588. if (track) {
  16589. this.bufferedTrack = track;
  16590. this.switchingTrack = null;
  16591. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  16592. }
  16593. }
  16594. this.fragBufferedComplete(frag, part);
  16595. if (this.media) {
  16596. this.tick();
  16597. }
  16598. }
  16599. onError(event, data) {
  16600. var _data$context;
  16601. if (data.fatal) {
  16602. this.state = State.ERROR;
  16603. return;
  16604. }
  16605. switch (data.details) {
  16606. case ErrorDetails.FRAG_GAP:
  16607. case ErrorDetails.FRAG_PARSING_ERROR:
  16608. case ErrorDetails.FRAG_DECRYPT_ERROR:
  16609. case ErrorDetails.FRAG_LOAD_ERROR:
  16610. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  16611. case ErrorDetails.KEY_LOAD_ERROR:
  16612. case ErrorDetails.KEY_LOAD_TIMEOUT:
  16613. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  16614. break;
  16615. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  16616. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  16617. case ErrorDetails.LEVEL_PARSING_ERROR:
  16618. // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE
  16619. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  16620. this.state = State.IDLE;
  16621. }
  16622. break;
  16623. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  16624. case ErrorDetails.BUFFER_APPEND_ERROR:
  16625. if (data.parent !== 'audio') {
  16626. return;
  16627. }
  16628. if (!this.reduceLengthAndFlushBuffer(data)) {
  16629. this.resetLoadingState();
  16630. }
  16631. break;
  16632. case ErrorDetails.BUFFER_FULL_ERROR:
  16633. if (data.parent !== 'audio') {
  16634. return;
  16635. }
  16636. if (this.reduceLengthAndFlushBuffer(data)) {
  16637. this.bufferedTrack = null;
  16638. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  16639. }
  16640. break;
  16641. case ErrorDetails.INTERNAL_EXCEPTION:
  16642. this.recoverWorkerError(data);
  16643. break;
  16644. }
  16645. }
  16646. onBufferFlushing(event, {
  16647. type
  16648. }) {
  16649. if (type !== ElementaryStreamTypes.VIDEO) {
  16650. this.flushing = true;
  16651. }
  16652. }
  16653. onBufferFlushed(event, {
  16654. type
  16655. }) {
  16656. if (type !== ElementaryStreamTypes.VIDEO) {
  16657. this.flushing = false;
  16658. this.bufferFlushed = true;
  16659. if (this.state === State.ENDED) {
  16660. this.state = State.IDLE;
  16661. }
  16662. const mediaBuffer = this.mediaBuffer || this.media;
  16663. if (mediaBuffer) {
  16664. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  16665. this.tick();
  16666. }
  16667. }
  16668. }
  16669. _handleTransmuxComplete(transmuxResult) {
  16670. var _id3$samples;
  16671. const id = 'audio';
  16672. const {
  16673. hls
  16674. } = this;
  16675. const {
  16676. remuxResult,
  16677. chunkMeta
  16678. } = transmuxResult;
  16679. const context = this.getCurrentContext(chunkMeta);
  16680. if (!context) {
  16681. this.resetWhenMissingContext(chunkMeta);
  16682. return;
  16683. }
  16684. const {
  16685. frag,
  16686. part,
  16687. level
  16688. } = context;
  16689. const {
  16690. details
  16691. } = level;
  16692. const {
  16693. audio,
  16694. text,
  16695. id3,
  16696. initSegment
  16697. } = remuxResult;
  16698. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  16699. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  16700. if (this.fragContextChanged(frag) || !details) {
  16701. this.fragmentTracker.removeFragment(frag);
  16702. return;
  16703. }
  16704. this.state = State.PARSING;
  16705. if (this.switchingTrack && audio) {
  16706. this.completeAudioSwitch(this.switchingTrack);
  16707. }
  16708. if (initSegment != null && initSegment.tracks) {
  16709. const mapFragment = frag.initSegment || frag;
  16710. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  16711. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  16712. frag: mapFragment,
  16713. id,
  16714. tracks: initSegment.tracks
  16715. });
  16716. // Only flush audio from old audio tracks when PTS is known on new audio track
  16717. }
  16718. if (audio) {
  16719. const {
  16720. startPTS,
  16721. endPTS,
  16722. startDTS,
  16723. endDTS
  16724. } = audio;
  16725. if (part) {
  16726. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  16727. startPTS,
  16728. endPTS,
  16729. startDTS,
  16730. endDTS
  16731. };
  16732. }
  16733. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  16734. this.bufferFragmentData(audio, frag, part, chunkMeta);
  16735. }
  16736. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  16737. const emittedID3 = _extends({
  16738. id,
  16739. frag,
  16740. details
  16741. }, id3);
  16742. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  16743. }
  16744. if (text) {
  16745. const emittedText = _extends({
  16746. id,
  16747. frag,
  16748. details
  16749. }, text);
  16750. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  16751. }
  16752. }
  16753. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  16754. if (this.state !== State.PARSING) {
  16755. return;
  16756. }
  16757. // delete any video track found on audio transmuxer
  16758. if (tracks.video) {
  16759. delete tracks.video;
  16760. }
  16761. if (tracks.audiovideo) {
  16762. delete tracks.audiovideo;
  16763. }
  16764. // include levelCodec in audio and video tracks
  16765. if (!tracks.audio) {
  16766. return;
  16767. }
  16768. const track = tracks.audio;
  16769. track.id = PlaylistLevelType.AUDIO;
  16770. const variantAudioCodecs = currentLevel.audioCodec;
  16771. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  16772. // SourceBuffer will use track.levelCodec if defined
  16773. if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {
  16774. track.levelCodec = variantAudioCodecs;
  16775. }
  16776. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  16777. const initSegment = track.initSegment;
  16778. if (initSegment != null && initSegment.byteLength) {
  16779. const segment = {
  16780. type: 'audio',
  16781. frag,
  16782. part: null,
  16783. chunkMeta,
  16784. parent: frag.type,
  16785. data: initSegment
  16786. };
  16787. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  16788. }
  16789. // trigger handler right now
  16790. this.tickImmediate();
  16791. }
  16792. loadFragment(frag, track, targetBufferTime) {
  16793. // only load if fragment is not loaded or if in audio switch
  16794. const fragState = this.fragmentTracker.getState(frag);
  16795. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  16796. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  16797. var _track$details;
  16798. if (!isMediaFragment(frag)) {
  16799. this._loadInitSegment(frag, track);
  16800. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  16801. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  16802. this.state = State.WAITING_INIT_PTS;
  16803. const mainDetails = this.mainDetails;
  16804. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  16805. alignMediaPlaylistByPDT(track.details, mainDetails);
  16806. }
  16807. } else {
  16808. super.loadFragment(frag, track, targetBufferTime);
  16809. }
  16810. } else {
  16811. this.clearTrackerIfNeeded(frag);
  16812. }
  16813. }
  16814. flushAudioIfNeeded(switchingTrack) {
  16815. if (this.media && this.bufferedTrack) {
  16816. const {
  16817. name,
  16818. lang,
  16819. assocLang,
  16820. characteristics,
  16821. audioCodec,
  16822. channels
  16823. } = this.bufferedTrack;
  16824. if (!matchesOption({
  16825. name,
  16826. lang,
  16827. assocLang,
  16828. characteristics,
  16829. audioCodec,
  16830. channels
  16831. }, switchingTrack, audioMatchPredicate)) {
  16832. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  16833. this.log('Switching audio track : flushing all audio');
  16834. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  16835. this.bufferedTrack = null;
  16836. } else {
  16837. // Main is being buffered. Set bufferedTrack so that it is flushed when switching back to alt-audio
  16838. this.bufferedTrack = switchingTrack;
  16839. }
  16840. }
  16841. }
  16842. }
  16843. completeAudioSwitch(switchingTrack) {
  16844. const {
  16845. hls
  16846. } = this;
  16847. this.flushAudioIfNeeded(switchingTrack);
  16848. this.bufferedTrack = switchingTrack;
  16849. this.switchingTrack = null;
  16850. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  16851. }
  16852. }
  16853. class BasePlaylistController extends Logger {
  16854. constructor(hls, logPrefix) {
  16855. super(logPrefix, hls.logger);
  16856. this.hls = void 0;
  16857. this.canLoad = false;
  16858. this.timer = -1;
  16859. this.hls = hls;
  16860. }
  16861. destroy() {
  16862. this.clearTimer();
  16863. // @ts-ignore
  16864. this.hls = this.log = this.warn = null;
  16865. }
  16866. clearTimer() {
  16867. if (this.timer !== -1) {
  16868. self.clearTimeout(this.timer);
  16869. this.timer = -1;
  16870. }
  16871. }
  16872. startLoad() {
  16873. this.canLoad = true;
  16874. this.loadPlaylist();
  16875. }
  16876. stopLoad() {
  16877. this.canLoad = false;
  16878. this.clearTimer();
  16879. }
  16880. switchParams(playlistUri, previous, current) {
  16881. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  16882. if (renditionReports) {
  16883. let foundIndex = -1;
  16884. for (let i = 0; i < renditionReports.length; i++) {
  16885. const attr = renditionReports[i];
  16886. let uri;
  16887. try {
  16888. uri = new self.URL(attr.URI, previous.url).href;
  16889. } catch (error) {
  16890. this.warn(`Could not construct new URL for Rendition Report: ${error}`);
  16891. uri = attr.URI || '';
  16892. }
  16893. // Use exact match. Otherwise, the last partial match, if any, will be used
  16894. // (Playlist URI includes a query string that the Rendition Report does not)
  16895. if (uri === playlistUri) {
  16896. foundIndex = i;
  16897. break;
  16898. } else if (uri === playlistUri.substring(0, uri.length)) {
  16899. foundIndex = i;
  16900. }
  16901. }
  16902. if (foundIndex !== -1) {
  16903. const attr = renditionReports[foundIndex];
  16904. const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  16905. let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  16906. if (this.hls.config.lowLatencyMode) {
  16907. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  16908. if (part >= 0 && currentGoal > previous.partTarget) {
  16909. part += 1;
  16910. }
  16911. }
  16912. const skip = current && getSkipValue(current);
  16913. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  16914. }
  16915. }
  16916. }
  16917. loadPlaylist(hlsUrlParameters) {
  16918. // Loading is handled by the subclasses
  16919. this.clearTimer();
  16920. }
  16921. loadingPlaylist(playlist, hlsUrlParameters) {
  16922. // Loading is handled by the subclasses
  16923. this.clearTimer();
  16924. }
  16925. shouldLoadPlaylist(playlist) {
  16926. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  16927. }
  16928. getUrlWithDirectives(uri, hlsUrlParameters) {
  16929. if (hlsUrlParameters) {
  16930. try {
  16931. return hlsUrlParameters.addDirectives(uri);
  16932. } catch (error) {
  16933. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  16934. }
  16935. }
  16936. return uri;
  16937. }
  16938. playlistLoaded(index, data, previousDetails) {
  16939. const {
  16940. details,
  16941. stats
  16942. } = data;
  16943. // Set last updated date-time
  16944. const now = self.performance.now();
  16945. const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  16946. details.advancedDateTime = Date.now() - elapsed;
  16947. // shift fragment starts with timelineOffset
  16948. const timelineOffset = this.hls.config.timelineOffset;
  16949. if (timelineOffset !== details.appliedTimelineOffset) {
  16950. const offset = Math.max(timelineOffset || 0, 0);
  16951. details.appliedTimelineOffset = offset;
  16952. details.fragments.forEach(frag => {
  16953. frag.start = frag.playlistOffset + offset;
  16954. });
  16955. }
  16956. // if current playlist is a live playlist, arm a timer to reload it
  16957. if (details.live || previousDetails != null && previousDetails.live) {
  16958. const levelOrTrack = 'levelInfo' in data ? data.levelInfo : data.track;
  16959. details.reloaded(previousDetails);
  16960. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  16961. if (previousDetails && details.fragments.length > 0) {
  16962. mergeDetails(previousDetails, details);
  16963. const error = details.playlistParsingError;
  16964. if (error) {
  16965. this.warn(error);
  16966. const hls = this.hls;
  16967. if (!hls.config.ignorePlaylistParsingErrors) {
  16968. var _details$fragments$;
  16969. const {
  16970. networkDetails
  16971. } = data;
  16972. hls.trigger(Events.ERROR, {
  16973. type: ErrorTypes.NETWORK_ERROR,
  16974. details: ErrorDetails.LEVEL_PARSING_ERROR,
  16975. fatal: false,
  16976. url: details.url,
  16977. error,
  16978. reason: error.message,
  16979. level: data.level || undefined,
  16980. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  16981. networkDetails,
  16982. stats
  16983. });
  16984. return;
  16985. }
  16986. details.playlistParsingError = null;
  16987. }
  16988. }
  16989. if (details.requestScheduled === -1) {
  16990. details.requestScheduled = stats.loading.start;
  16991. }
  16992. const bufferInfo = this.hls.mainForwardBufferInfo;
  16993. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  16994. const distanceToLiveEdgeMs = (details.edge - position) * 1000;
  16995. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  16996. if (details.requestScheduled + reloadInterval < now) {
  16997. details.requestScheduled = now;
  16998. } else {
  16999. details.requestScheduled += reloadInterval;
  17000. }
  17001. this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);
  17002. if (!this.canLoad || !details.live) {
  17003. return;
  17004. }
  17005. let deliveryDirectives;
  17006. let msn = undefined;
  17007. let part = undefined;
  17008. if (details.canBlockReload && details.endSN && details.advanced) {
  17009. // Load level with LL-HLS delivery directives
  17010. const lowLatencyMode = this.hls.config.lowLatencyMode;
  17011. const lastPartSn = details.lastPartSn;
  17012. const endSn = details.endSN;
  17013. const lastPartIndex = details.lastPartIndex;
  17014. const hasParts = lastPartIndex !== -1;
  17015. const atLastPartOfSegment = lastPartSn === endSn;
  17016. if (hasParts) {
  17017. // When low latency mode is disabled, request the last part of the next segment
  17018. if (atLastPartOfSegment) {
  17019. msn = endSn + 1;
  17020. part = lowLatencyMode ? 0 : lastPartIndex;
  17021. } else {
  17022. msn = lastPartSn;
  17023. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  17024. }
  17025. } else {
  17026. msn = endSn + 1;
  17027. }
  17028. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  17029. // Update directives to obtain the Playlist that has the estimated additional duration of media
  17030. const lastAdvanced = details.age;
  17031. const cdnAge = lastAdvanced + details.ageHeader;
  17032. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  17033. if (currentGoal > 0) {
  17034. if (cdnAge > details.targetduration * 3) {
  17035. // Omit segment and part directives when the last response was more than 3 target durations ago,
  17036. this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);
  17037. msn = undefined;
  17038. part = undefined;
  17039. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  17040. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  17041. // then we either can't catchup, or the "age" header cannot be trusted.
  17042. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  17043. currentGoal = 0;
  17044. } else {
  17045. const segments = Math.floor(currentGoal / details.targetduration);
  17046. msn += segments;
  17047. if (part !== undefined) {
  17048. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  17049. part += parts;
  17050. }
  17051. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  17052. }
  17053. details.tuneInGoal = currentGoal;
  17054. }
  17055. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  17056. if (lowLatencyMode || !atLastPartOfSegment) {
  17057. details.requestScheduled = now;
  17058. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17059. return;
  17060. }
  17061. } else if (details.canBlockReload || details.canSkipUntil) {
  17062. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  17063. }
  17064. if (deliveryDirectives && msn !== undefined && details.canBlockReload) {
  17065. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  17066. }
  17067. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  17068. } else {
  17069. this.clearTimer();
  17070. }
  17071. }
  17072. scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  17073. const details = updatedDetails || levelOrTrack.details;
  17074. if (!details) {
  17075. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17076. return;
  17077. }
  17078. const now = self.performance.now();
  17079. const requestScheduled = details.requestScheduled;
  17080. if (now >= requestScheduled) {
  17081. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17082. return;
  17083. }
  17084. const estimatedTimeUntilUpdate = requestScheduled - now;
  17085. this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + 'bps'} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  17086. this.clearTimer();
  17087. this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);
  17088. }
  17089. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  17090. let skip = getSkipValue(details);
  17091. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  17092. msn = previousDeliveryDirectives.msn;
  17093. part = previousDeliveryDirectives.part;
  17094. skip = HlsSkip.No;
  17095. }
  17096. return new HlsUrlParameters(msn, part, skip);
  17097. }
  17098. checkRetry(errorEvent) {
  17099. const errorDetails = errorEvent.details;
  17100. const isTimeout = isTimeoutError(errorEvent);
  17101. const errorAction = errorEvent.errorAction;
  17102. const {
  17103. action,
  17104. retryCount = 0,
  17105. retryConfig
  17106. } = errorAction || {};
  17107. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  17108. if (retry) {
  17109. var _errorEvent$context;
  17110. if (retryCount >= retryConfig.maxNumRetry) {
  17111. return false;
  17112. }
  17113. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  17114. // The LL-HLS request already timed out so retry immediately
  17115. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  17116. this.loadPlaylist();
  17117. } else {
  17118. const delay = getRetryDelay(retryConfig, retryCount);
  17119. // Schedule level/track reload
  17120. this.clearTimer();
  17121. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  17122. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  17123. }
  17124. // `levelRetry = true` used to inform other controllers that a retry is happening
  17125. errorEvent.levelRetry = true;
  17126. errorAction.resolved = true;
  17127. }
  17128. return retry;
  17129. }
  17130. }
  17131. function subtitleOptionsIdentical(trackList1, trackList2) {
  17132. if (trackList1.length !== trackList2.length) {
  17133. return false;
  17134. }
  17135. for (let i = 0; i < trackList1.length; i++) {
  17136. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  17137. return false;
  17138. }
  17139. }
  17140. return true;
  17141. }
  17142. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  17143. // Media options with the same rendition ID must be bit identical
  17144. const stableRenditionId = attrs1['STABLE-RENDITION-ID'];
  17145. if (stableRenditionId && !customAttributes) {
  17146. return stableRenditionId === attrs2['STABLE-RENDITION-ID'];
  17147. }
  17148. // When rendition ID is not present, compare attributes
  17149. return !(customAttributes || ['LANGUAGE', 'NAME', 'CHARACTERISTICS', 'AUTOSELECT', 'DEFAULT', 'FORCED', 'ASSOC-LANGUAGE']).some(subtitleAttribute => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  17150. }
  17151. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  17152. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || '').toLowerCase());
  17153. }
  17154. class AudioTrackController extends BasePlaylistController {
  17155. constructor(hls) {
  17156. super(hls, 'audio-track-controller');
  17157. this.tracks = [];
  17158. this.groupIds = null;
  17159. this.tracksInGroup = [];
  17160. this.trackId = -1;
  17161. this.currentTrack = null;
  17162. this.selectDefaultTrack = true;
  17163. this.registerListeners();
  17164. }
  17165. registerListeners() {
  17166. const {
  17167. hls
  17168. } = this;
  17169. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17170. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17171. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  17172. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  17173. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  17174. hls.on(Events.ERROR, this.onError, this);
  17175. }
  17176. unregisterListeners() {
  17177. const {
  17178. hls
  17179. } = this;
  17180. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17181. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17182. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  17183. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  17184. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  17185. hls.off(Events.ERROR, this.onError, this);
  17186. }
  17187. destroy() {
  17188. this.unregisterListeners();
  17189. this.tracks.length = 0;
  17190. this.tracksInGroup.length = 0;
  17191. this.currentTrack = null;
  17192. super.destroy();
  17193. }
  17194. onManifestLoading() {
  17195. this.tracks = [];
  17196. this.tracksInGroup = [];
  17197. this.groupIds = null;
  17198. this.currentTrack = null;
  17199. this.trackId = -1;
  17200. this.selectDefaultTrack = true;
  17201. }
  17202. onManifestParsed(event, data) {
  17203. this.tracks = data.audioTracks || [];
  17204. }
  17205. onAudioTrackLoaded(event, data) {
  17206. const {
  17207. id,
  17208. groupId,
  17209. details
  17210. } = data;
  17211. const trackInActiveGroup = this.tracksInGroup[id];
  17212. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  17213. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  17214. return;
  17215. }
  17216. const curDetails = trackInActiveGroup.details;
  17217. trackInActiveGroup.details = data.details;
  17218. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  17219. if (id === this.trackId) {
  17220. this.playlistLoaded(id, data, curDetails);
  17221. }
  17222. }
  17223. onLevelLoading(event, data) {
  17224. this.switchLevel(data.level);
  17225. }
  17226. onLevelSwitching(event, data) {
  17227. this.switchLevel(data.level);
  17228. }
  17229. switchLevel(levelIndex) {
  17230. const levelInfo = this.hls.levels[levelIndex];
  17231. if (!levelInfo) {
  17232. return;
  17233. }
  17234. const audioGroups = levelInfo.audioGroups || null;
  17235. const currentGroups = this.groupIds;
  17236. let currentTrack = this.currentTrack;
  17237. if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some(groupId => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  17238. this.groupIds = audioGroups;
  17239. this.trackId = -1;
  17240. this.currentTrack = null;
  17241. const audioTracks = this.tracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  17242. if (audioTracks.length) {
  17243. // Disable selectDefaultTrack if there are no default tracks
  17244. if (this.selectDefaultTrack && !audioTracks.some(track => track.default)) {
  17245. this.selectDefaultTrack = false;
  17246. }
  17247. // track.id should match hls.audioTracks index
  17248. audioTracks.forEach((track, i) => {
  17249. track.id = i;
  17250. });
  17251. } else if (!currentTrack && !this.tracksInGroup.length) {
  17252. // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks
  17253. return;
  17254. }
  17255. this.tracksInGroup = audioTracks;
  17256. // Find preferred track
  17257. const audioPreference = this.hls.config.audioPreference;
  17258. if (!currentTrack && audioPreference) {
  17259. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  17260. if (groupIndex > -1) {
  17261. currentTrack = audioTracks[groupIndex];
  17262. } else {
  17263. const allIndex = findMatchingOption(audioPreference, this.tracks);
  17264. currentTrack = this.tracks[allIndex];
  17265. }
  17266. }
  17267. // Select initial track
  17268. let trackId = this.findTrackId(currentTrack);
  17269. if (trackId === -1 && currentTrack) {
  17270. trackId = this.findTrackId(null);
  17271. }
  17272. // Dispatch events and load track if needed
  17273. const audioTracksUpdated = {
  17274. audioTracks
  17275. };
  17276. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(',')}`);
  17277. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  17278. const selectedTrackId = this.trackId;
  17279. if (trackId !== -1 && selectedTrackId === -1) {
  17280. this.setAudioTrack(trackId);
  17281. } else if (audioTracks.length && selectedTrackId === -1) {
  17282. var _this$groupIds;
  17283. const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(',')} track count: ${audioTracks.length}`);
  17284. this.warn(error.message);
  17285. this.hls.trigger(Events.ERROR, {
  17286. type: ErrorTypes.MEDIA_ERROR,
  17287. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  17288. fatal: true,
  17289. error
  17290. });
  17291. }
  17292. }
  17293. }
  17294. onError(event, data) {
  17295. if (data.fatal || !data.context) {
  17296. return;
  17297. }
  17298. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  17299. this.checkRetry(data);
  17300. }
  17301. }
  17302. get allAudioTracks() {
  17303. return this.tracks;
  17304. }
  17305. get audioTracks() {
  17306. return this.tracksInGroup;
  17307. }
  17308. get audioTrack() {
  17309. return this.trackId;
  17310. }
  17311. set audioTrack(newId) {
  17312. // If audio track is selected from API then don't choose from the manifest default track
  17313. this.selectDefaultTrack = false;
  17314. this.setAudioTrack(newId);
  17315. }
  17316. setAudioOption(audioOption) {
  17317. const hls = this.hls;
  17318. hls.config.audioPreference = audioOption;
  17319. if (audioOption) {
  17320. const allAudioTracks = this.allAudioTracks;
  17321. this.selectDefaultTrack = false;
  17322. if (allAudioTracks.length) {
  17323. // First see if current option matches (no switch op)
  17324. const currentTrack = this.currentTrack;
  17325. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  17326. return currentTrack;
  17327. }
  17328. // Find option in available tracks (tracksInGroup)
  17329. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  17330. if (groupIndex > -1) {
  17331. const track = this.tracksInGroup[groupIndex];
  17332. this.setAudioTrack(groupIndex);
  17333. return track;
  17334. } else if (currentTrack) {
  17335. // Find option in nearest level audio group
  17336. let searchIndex = hls.loadLevel;
  17337. if (searchIndex === -1) {
  17338. searchIndex = hls.firstAutoLevel;
  17339. }
  17340. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  17341. if (switchIndex === -1) {
  17342. // could not find matching variant
  17343. return null;
  17344. }
  17345. // and switch level to acheive the audio group switch
  17346. hls.nextLoadLevel = switchIndex;
  17347. }
  17348. if (audioOption.channels || audioOption.audioCodec) {
  17349. // Could not find a match with codec / channels predicate
  17350. // Find a match without channels or codec
  17351. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  17352. if (withoutCodecAndChannelsMatch > -1) {
  17353. return allAudioTracks[withoutCodecAndChannelsMatch];
  17354. }
  17355. }
  17356. }
  17357. }
  17358. return null;
  17359. }
  17360. setAudioTrack(newId) {
  17361. const tracks = this.tracksInGroup;
  17362. // check if level idx is valid
  17363. if (newId < 0 || newId >= tracks.length) {
  17364. this.warn(`Invalid audio track id: ${newId}`);
  17365. return;
  17366. }
  17367. this.selectDefaultTrack = false;
  17368. const lastTrack = this.currentTrack;
  17369. const track = tracks[newId];
  17370. const trackLoaded = track.details && !track.details.live;
  17371. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  17372. return;
  17373. }
  17374. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  17375. this.trackId = newId;
  17376. this.currentTrack = track;
  17377. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  17378. // Do not reload track unless live
  17379. if (trackLoaded) {
  17380. return;
  17381. }
  17382. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  17383. this.loadPlaylist(hlsUrlParameters);
  17384. }
  17385. findTrackId(currentTrack) {
  17386. const audioTracks = this.tracksInGroup;
  17387. for (let i = 0; i < audioTracks.length; i++) {
  17388. const track = audioTracks[i];
  17389. if (this.selectDefaultTrack && !track.default) {
  17390. continue;
  17391. }
  17392. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  17393. return i;
  17394. }
  17395. }
  17396. if (currentTrack) {
  17397. const {
  17398. name,
  17399. lang,
  17400. assocLang,
  17401. characteristics,
  17402. audioCodec,
  17403. channels
  17404. } = currentTrack;
  17405. for (let i = 0; i < audioTracks.length; i++) {
  17406. const track = audioTracks[i];
  17407. if (matchesOption({
  17408. name,
  17409. lang,
  17410. assocLang,
  17411. characteristics,
  17412. audioCodec,
  17413. channels
  17414. }, track, audioMatchPredicate)) {
  17415. return i;
  17416. }
  17417. }
  17418. for (let i = 0; i < audioTracks.length; i++) {
  17419. const track = audioTracks[i];
  17420. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  17421. return i;
  17422. }
  17423. }
  17424. for (let i = 0; i < audioTracks.length; i++) {
  17425. const track = audioTracks[i];
  17426. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  17427. return i;
  17428. }
  17429. }
  17430. }
  17431. return -1;
  17432. }
  17433. loadPlaylist(hlsUrlParameters) {
  17434. super.loadPlaylist();
  17435. const audioTrack = this.currentTrack;
  17436. if (!this.shouldLoadPlaylist(audioTrack)) {
  17437. return;
  17438. }
  17439. // Do not load audio rendition with URI matching main variant URI
  17440. if (useAlternateAudio(audioTrack.url, this.hls)) {
  17441. this.scheduleLoading(audioTrack, hlsUrlParameters);
  17442. }
  17443. }
  17444. loadingPlaylist(audioTrack, hlsUrlParameters) {
  17445. super.loadingPlaylist(audioTrack, hlsUrlParameters);
  17446. const id = audioTrack.id;
  17447. const groupId = audioTrack.groupId;
  17448. const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  17449. const details = audioTrack.details;
  17450. const age = details == null ? void 0 : details.age;
  17451. this.log(`Loading audio-track ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);
  17452. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  17453. url,
  17454. id,
  17455. groupId,
  17456. deliveryDirectives: hlsUrlParameters || null,
  17457. track: audioTrack
  17458. });
  17459. }
  17460. }
  17461. class BufferOperationQueue {
  17462. constructor(sourceBufferReference) {
  17463. this.tracks = void 0;
  17464. this.queues = {
  17465. video: [],
  17466. audio: [],
  17467. audiovideo: []
  17468. };
  17469. this.tracks = sourceBufferReference;
  17470. }
  17471. destroy() {
  17472. this.tracks = this.queues = null;
  17473. }
  17474. append(operation, type, pending) {
  17475. if (this.queues === null || this.tracks === null) {
  17476. return;
  17477. }
  17478. const queue = this.queues[type];
  17479. queue.push(operation);
  17480. if (queue.length === 1 && !pending) {
  17481. this.executeNext(type);
  17482. }
  17483. }
  17484. appendBlocker(type) {
  17485. return new Promise(resolve => {
  17486. const operation = {
  17487. label: 'async-blocker',
  17488. execute: resolve,
  17489. onStart: () => {},
  17490. onComplete: () => {},
  17491. onError: () => {}
  17492. };
  17493. this.append(operation, type);
  17494. });
  17495. }
  17496. prependBlocker(type) {
  17497. return new Promise(resolve => {
  17498. if (this.queues) {
  17499. const operation = {
  17500. label: 'async-blocker-prepend',
  17501. execute: resolve,
  17502. onStart: () => {},
  17503. onComplete: () => {},
  17504. onError: () => {}
  17505. };
  17506. this.queues[type].unshift(operation);
  17507. }
  17508. });
  17509. }
  17510. removeBlockers() {
  17511. if (this.queues === null) {
  17512. return;
  17513. }
  17514. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach(queue => {
  17515. var _queue$;
  17516. const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  17517. if (label === 'async-blocker' || label === 'async-blocker-prepend') {
  17518. queue[0].execute();
  17519. queue.splice(0, 1);
  17520. }
  17521. });
  17522. }
  17523. unblockAudio(op) {
  17524. if (this.queues === null) {
  17525. return;
  17526. }
  17527. const queue = this.queues.audio;
  17528. if (queue[0] === op) {
  17529. this.shiftAndExecuteNext('audio');
  17530. }
  17531. }
  17532. executeNext(type) {
  17533. if (this.queues === null || this.tracks === null) {
  17534. return;
  17535. }
  17536. const queue = this.queues[type];
  17537. if (queue.length) {
  17538. const operation = queue[0];
  17539. try {
  17540. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  17541. // which do not end with this event must call _onSBUpdateEnd manually
  17542. operation.execute();
  17543. } catch (error) {
  17544. var _this$tracks$type;
  17545. operation.onError(error);
  17546. if (this.queues === null || this.tracks === null) {
  17547. return;
  17548. }
  17549. // Only shift the current operation off, otherwise the updateend handler will do this for us
  17550. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  17551. if (!(sb != null && sb.updating)) {
  17552. this.shiftAndExecuteNext(type);
  17553. }
  17554. }
  17555. }
  17556. }
  17557. shiftAndExecuteNext(type) {
  17558. if (this.queues === null) {
  17559. return;
  17560. }
  17561. this.queues[type].shift();
  17562. this.executeNext(type);
  17563. }
  17564. current(type) {
  17565. var _this$queues;
  17566. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  17567. }
  17568. toString() {
  17569. const {
  17570. queues,
  17571. tracks
  17572. } = this;
  17573. if (queues === null || tracks === null) {
  17574. return `<destroyed>`;
  17575. }
  17576. return `
  17577. ${this.list('video')}
  17578. ${this.list('audio')}
  17579. ${this.list('audiovideo')}}`;
  17580. }
  17581. list(type) {
  17582. var _this$queues2, _this$tracks;
  17583. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : '';
  17584. }
  17585. listSbInfo(type) {
  17586. var _this$tracks2;
  17587. const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  17588. const sb = track == null ? void 0 : track.buffer;
  17589. if (!sb) {
  17590. return 'none';
  17591. }
  17592. return `SourceBuffer${sb.updating ? ' updating' : ''}${track.ended ? ' ended' : ''}${track.ending ? ' ending' : ''}`;
  17593. }
  17594. listOps(type) {
  17595. var _this$queues3;
  17596. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map(op => op.label).join(', ')) || '';
  17597. }
  17598. }
  17599. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  17600. const TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';
  17601. class HlsJsTrackRemovedError extends Error {
  17602. constructor(message) {
  17603. super(message);
  17604. this.name = TRACK_REMOVED_ERROR_NAME;
  17605. }
  17606. }
  17607. class BufferController extends Logger {
  17608. constructor(hls, fragmentTracker) {
  17609. super('buffer-controller', hls.logger);
  17610. this.hls = void 0;
  17611. this.fragmentTracker = void 0;
  17612. // The level details used to determine duration, target-duration and live
  17613. this.details = null;
  17614. // cache the self generated object url to detect hijack of video tag
  17615. this._objectUrl = null;
  17616. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  17617. this.operationQueue = null;
  17618. // The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)
  17619. this.bufferCodecEventsTotal = 0;
  17620. // A reference to the attached media element
  17621. this.media = null;
  17622. // A reference to the active media source
  17623. this.mediaSource = null;
  17624. // Last MP3 audio chunk appended
  17625. this.lastMpegAudioChunk = null;
  17626. // Audio fragment blocked from appending until corresponding video appends or context changes
  17627. this.blockedAudioAppend = null;
  17628. // Keep track of video append position for unblocking audio
  17629. this.lastVideoAppendEnd = 0;
  17630. // Whether or not to use ManagedMediaSource API and append source element to media element.
  17631. this.appendSource = void 0;
  17632. // Transferred MediaSource information used to detmerine if duration end endstream may be appended
  17633. this.transferData = void 0;
  17634. // Directives used to override default MediaSource handling
  17635. this.overrides = void 0;
  17636. // Error counters
  17637. this.appendErrors = {
  17638. audio: 0,
  17639. video: 0,
  17640. audiovideo: 0
  17641. };
  17642. // Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.
  17643. this.tracks = {};
  17644. // Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.
  17645. this.sourceBuffers = [[null, null], [null, null]];
  17646. this._onEndStreaming = event => {
  17647. var _this$mediaSource;
  17648. if (!this.hls) {
  17649. return;
  17650. }
  17651. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== 'open') {
  17652. return;
  17653. }
  17654. this.hls.pauseBuffering();
  17655. };
  17656. this._onStartStreaming = event => {
  17657. if (!this.hls) {
  17658. return;
  17659. }
  17660. this.hls.resumeBuffering();
  17661. };
  17662. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  17663. this._onMediaSourceOpen = e => {
  17664. const {
  17665. media,
  17666. mediaSource
  17667. } = this;
  17668. if (e) {
  17669. this.log('Media source opened');
  17670. }
  17671. if (!media || !mediaSource) {
  17672. return;
  17673. }
  17674. // once received, don't listen anymore to sourceopen event
  17675. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  17676. media.removeEventListener('emptied', this._onMediaEmptied);
  17677. this.updateDuration();
  17678. this.hls.trigger(Events.MEDIA_ATTACHED, {
  17679. media,
  17680. mediaSource: mediaSource
  17681. });
  17682. if (this.mediaSource !== null) {
  17683. this.checkPendingTracks();
  17684. }
  17685. };
  17686. this._onMediaSourceClose = () => {
  17687. this.log('Media source closed');
  17688. };
  17689. this._onMediaSourceEnded = () => {
  17690. this.log('Media source ended');
  17691. };
  17692. this._onMediaEmptied = () => {
  17693. const {
  17694. mediaSrc,
  17695. _objectUrl
  17696. } = this;
  17697. if (mediaSrc !== _objectUrl) {
  17698. this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  17699. }
  17700. };
  17701. this.hls = hls;
  17702. this.fragmentTracker = fragmentTracker;
  17703. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  17704. this.initTracks();
  17705. this.registerListeners();
  17706. }
  17707. hasSourceTypes() {
  17708. return Object.keys(this.tracks).length > 0;
  17709. }
  17710. destroy() {
  17711. this.unregisterListeners();
  17712. this.details = null;
  17713. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  17714. this.transferData = this.overrides = undefined;
  17715. if (this.operationQueue) {
  17716. this.operationQueue.destroy();
  17717. this.operationQueue = null;
  17718. }
  17719. // @ts-ignore
  17720. this.hls = this.fragmentTracker = null;
  17721. // @ts-ignore
  17722. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  17723. // @ts-ignore
  17724. this._onMediaSourceEnded = null;
  17725. // @ts-ignore
  17726. this._onStartStreaming = this._onEndStreaming = null;
  17727. }
  17728. registerListeners() {
  17729. const {
  17730. hls
  17731. } = this;
  17732. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17733. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17734. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17735. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17736. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  17737. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17738. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17739. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  17740. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17741. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17742. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  17743. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  17744. hls.on(Events.ERROR, this.onError, this);
  17745. }
  17746. unregisterListeners() {
  17747. const {
  17748. hls
  17749. } = this;
  17750. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17751. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17752. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17753. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17754. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  17755. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17756. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17757. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  17758. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17759. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17760. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  17761. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  17762. hls.off(Events.ERROR, this.onError, this);
  17763. }
  17764. transferMedia() {
  17765. const {
  17766. media,
  17767. mediaSource
  17768. } = this;
  17769. if (!media) {
  17770. return null;
  17771. }
  17772. const tracks = {};
  17773. if (this.operationQueue) {
  17774. const updating = this.isUpdating();
  17775. if (!updating) {
  17776. this.operationQueue.removeBlockers();
  17777. }
  17778. const queued = this.isQueued();
  17779. if (updating || queued) {
  17780. this.warn(`Transfering MediaSource with${queued ? ' operations in queue' : ''}${updating ? ' updating SourceBuffer(s)' : ''} ${this.operationQueue}`);
  17781. }
  17782. this.operationQueue.destroy();
  17783. }
  17784. const transferData = this.transferData;
  17785. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  17786. _extends(tracks, transferData.tracks);
  17787. } else {
  17788. this.sourceBuffers.forEach(tuple => {
  17789. const [type] = tuple;
  17790. if (type) {
  17791. tracks[type] = _extends({}, this.tracks[type]);
  17792. this.removeBuffer(type);
  17793. }
  17794. tuple[0] = tuple[1] = null;
  17795. });
  17796. }
  17797. return {
  17798. media,
  17799. mediaSource,
  17800. tracks
  17801. };
  17802. }
  17803. initTracks() {
  17804. const tracks = {};
  17805. this.sourceBuffers = [[null, null], [null, null]];
  17806. this.tracks = tracks;
  17807. this.resetQueue();
  17808. this.resetAppendErrors();
  17809. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  17810. this.lastVideoAppendEnd = 0;
  17811. }
  17812. onManifestLoading() {
  17813. this.bufferCodecEventsTotal = 0;
  17814. this.details = null;
  17815. }
  17816. onManifestParsed(event, data) {
  17817. var _this$transferData;
  17818. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  17819. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  17820. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  17821. // it will contain the expected nb of source buffers, no need to compute it
  17822. let codecEvents = 2;
  17823. if (data.audio && !data.video || !data.altAudio) {
  17824. codecEvents = 1;
  17825. }
  17826. this.bufferCodecEventsTotal = codecEvents;
  17827. this.log(`${codecEvents} bufferCodec event(s) expected.`);
  17828. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  17829. this.bufferCreated();
  17830. }
  17831. }
  17832. onMediaAttaching(event, data) {
  17833. const media = this.media = data.media;
  17834. const MediaSource = getMediaSource(this.appendSource);
  17835. this.transferData = this.overrides = undefined;
  17836. if (media && MediaSource) {
  17837. const transferringMedia = !!data.mediaSource;
  17838. if (transferringMedia || data.overrides) {
  17839. this.transferData = data;
  17840. this.overrides = data.overrides;
  17841. }
  17842. const ms = this.mediaSource = data.mediaSource || new MediaSource();
  17843. this.assignMediaSource(ms);
  17844. if (transferringMedia) {
  17845. this._objectUrl = media.src;
  17846. this.attachTransferred();
  17847. } else {
  17848. // cache the locally generated object url
  17849. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  17850. // link video and media Source
  17851. if (this.appendSource) {
  17852. try {
  17853. media.removeAttribute('src');
  17854. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  17855. const MMS = self.ManagedMediaSource;
  17856. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  17857. removeSourceChildren(media);
  17858. addSource(media, objectUrl);
  17859. media.load();
  17860. } catch (error) {
  17861. media.src = objectUrl;
  17862. }
  17863. } else {
  17864. media.src = objectUrl;
  17865. }
  17866. }
  17867. media.addEventListener('emptied', this._onMediaEmptied);
  17868. }
  17869. }
  17870. assignMediaSource(ms) {
  17871. var _this$transferData2, _ms$constructor;
  17872. this.log(`${((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? 'transferred' : 'created'} media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
  17873. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  17874. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  17875. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  17876. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  17877. if (this.appendSource) {
  17878. ms.addEventListener('startstreaming', this._onStartStreaming);
  17879. ms.addEventListener('endstreaming', this._onEndStreaming);
  17880. }
  17881. }
  17882. attachTransferred() {
  17883. const media = this.media;
  17884. const data = this.transferData;
  17885. if (!data || !media) {
  17886. return;
  17887. }
  17888. const requiredTracks = this.tracks;
  17889. const transferredTracks = data.tracks;
  17890. const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  17891. const trackCount = trackNames ? trackNames.length : 0;
  17892. const mediaSourceOpenCallback = () => {
  17893. if (this.media && this.mediaSourceOpenOrEnded) {
  17894. this._onMediaSourceOpen();
  17895. }
  17896. };
  17897. if (transferredTracks && trackNames && trackCount) {
  17898. if (!this.tracksReady) {
  17899. // Wait for CODECS event(s)
  17900. this.hls.config.startFragPrefetch = true;
  17901. this.log(`attachTransferred: waiting for SourceBuffer track info`);
  17902. return;
  17903. }
  17904. this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
  17905. required tracks: ${stringify(requiredTracks, (key, value) => key === 'initSegment' ? undefined : value)};
  17906. transfer tracks: ${stringify(transferredTracks, (key, value) => key === 'initSegment' ? undefined : value)}}`);
  17907. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  17908. // destroy attaching media source
  17909. data.mediaSource = null;
  17910. data.tracks = undefined;
  17911. const currentTime = media.currentTime;
  17912. const details = this.details;
  17913. const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  17914. if (startTime - currentTime > 1) {
  17915. this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);
  17916. return;
  17917. }
  17918. this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(transferredTracks)}"->"${Object.keys(requiredTracks)}") start time: ${startTime} currentTime: ${currentTime}`);
  17919. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  17920. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  17921. media.currentTime = startTime;
  17922. return;
  17923. }
  17924. this.transferData = undefined;
  17925. trackNames.forEach(trackName => {
  17926. const type = trackName;
  17927. const track = transferredTracks[type];
  17928. if (track) {
  17929. const sb = track.buffer;
  17930. if (sb) {
  17931. // Purge fragment tracker of ejected segments for existing buffer
  17932. const fragmentTracker = this.fragmentTracker;
  17933. const playlistType = track.id;
  17934. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  17935. const bufferedTimeRanges = BufferHelper.getBuffered(sb);
  17936. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  17937. }
  17938. // Transfer SourceBuffer
  17939. const sbIndex = sourceBufferNameToIndex(type);
  17940. const sbTuple = [type, sb];
  17941. this.sourceBuffers[sbIndex] = sbTuple;
  17942. if (sb.updating && this.operationQueue) {
  17943. this.operationQueue.prependBlocker(type);
  17944. }
  17945. this.trackSourceBuffer(type, track);
  17946. }
  17947. }
  17948. });
  17949. mediaSourceOpenCallback();
  17950. this.bufferCreated();
  17951. } else {
  17952. this.log(`attachTransferred: MediaSource w/o SourceBuffers`);
  17953. mediaSourceOpenCallback();
  17954. }
  17955. }
  17956. get mediaSourceOpenOrEnded() {
  17957. var _this$mediaSource2;
  17958. const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;
  17959. return readyState === 'open' || readyState === 'ended';
  17960. }
  17961. onMediaDetaching(event, data) {
  17962. const transferringMedia = !!data.transferMedia;
  17963. this.transferData = this.overrides = undefined;
  17964. const {
  17965. media,
  17966. mediaSource,
  17967. _objectUrl
  17968. } = this;
  17969. if (mediaSource) {
  17970. this.log(`media source ${transferringMedia ? 'transferring' : 'detaching'}`);
  17971. if (transferringMedia) {
  17972. // Detach SourceBuffers without removing from MediaSource
  17973. // and leave `tracks` (required SourceBuffers configuration)
  17974. this.sourceBuffers.forEach(([type]) => {
  17975. if (type) {
  17976. this.removeBuffer(type);
  17977. }
  17978. });
  17979. this.resetQueue();
  17980. } else {
  17981. if (this.mediaSourceOpenOrEnded) {
  17982. const open = mediaSource.readyState === 'open';
  17983. try {
  17984. const sourceBuffers = mediaSource.sourceBuffers;
  17985. for (let i = sourceBuffers.length; i--;) {
  17986. if (open) {
  17987. sourceBuffers[i].abort();
  17988. }
  17989. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  17990. }
  17991. if (open) {
  17992. // endOfStream could trigger exception if any sourcebuffer is in updating state
  17993. // we don't really care about checking sourcebuffer state here,
  17994. // as we are anyway detaching the MediaSource
  17995. // let's just avoid this exception to propagate
  17996. mediaSource.endOfStream();
  17997. }
  17998. } catch (err) {
  17999. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  18000. }
  18001. }
  18002. // Clean up the SourceBuffers by invoking onBufferReset
  18003. if (this.sourceBufferCount) {
  18004. this.onBufferReset();
  18005. }
  18006. }
  18007. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  18008. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  18009. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  18010. if (this.appendSource) {
  18011. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  18012. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  18013. }
  18014. this.mediaSource = null;
  18015. this._objectUrl = null;
  18016. }
  18017. // Detach properly the MediaSource from the HTMLMediaElement as
  18018. // suggested in https://github.com/w3c/media-source/issues/53.
  18019. if (media) {
  18020. media.removeEventListener('emptied', this._onMediaEmptied);
  18021. if (!transferringMedia) {
  18022. if (_objectUrl) {
  18023. self.URL.revokeObjectURL(_objectUrl);
  18024. }
  18025. // clean up video tag src only if it's our own url. some external libraries might
  18026. // hijack the video tag and change its 'src' without destroying the Hls instance first
  18027. if (this.mediaSrc === _objectUrl) {
  18028. media.removeAttribute('src');
  18029. if (this.appendSource) {
  18030. removeSourceChildren(media);
  18031. }
  18032. media.load();
  18033. } else {
  18034. this.warn('media|source.src was changed by a third party - skip cleanup');
  18035. }
  18036. }
  18037. this.media = null;
  18038. }
  18039. this.hls.trigger(Events.MEDIA_DETACHED, data);
  18040. }
  18041. onBufferReset() {
  18042. this.sourceBuffers.forEach(([type]) => {
  18043. if (type) {
  18044. this.resetBuffer(type);
  18045. }
  18046. });
  18047. this.initTracks();
  18048. }
  18049. resetBuffer(type) {
  18050. var _this$tracks$type;
  18051. const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  18052. this.removeBuffer(type);
  18053. if (sb) {
  18054. try {
  18055. var _this$mediaSource3;
  18056. if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {
  18057. this.mediaSource.removeSourceBuffer(sb);
  18058. }
  18059. } catch (err) {
  18060. this.warn(`onBufferReset ${type}`, err);
  18061. }
  18062. }
  18063. delete this.tracks[type];
  18064. }
  18065. removeBuffer(type) {
  18066. this.removeBufferListeners(type);
  18067. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  18068. const track = this.tracks[type];
  18069. if (track) {
  18070. track.buffer = undefined;
  18071. }
  18072. }
  18073. resetQueue() {
  18074. if (this.operationQueue) {
  18075. this.operationQueue.destroy();
  18076. }
  18077. this.operationQueue = new BufferOperationQueue(this.tracks);
  18078. }
  18079. onBufferCodecs(event, data) {
  18080. const tracks = this.tracks;
  18081. const trackNames = Object.keys(data);
  18082. this.log(`BUFFER_CODECS: "${trackNames}" (current SB count ${this.sourceBufferCount})`);
  18083. const unmuxedToMuxed = 'audiovideo' in data && (tracks.audio || tracks.video) || tracks.audiovideo && ('audio' in data || 'video' in data);
  18084. const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some(sbName => !tracks[sbName]);
  18085. if (unmuxedToMuxed || muxedToUnmuxed) {
  18086. this.warn(`Unsupported transition between "${Object.keys(tracks)}" and "${trackNames}" SourceBuffers`);
  18087. // Do not add incompatible track ('audiovideo' <-> 'video'/'audio').
  18088. // Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.
  18089. // This will either be resolved by level switch or could be handled with recoverMediaError().
  18090. return;
  18091. }
  18092. trackNames.forEach(trackName => {
  18093. var _this$transferData3, _this$transferData3$t, _trackCodec;
  18094. const parsedTrack = data[trackName];
  18095. const {
  18096. id,
  18097. codec,
  18098. levelCodec,
  18099. container,
  18100. metadata,
  18101. supplemental
  18102. } = parsedTrack;
  18103. let track = tracks[trackName];
  18104. const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];
  18105. const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  18106. const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  18107. const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  18108. if (!track) {
  18109. track = tracks[trackName] = {
  18110. buffer: undefined,
  18111. listeners: [],
  18112. codec,
  18113. supplemental,
  18114. container,
  18115. levelCodec,
  18116. metadata,
  18117. id
  18118. };
  18119. }
  18120. // check if SourceBuffer codec needs to change
  18121. const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  18122. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  18123. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  18124. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  18125. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  18126. if (trackName.slice(0, 5) === 'audio') {
  18127. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  18128. }
  18129. this.log(`switching codec ${sbCodec} to ${trackCodec}`);
  18130. if (trackCodec !== (track.pendingCodec || track.codec)) {
  18131. track.pendingCodec = trackCodec;
  18132. }
  18133. track.container = container;
  18134. this.appendChangeType(trackName, container, trackCodec);
  18135. }
  18136. });
  18137. if (this.tracksReady || this.sourceBufferCount) {
  18138. data.tracks = this.sourceBufferTracks;
  18139. }
  18140. // if sourcebuffers already created, do nothing ...
  18141. if (this.sourceBufferCount) {
  18142. return;
  18143. }
  18144. if (this.mediaSourceOpenOrEnded) {
  18145. this.checkPendingTracks();
  18146. }
  18147. }
  18148. get sourceBufferTracks() {
  18149. return Object.keys(this.tracks).reduce((baseTracks, type) => {
  18150. const track = this.tracks[type];
  18151. baseTracks[type] = {
  18152. id: track.id,
  18153. container: track.container,
  18154. codec: track.codec,
  18155. levelCodec: track.levelCodec
  18156. };
  18157. return baseTracks;
  18158. }, {});
  18159. }
  18160. appendChangeType(type, container, codec) {
  18161. const mimeType = `${container};codecs=${codec}`;
  18162. const operation = {
  18163. label: `change-type=${mimeType}`,
  18164. execute: () => {
  18165. const track = this.tracks[type];
  18166. if (track) {
  18167. const sb = track.buffer;
  18168. if (sb != null && sb.changeType) {
  18169. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  18170. sb.changeType(mimeType);
  18171. track.codec = codec;
  18172. track.container = container;
  18173. }
  18174. }
  18175. this.shiftAndExecuteNext(type);
  18176. },
  18177. onStart: () => {},
  18178. onComplete: () => {},
  18179. onError: error => {
  18180. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  18181. }
  18182. };
  18183. this.append(operation, type, this.isPending(this.tracks[type]));
  18184. }
  18185. blockAudio(partOrFrag) {
  18186. var _this$fragmentTracker;
  18187. const pStart = partOrFrag.start;
  18188. const pTime = pStart + partOrFrag.duration * 0.05;
  18189. const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  18190. if (atGap) {
  18191. return;
  18192. }
  18193. const op = {
  18194. label: 'block-audio',
  18195. execute: () => {
  18196. var _this$fragmentTracker2;
  18197. const videoTrack = this.tracks.video;
  18198. if (this.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this$fragmentTracker2 = this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker2.gap) === true) {
  18199. this.blockedAudioAppend = null;
  18200. this.shiftAndExecuteNext('audio');
  18201. }
  18202. },
  18203. onStart: () => {},
  18204. onComplete: () => {},
  18205. onError: error => {
  18206. this.warn('Error executing block-audio operation', error);
  18207. }
  18208. };
  18209. this.blockedAudioAppend = {
  18210. op,
  18211. frag: partOrFrag
  18212. };
  18213. this.append(op, 'audio', true);
  18214. }
  18215. unblockAudio() {
  18216. const {
  18217. blockedAudioAppend,
  18218. operationQueue
  18219. } = this;
  18220. if (blockedAudioAppend && operationQueue) {
  18221. this.blockedAudioAppend = null;
  18222. operationQueue.unblockAudio(blockedAudioAppend.op);
  18223. }
  18224. }
  18225. onBufferAppending(event, eventData) {
  18226. const {
  18227. tracks
  18228. } = this;
  18229. const {
  18230. data,
  18231. type,
  18232. parent,
  18233. frag,
  18234. part,
  18235. chunkMeta,
  18236. offset
  18237. } = eventData;
  18238. const chunkStats = chunkMeta.buffering[type];
  18239. const {
  18240. sn,
  18241. cc
  18242. } = frag;
  18243. const bufferAppendingStart = self.performance.now();
  18244. chunkStats.start = bufferAppendingStart;
  18245. const fragBuffering = frag.stats.buffering;
  18246. const partBuffering = part ? part.stats.buffering : null;
  18247. if (fragBuffering.start === 0) {
  18248. fragBuffering.start = bufferAppendingStart;
  18249. }
  18250. if (partBuffering && partBuffering.start === 0) {
  18251. partBuffering.start = bufferAppendingStart;
  18252. }
  18253. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  18254. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  18255. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  18256. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  18257. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  18258. const audioTrack = tracks.audio;
  18259. let checkTimestampOffset = false;
  18260. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  18261. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  18262. this.lastMpegAudioChunk = chunkMeta;
  18263. }
  18264. // Block audio append until overlapping video append
  18265. const videoTrack = tracks.video;
  18266. const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  18267. if (videoSb && sn !== 'initSegment') {
  18268. const partOrFrag = part || frag;
  18269. const blockedAudioAppend = this.blockedAudioAppend;
  18270. if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {
  18271. const pStart = partOrFrag.start;
  18272. const pTime = pStart + partOrFrag.duration * 0.05;
  18273. const vbuffered = videoSb.buffered;
  18274. const vappending = this.currentOp('video');
  18275. if (!vbuffered.length && !vappending) {
  18276. // wait for video before appending audio
  18277. this.blockAudio(partOrFrag);
  18278. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  18279. // audio is ahead of video
  18280. this.blockAudio(partOrFrag);
  18281. }
  18282. } else if (type === 'video') {
  18283. const videoAppendEnd = partOrFrag.end;
  18284. if (blockedAudioAppend) {
  18285. const audioStart = blockedAudioAppend.frag.start;
  18286. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  18287. this.unblockAudio();
  18288. }
  18289. }
  18290. this.lastVideoAppendEnd = videoAppendEnd;
  18291. }
  18292. }
  18293. const fragStart = (part || frag).start;
  18294. const operation = {
  18295. label: `append-${type}`,
  18296. execute: () => {
  18297. var _this$tracks$type2;
  18298. chunkStats.executeStart = self.performance.now();
  18299. const sb = (_this$tracks$type2 = this.tracks[type]) == null ? void 0 : _this$tracks$type2.buffer;
  18300. if (sb) {
  18301. if (checkTimestampOffset) {
  18302. this.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  18303. } else if (offset !== undefined && isFiniteNumber(offset)) {
  18304. this.updateTimestampOffset(sb, offset, 0.000001, type, sn, cc);
  18305. }
  18306. }
  18307. this.appendExecutor(data, type);
  18308. },
  18309. onStart: () => {
  18310. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  18311. },
  18312. onComplete: () => {
  18313. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  18314. const end = self.performance.now();
  18315. chunkStats.executeEnd = chunkStats.end = end;
  18316. if (fragBuffering.first === 0) {
  18317. fragBuffering.first = end;
  18318. }
  18319. if (partBuffering && partBuffering.first === 0) {
  18320. partBuffering.first = end;
  18321. }
  18322. const timeRanges = {};
  18323. this.sourceBuffers.forEach(([type, sb]) => {
  18324. if (type) {
  18325. timeRanges[type] = BufferHelper.getBuffered(sb);
  18326. }
  18327. });
  18328. this.appendErrors[type] = 0;
  18329. if (type === 'audio' || type === 'video') {
  18330. this.appendErrors.audiovideo = 0;
  18331. } else {
  18332. this.appendErrors.audio = 0;
  18333. this.appendErrors.video = 0;
  18334. }
  18335. this.hls.trigger(Events.BUFFER_APPENDED, {
  18336. type,
  18337. frag,
  18338. part,
  18339. chunkMeta,
  18340. parent: frag.type,
  18341. timeRanges
  18342. });
  18343. },
  18344. onError: error => {
  18345. var _this$media;
  18346. // in case any error occured while appending, put back segment in segments table
  18347. const event = {
  18348. type: ErrorTypes.MEDIA_ERROR,
  18349. parent: frag.type,
  18350. details: ErrorDetails.BUFFER_APPEND_ERROR,
  18351. sourceBufferName: type,
  18352. frag,
  18353. part,
  18354. chunkMeta,
  18355. error,
  18356. err: error,
  18357. fatal: false
  18358. };
  18359. const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;
  18360. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == 'QuotaExceededError' || `quota` in error) {
  18361. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  18362. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  18363. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  18364. } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {
  18365. // Allow retry for "Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing" errors
  18366. event.errorAction = createDoNothingErrorAction(true);
  18367. } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {
  18368. // Do nothing if sourceBuffers were removed (media is detached and append was not aborted)
  18369. event.errorAction = createDoNothingErrorAction(true);
  18370. } else {
  18371. const appendErrorCount = ++this.appendErrors[type];
  18372. /* with UHD content, we could get loop of quota exceeded error until
  18373. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  18374. */
  18375. this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer (${mediaError ? mediaError : 'no media error'})`);
  18376. if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {
  18377. event.fatal = true;
  18378. }
  18379. }
  18380. this.hls.trigger(Events.ERROR, event);
  18381. }
  18382. };
  18383. this.append(operation, type, this.isPending(this.tracks[type]));
  18384. }
  18385. getFlushOp(type, start, end) {
  18386. this.log(`queuing "${type}" remove ${start}-${end}`);
  18387. return {
  18388. label: 'remove',
  18389. execute: () => {
  18390. this.removeExecutor(type, start, end);
  18391. },
  18392. onStart: () => {
  18393. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  18394. },
  18395. onComplete: () => {
  18396. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  18397. this.hls.trigger(Events.BUFFER_FLUSHED, {
  18398. type
  18399. });
  18400. },
  18401. onError: error => {
  18402. this.warn(`Failed to remove ${start}-${end} from "${type}" SourceBuffer`, error);
  18403. }
  18404. };
  18405. }
  18406. onBufferFlushing(event, data) {
  18407. const {
  18408. type,
  18409. startOffset,
  18410. endOffset
  18411. } = data;
  18412. if (type) {
  18413. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  18414. } else {
  18415. this.sourceBuffers.forEach(([type]) => {
  18416. if (type) {
  18417. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  18418. }
  18419. });
  18420. }
  18421. }
  18422. onFragParsed(event, data) {
  18423. const {
  18424. frag,
  18425. part
  18426. } = data;
  18427. const buffersAppendedTo = [];
  18428. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  18429. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  18430. buffersAppendedTo.push('audiovideo');
  18431. } else {
  18432. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  18433. buffersAppendedTo.push('audio');
  18434. }
  18435. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  18436. buffersAppendedTo.push('video');
  18437. }
  18438. }
  18439. const onUnblocked = () => {
  18440. const now = self.performance.now();
  18441. frag.stats.buffering.end = now;
  18442. if (part) {
  18443. part.stats.buffering.end = now;
  18444. }
  18445. const stats = part ? part.stats : frag.stats;
  18446. this.hls.trigger(Events.FRAG_BUFFERED, {
  18447. frag,
  18448. part,
  18449. stats,
  18450. id: frag.type
  18451. });
  18452. };
  18453. if (buffersAppendedTo.length === 0) {
  18454. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  18455. }
  18456. this.blockBuffers(onUnblocked, buffersAppendedTo).catch(error => {
  18457. this.warn(`Fragment buffered callback ${error}`);
  18458. this.stepOperationQueue(this.sourceBufferTypes);
  18459. });
  18460. }
  18461. onFragChanged(event, data) {
  18462. this.trimBuffers();
  18463. }
  18464. get bufferedToEnd() {
  18465. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  18466. var _this$tracks$type3, _this$tracks$type4;
  18467. return type && (!((_this$tracks$type3 = this.tracks[type]) != null && _this$tracks$type3.ended) || ((_this$tracks$type4 = this.tracks[type]) == null ? void 0 : _this$tracks$type4.ending));
  18468. });
  18469. }
  18470. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  18471. // an undefined data.type will mark all buffers as EOS.
  18472. onBufferEos(event, data) {
  18473. var _this$overrides;
  18474. this.sourceBuffers.forEach(([type]) => {
  18475. if (type) {
  18476. const track = this.tracks[type];
  18477. if (!data.type || data.type === type) {
  18478. track.ending = true;
  18479. if (!track.ended) {
  18480. track.ended = true;
  18481. this.log(`${type} buffer reached EOS`);
  18482. }
  18483. }
  18484. }
  18485. });
  18486. const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  18487. const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {
  18488. var _this$tracks$type5;
  18489. return type && !((_this$tracks$type5 = this.tracks[type]) != null && _this$tracks$type5.ended);
  18490. });
  18491. if (allTracksEnding) {
  18492. if (allowEndOfStream) {
  18493. this.log(`Queueing EOS`);
  18494. this.blockUntilOpen(() => {
  18495. this.tracksEnded();
  18496. const {
  18497. mediaSource
  18498. } = this;
  18499. if (!mediaSource || mediaSource.readyState !== 'open') {
  18500. if (mediaSource) {
  18501. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  18502. }
  18503. return;
  18504. }
  18505. this.log(`Calling mediaSource.endOfStream()`);
  18506. // Allow this to throw and be caught by the enqueueing function
  18507. mediaSource.endOfStream();
  18508. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  18509. });
  18510. } else {
  18511. this.tracksEnded();
  18512. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  18513. }
  18514. }
  18515. }
  18516. tracksEnded() {
  18517. this.sourceBuffers.forEach(([type]) => {
  18518. if (type !== null) {
  18519. const track = this.tracks[type];
  18520. if (track) {
  18521. track.ending = false;
  18522. }
  18523. }
  18524. });
  18525. }
  18526. onLevelUpdated(event, {
  18527. details
  18528. }) {
  18529. if (!details.fragments.length) {
  18530. return;
  18531. }
  18532. this.details = details;
  18533. this.updateDuration();
  18534. }
  18535. updateDuration() {
  18536. this.blockUntilOpen(() => {
  18537. const durationAndRange = this.getDurationAndRange();
  18538. if (!durationAndRange) {
  18539. return;
  18540. }
  18541. this.updateMediaSource(durationAndRange);
  18542. });
  18543. }
  18544. onError(event, data) {
  18545. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  18546. var _data$errorAction;
  18547. const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  18548. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  18549. this.resetAppendErrors();
  18550. }
  18551. }
  18552. }
  18553. resetAppendErrors() {
  18554. this.appendErrors = {
  18555. audio: 0,
  18556. video: 0,
  18557. audiovideo: 0
  18558. };
  18559. }
  18560. trimBuffers() {
  18561. const {
  18562. hls,
  18563. details,
  18564. media
  18565. } = this;
  18566. if (!media || details === null) {
  18567. return;
  18568. }
  18569. if (!this.sourceBufferCount) {
  18570. return;
  18571. }
  18572. const config = hls.config;
  18573. const currentTime = media.currentTime;
  18574. const targetDuration = details.levelTargetDuration;
  18575. // Support for deprecated liveBackBufferLength
  18576. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  18577. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  18578. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  18579. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  18580. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  18581. }
  18582. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  18583. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  18584. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  18585. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  18586. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  18587. }
  18588. }
  18589. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  18590. this.sourceBuffers.forEach(([type, sb]) => {
  18591. if (sb) {
  18592. const buffered = BufferHelper.getBuffered(sb);
  18593. // when target buffer start exceeds actual buffer start
  18594. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  18595. var _this$details;
  18596. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  18597. bufferEnd: targetBackBufferPosition
  18598. });
  18599. // Support for deprecated event:
  18600. const track = this.tracks[type];
  18601. if ((_this$details = this.details) != null && _this$details.live) {
  18602. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  18603. bufferEnd: targetBackBufferPosition
  18604. });
  18605. } else if (track != null && track.ended) {
  18606. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  18607. return;
  18608. }
  18609. this.hls.trigger(Events.BUFFER_FLUSHING, {
  18610. startOffset: 0,
  18611. endOffset: targetBackBufferPosition,
  18612. type
  18613. });
  18614. }
  18615. }
  18616. });
  18617. }
  18618. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  18619. this.sourceBuffers.forEach(([type, sb]) => {
  18620. if (sb) {
  18621. const buffered = BufferHelper.getBuffered(sb);
  18622. const numBufferedRanges = buffered.length;
  18623. // The buffer is either empty or contiguous
  18624. if (numBufferedRanges < 2) {
  18625. return;
  18626. }
  18627. const bufferStart = buffered.start(numBufferedRanges - 1);
  18628. const bufferEnd = buffered.end(numBufferedRanges - 1);
  18629. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  18630. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  18631. return;
  18632. }
  18633. this.hls.trigger(Events.BUFFER_FLUSHING, {
  18634. startOffset: bufferStart,
  18635. endOffset: Infinity,
  18636. type
  18637. });
  18638. }
  18639. });
  18640. }
  18641. /**
  18642. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  18643. * 'liveDurationInfinity` is set to `true`
  18644. * More details: https://github.com/video-dev/hls.js/issues/355
  18645. */
  18646. getDurationAndRange() {
  18647. var _this$overrides2;
  18648. const {
  18649. details,
  18650. mediaSource
  18651. } = this;
  18652. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== 'open') {
  18653. return null;
  18654. }
  18655. const playlistEnd = details.edge;
  18656. if (details.live && this.hls.config.liveDurationInfinity) {
  18657. const len = details.fragments.length;
  18658. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  18659. const start = Math.max(0, details.fragmentStart);
  18660. const end = Math.max(start, playlistEnd);
  18661. return {
  18662. duration: Infinity,
  18663. start,
  18664. end
  18665. };
  18666. }
  18667. return {
  18668. duration: Infinity
  18669. };
  18670. }
  18671. const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  18672. if (overrideDuration) {
  18673. if (!isFiniteNumber(overrideDuration)) {
  18674. return null;
  18675. }
  18676. return {
  18677. duration: overrideDuration
  18678. };
  18679. }
  18680. const mediaDuration = this.media.duration;
  18681. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  18682. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  18683. return {
  18684. duration: playlistEnd
  18685. };
  18686. }
  18687. return null;
  18688. }
  18689. updateMediaSource({
  18690. duration,
  18691. start,
  18692. end
  18693. }) {
  18694. const mediaSource = this.mediaSource;
  18695. if (!this.media || !mediaSource || mediaSource.readyState !== 'open') {
  18696. return;
  18697. }
  18698. if (mediaSource.duration !== duration) {
  18699. if (isFiniteNumber(duration)) {
  18700. this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);
  18701. }
  18702. mediaSource.duration = duration;
  18703. }
  18704. if (start !== undefined && end !== undefined) {
  18705. this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  18706. mediaSource.setLiveSeekableRange(start, end);
  18707. }
  18708. }
  18709. get tracksReady() {
  18710. const pendingTrackCount = this.pendingTrackCount;
  18711. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  18712. }
  18713. checkPendingTracks() {
  18714. const {
  18715. bufferCodecEventsTotal,
  18716. pendingTrackCount,
  18717. tracks
  18718. } = this;
  18719. this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);
  18720. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  18721. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  18722. // data has been appended to existing ones.
  18723. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  18724. if (this.tracksReady) {
  18725. var _this$transferData4;
  18726. const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;
  18727. if (transferredTracks && Object.keys(transferredTracks).length) {
  18728. this.attachTransferred();
  18729. } else {
  18730. // ok, let's create them now !
  18731. this.createSourceBuffers();
  18732. }
  18733. }
  18734. }
  18735. bufferCreated() {
  18736. if (this.sourceBufferCount) {
  18737. const tracks = {};
  18738. this.sourceBuffers.forEach(([type, buffer]) => {
  18739. if (type) {
  18740. const track = this.tracks[type];
  18741. tracks[type] = {
  18742. buffer,
  18743. container: track.container,
  18744. codec: track.codec,
  18745. supplemental: track.supplemental,
  18746. levelCodec: track.levelCodec,
  18747. id: track.id,
  18748. metadata: track.metadata
  18749. };
  18750. }
  18751. });
  18752. this.hls.trigger(Events.BUFFER_CREATED, {
  18753. tracks
  18754. });
  18755. this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);
  18756. this.sourceBuffers.forEach(([type]) => {
  18757. this.executeNext(type);
  18758. });
  18759. } else {
  18760. const error = new Error('could not create source buffer for media codec(s)');
  18761. this.hls.trigger(Events.ERROR, {
  18762. type: ErrorTypes.MEDIA_ERROR,
  18763. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  18764. fatal: true,
  18765. error,
  18766. reason: error.message
  18767. });
  18768. }
  18769. }
  18770. createSourceBuffers() {
  18771. const {
  18772. tracks,
  18773. sourceBuffers,
  18774. mediaSource
  18775. } = this;
  18776. if (!mediaSource) {
  18777. throw new Error('createSourceBuffers called when mediaSource was null');
  18778. }
  18779. for (const trackName in tracks) {
  18780. const type = trackName;
  18781. const track = tracks[type];
  18782. if (this.isPending(track)) {
  18783. const codec = this.getTrackCodec(track, type);
  18784. const mimeType = `${track.container};codecs=${codec}`;
  18785. track.codec = codec;
  18786. this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? ' Queued' : ''} ${stringify(track)}`);
  18787. try {
  18788. const sb = mediaSource.addSourceBuffer(mimeType);
  18789. const sbIndex = sourceBufferNameToIndex(type);
  18790. const sbTuple = [type, sb];
  18791. sourceBuffers[sbIndex] = sbTuple;
  18792. track.buffer = sb;
  18793. } catch (error) {
  18794. var _this$operationQueue;
  18795. this.error(`error while trying to add sourceBuffer: ${error.message}`);
  18796. // remove init segment from queue and delete track info
  18797. this.shiftAndExecuteNext(type);
  18798. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  18799. delete this.tracks[type];
  18800. this.hls.trigger(Events.ERROR, {
  18801. type: ErrorTypes.MEDIA_ERROR,
  18802. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  18803. fatal: false,
  18804. error,
  18805. sourceBufferName: type,
  18806. mimeType: mimeType,
  18807. parent: track.id
  18808. });
  18809. return;
  18810. }
  18811. this.trackSourceBuffer(type, track);
  18812. }
  18813. }
  18814. this.bufferCreated();
  18815. }
  18816. getTrackCodec(track, trackName) {
  18817. // Use supplemental video codec when supported when adding SourceBuffer (#5558)
  18818. const supplementalCodec = track.supplemental;
  18819. let trackCodec = track.codec;
  18820. if (supplementalCodec && (trackName === 'video' || trackName === 'audiovideo') && areCodecsMediaSourceSupported(supplementalCodec, 'video')) {
  18821. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  18822. }
  18823. const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  18824. if (codec) {
  18825. if (trackName.slice(0, 5) === 'audio') {
  18826. return getCodecCompatibleName(codec, this.appendSource);
  18827. }
  18828. return codec;
  18829. }
  18830. return '';
  18831. }
  18832. trackSourceBuffer(type, track) {
  18833. const buffer = track.buffer;
  18834. if (!buffer) {
  18835. return;
  18836. }
  18837. const codec = this.getTrackCodec(track, type);
  18838. this.tracks[type] = {
  18839. buffer,
  18840. codec,
  18841. container: track.container,
  18842. levelCodec: track.levelCodec,
  18843. supplemental: track.supplemental,
  18844. metadata: track.metadata,
  18845. id: track.id,
  18846. listeners: []
  18847. };
  18848. this.removeBufferListeners(type);
  18849. this.addBufferListener(type, 'updatestart', this.onSBUpdateStart);
  18850. this.addBufferListener(type, 'updateend', this.onSBUpdateEnd);
  18851. this.addBufferListener(type, 'error', this.onSBUpdateError);
  18852. // ManagedSourceBuffer bufferedchange event
  18853. if (this.appendSource) {
  18854. this.addBufferListener(type, 'bufferedchange', (type, event) => {
  18855. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  18856. const removedRanges = event.removedRanges;
  18857. if (removedRanges != null && removedRanges.length) {
  18858. this.hls.trigger(Events.BUFFER_FLUSHED, {
  18859. type: type
  18860. });
  18861. }
  18862. });
  18863. }
  18864. }
  18865. get mediaSrc() {
  18866. var _this$media2, _this$media2$querySel;
  18867. const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, 'source')) || this.media;
  18868. return media == null ? void 0 : media.src;
  18869. }
  18870. onSBUpdateStart(type) {
  18871. const operation = this.currentOp(type);
  18872. if (!operation) {
  18873. return;
  18874. }
  18875. operation.onStart();
  18876. }
  18877. onSBUpdateEnd(type) {
  18878. var _this$mediaSource4;
  18879. if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === 'closed') {
  18880. this.resetBuffer(type);
  18881. return;
  18882. }
  18883. const operation = this.currentOp(type);
  18884. if (!operation) {
  18885. return;
  18886. }
  18887. operation.onComplete();
  18888. this.shiftAndExecuteNext(type);
  18889. }
  18890. onSBUpdateError(type, event) {
  18891. var _this$mediaSource5;
  18892. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);
  18893. this.error(`${error}`, event);
  18894. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  18895. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  18896. this.hls.trigger(Events.ERROR, {
  18897. type: ErrorTypes.MEDIA_ERROR,
  18898. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  18899. sourceBufferName: type,
  18900. error,
  18901. fatal: false
  18902. });
  18903. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  18904. const operation = this.currentOp(type);
  18905. if (operation) {
  18906. operation.onError(error);
  18907. }
  18908. }
  18909. updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  18910. const delta = timestampOffset - sb.timestampOffset;
  18911. if (Math.abs(delta) >= tolerance) {
  18912. this.log(`Updating ${type} SourceBuffer timestampOffset to ${timestampOffset} (sn: ${sn} cc: ${cc})`);
  18913. sb.timestampOffset = timestampOffset;
  18914. }
  18915. }
  18916. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  18917. removeExecutor(type, startOffset, endOffset) {
  18918. const {
  18919. media,
  18920. mediaSource
  18921. } = this;
  18922. const track = this.tracks[type];
  18923. const sb = track == null ? void 0 : track.buffer;
  18924. if (!media || !mediaSource || !sb) {
  18925. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  18926. this.shiftAndExecuteNext(type);
  18927. return;
  18928. }
  18929. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  18930. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  18931. const removeStart = Math.max(0, startOffset);
  18932. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  18933. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  18934. track.ended = false;
  18935. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  18936. sb.remove(removeStart, removeEnd);
  18937. } else {
  18938. // Cycle the queue
  18939. this.shiftAndExecuteNext(type);
  18940. }
  18941. }
  18942. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  18943. appendExecutor(data, type) {
  18944. const track = this.tracks[type];
  18945. const sb = track == null ? void 0 : track.buffer;
  18946. if (!sb) {
  18947. throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  18948. }
  18949. track.ending = false;
  18950. track.ended = false;
  18951. sb.appendBuffer(data);
  18952. }
  18953. blockUntilOpen(callback) {
  18954. if (this.isUpdating() || this.isQueued()) {
  18955. this.blockBuffers(callback).catch(error => {
  18956. this.warn(`SourceBuffer blocked callback ${error}`);
  18957. this.stepOperationQueue(this.sourceBufferTypes);
  18958. });
  18959. } else {
  18960. try {
  18961. callback();
  18962. } catch (error) {
  18963. this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);
  18964. }
  18965. }
  18966. }
  18967. isUpdating() {
  18968. return this.sourceBuffers.some(([type, sb]) => type && sb.updating);
  18969. }
  18970. isQueued() {
  18971. return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));
  18972. }
  18973. isPending(track) {
  18974. return !!track && !track.buffer;
  18975. }
  18976. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  18977. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  18978. // upon completion, since we already do it here
  18979. blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {
  18980. if (!bufferNames.length) {
  18981. this.log('Blocking operation requested, but no SourceBuffers exist');
  18982. return Promise.resolve().then(onUnblocked);
  18983. }
  18984. const {
  18985. operationQueue
  18986. } = this;
  18987. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  18988. const blockingOperations = bufferNames.map(type => this.appendBlocker(type));
  18989. const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  18990. if (audioBlocked) {
  18991. this.unblockAudio();
  18992. }
  18993. return Promise.all(blockingOperations).then(result => {
  18994. if (operationQueue !== this.operationQueue) {
  18995. return;
  18996. }
  18997. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  18998. onUnblocked();
  18999. this.stepOperationQueue(this.sourceBufferTypes);
  19000. });
  19001. }
  19002. stepOperationQueue(bufferNames) {
  19003. bufferNames.forEach(type => {
  19004. var _this$tracks$type6;
  19005. const sb = (_this$tracks$type6 = this.tracks[type]) == null ? void 0 : _this$tracks$type6.buffer;
  19006. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  19007. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  19008. // While this is a workaround, it's probably useful to have around
  19009. if (!sb || sb.updating) {
  19010. return;
  19011. }
  19012. this.shiftAndExecuteNext(type);
  19013. });
  19014. }
  19015. append(operation, type, pending) {
  19016. if (this.operationQueue) {
  19017. this.operationQueue.append(operation, type, pending);
  19018. }
  19019. }
  19020. appendBlocker(type) {
  19021. if (this.operationQueue) {
  19022. return this.operationQueue.appendBlocker(type);
  19023. }
  19024. }
  19025. currentOp(type) {
  19026. if (this.operationQueue) {
  19027. return this.operationQueue.current(type);
  19028. }
  19029. return null;
  19030. }
  19031. executeNext(type) {
  19032. if (type && this.operationQueue) {
  19033. this.operationQueue.executeNext(type);
  19034. }
  19035. }
  19036. shiftAndExecuteNext(type) {
  19037. if (this.operationQueue) {
  19038. this.operationQueue.shiftAndExecuteNext(type);
  19039. }
  19040. }
  19041. get pendingTrackCount() {
  19042. return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);
  19043. }
  19044. get sourceBufferCount() {
  19045. return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);
  19046. }
  19047. get sourceBufferTypes() {
  19048. return this.sourceBuffers.map(([type]) => type).filter(type => !!type);
  19049. }
  19050. addBufferListener(type, event, fn) {
  19051. const track = this.tracks[type];
  19052. if (!track) {
  19053. return;
  19054. }
  19055. const buffer = track.buffer;
  19056. if (!buffer) {
  19057. return;
  19058. }
  19059. const listener = fn.bind(this, type);
  19060. track.listeners.push({
  19061. event,
  19062. listener
  19063. });
  19064. buffer.addEventListener(event, listener);
  19065. }
  19066. removeBufferListeners(type) {
  19067. const track = this.tracks[type];
  19068. if (!track) {
  19069. return;
  19070. }
  19071. const buffer = track.buffer;
  19072. if (!buffer) {
  19073. return;
  19074. }
  19075. track.listeners.forEach(l => {
  19076. buffer.removeEventListener(l.event, l.listener);
  19077. });
  19078. track.listeners.length = 0;
  19079. }
  19080. }
  19081. function removeSourceChildren(node) {
  19082. const sourceChildren = node.querySelectorAll('source');
  19083. [].slice.call(sourceChildren).forEach(source => {
  19084. node.removeChild(source);
  19085. });
  19086. }
  19087. function addSource(media, url) {
  19088. const source = self.document.createElement('source');
  19089. source.type = 'video/mp4';
  19090. source.src = url;
  19091. media.appendChild(source);
  19092. }
  19093. function sourceBufferNameToIndex(type) {
  19094. return type === 'audio' ? 1 : 0;
  19095. }
  19096. class CapLevelController {
  19097. constructor(hls) {
  19098. this.hls = void 0;
  19099. this.autoLevelCapping = void 0;
  19100. this.firstLevel = void 0;
  19101. this.media = void 0;
  19102. this.restrictedLevels = void 0;
  19103. this.timer = void 0;
  19104. this.clientRect = void 0;
  19105. this.streamController = void 0;
  19106. this.hls = hls;
  19107. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19108. this.firstLevel = -1;
  19109. this.media = null;
  19110. this.restrictedLevels = [];
  19111. this.timer = undefined;
  19112. this.clientRect = null;
  19113. this.registerListeners();
  19114. }
  19115. setStreamController(streamController) {
  19116. this.streamController = streamController;
  19117. }
  19118. destroy() {
  19119. if (this.hls) {
  19120. this.unregisterListener();
  19121. }
  19122. if (this.timer) {
  19123. this.stopCapping();
  19124. }
  19125. this.media = null;
  19126. this.clientRect = null;
  19127. // @ts-ignore
  19128. this.hls = this.streamController = null;
  19129. }
  19130. registerListeners() {
  19131. const {
  19132. hls
  19133. } = this;
  19134. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  19135. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19136. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19137. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19138. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  19139. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19140. }
  19141. unregisterListener() {
  19142. const {
  19143. hls
  19144. } = this;
  19145. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  19146. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19147. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19148. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19149. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  19150. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19151. }
  19152. onFpsDropLevelCapping(event, data) {
  19153. // Don't add a restricted level more than once
  19154. const level = this.hls.levels[data.droppedLevel];
  19155. if (this.isLevelAllowed(level)) {
  19156. this.restrictedLevels.push({
  19157. bitrate: level.bitrate,
  19158. height: level.height,
  19159. width: level.width
  19160. });
  19161. }
  19162. }
  19163. onMediaAttaching(event, data) {
  19164. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  19165. this.clientRect = null;
  19166. if (this.timer && this.hls.levels.length) {
  19167. this.detectPlayerSize();
  19168. }
  19169. }
  19170. onManifestParsed(event, data) {
  19171. const hls = this.hls;
  19172. this.restrictedLevels = [];
  19173. this.firstLevel = data.firstLevel;
  19174. if (hls.config.capLevelToPlayerSize && data.video) {
  19175. // Start capping immediately if the manifest has signaled video codecs
  19176. this.startCapping();
  19177. }
  19178. }
  19179. onLevelsUpdated(event, data) {
  19180. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  19181. this.detectPlayerSize();
  19182. }
  19183. }
  19184. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  19185. // to the first level
  19186. onBufferCodecs(event, data) {
  19187. const hls = this.hls;
  19188. if (hls.config.capLevelToPlayerSize && data.video) {
  19189. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  19190. this.startCapping();
  19191. }
  19192. }
  19193. onMediaDetaching() {
  19194. this.stopCapping();
  19195. this.media = null;
  19196. }
  19197. detectPlayerSize() {
  19198. if (this.media) {
  19199. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  19200. this.clientRect = null;
  19201. return;
  19202. }
  19203. const levels = this.hls.levels;
  19204. if (levels.length) {
  19205. const hls = this.hls;
  19206. const maxLevel = this.getMaxLevel(levels.length - 1);
  19207. if (maxLevel !== this.autoLevelCapping) {
  19208. hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  19209. }
  19210. hls.autoLevelCapping = maxLevel;
  19211. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  19212. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  19213. // usually happen when the user go to the fullscreen mode.
  19214. this.streamController.nextLevelSwitch();
  19215. }
  19216. this.autoLevelCapping = hls.autoLevelCapping;
  19217. }
  19218. }
  19219. }
  19220. /*
  19221. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  19222. */
  19223. getMaxLevel(capLevelIndex) {
  19224. const levels = this.hls.levels;
  19225. if (!levels.length) {
  19226. return -1;
  19227. }
  19228. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  19229. this.clientRect = null;
  19230. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  19231. }
  19232. startCapping() {
  19233. if (this.timer) {
  19234. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  19235. return;
  19236. }
  19237. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19238. self.clearInterval(this.timer);
  19239. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  19240. this.detectPlayerSize();
  19241. }
  19242. stopCapping() {
  19243. this.restrictedLevels = [];
  19244. this.firstLevel = -1;
  19245. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19246. if (this.timer) {
  19247. self.clearInterval(this.timer);
  19248. this.timer = undefined;
  19249. }
  19250. }
  19251. getDimensions() {
  19252. if (this.clientRect) {
  19253. return this.clientRect;
  19254. }
  19255. const media = this.media;
  19256. const boundsRect = {
  19257. width: 0,
  19258. height: 0
  19259. };
  19260. if (media) {
  19261. const clientRect = media.getBoundingClientRect();
  19262. boundsRect.width = clientRect.width;
  19263. boundsRect.height = clientRect.height;
  19264. if (!boundsRect.width && !boundsRect.height) {
  19265. // When the media element has no width or height (equivalent to not being in the DOM),
  19266. // then use its width and height attributes (media.width, media.height)
  19267. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  19268. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  19269. }
  19270. }
  19271. this.clientRect = boundsRect;
  19272. return boundsRect;
  19273. }
  19274. get mediaWidth() {
  19275. return this.getDimensions().width * this.contentScaleFactor;
  19276. }
  19277. get mediaHeight() {
  19278. return this.getDimensions().height * this.contentScaleFactor;
  19279. }
  19280. get contentScaleFactor() {
  19281. let pixelRatio = 1;
  19282. if (!this.hls.config.ignoreDevicePixelRatio) {
  19283. try {
  19284. pixelRatio = self.devicePixelRatio;
  19285. } catch (e) {
  19286. /* no-op */
  19287. }
  19288. }
  19289. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  19290. }
  19291. isLevelAllowed(level) {
  19292. const restrictedLevels = this.restrictedLevels;
  19293. return !restrictedLevels.some(restrictedLevel => {
  19294. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  19295. });
  19296. }
  19297. static getMaxLevelByMediaSize(levels, width, height) {
  19298. if (!(levels != null && levels.length)) {
  19299. return -1;
  19300. }
  19301. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  19302. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  19303. const atGreatestBandwidth = (curLevel, nextLevel) => {
  19304. if (!nextLevel) {
  19305. return true;
  19306. }
  19307. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  19308. };
  19309. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  19310. // the max level
  19311. let maxLevelIndex = levels.length - 1;
  19312. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  19313. const squareSize = Math.max(width, height);
  19314. for (let i = 0; i < levels.length; i += 1) {
  19315. const level = levels[i];
  19316. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  19317. maxLevelIndex = i;
  19318. break;
  19319. }
  19320. }
  19321. return maxLevelIndex;
  19322. }
  19323. }
  19324. /**
  19325. * Common Media Object Type
  19326. *
  19327. * @internal
  19328. */
  19329. const CmObjectType = {
  19330. /**
  19331. * text file, such as a manifest or playlist
  19332. */
  19333. MANIFEST: 'm',
  19334. /**
  19335. * audio only
  19336. */
  19337. AUDIO: 'a',
  19338. /**
  19339. * video only
  19340. */
  19341. VIDEO: 'v',
  19342. /**
  19343. * muxed audio and video
  19344. */
  19345. MUXED: 'av',
  19346. /**
  19347. * init segment
  19348. */
  19349. INIT: 'i',
  19350. /**
  19351. * caption or subtitle
  19352. */
  19353. CAPTION: 'c',
  19354. /**
  19355. * ISOBMFF timed text track
  19356. */
  19357. TIMED_TEXT: 'tt',
  19358. /**
  19359. * cryptographic key, license or certificate.
  19360. */
  19361. KEY: 'k',
  19362. /**
  19363. * other
  19364. */
  19365. OTHER: 'o'
  19366. };
  19367. /**
  19368. * Common Media Client Data Object Type
  19369. *
  19370. * @group CMCD
  19371. *
  19372. * @beta
  19373. *
  19374. * @enum
  19375. */
  19376. const CmcdObjectType = CmObjectType;
  19377. /**
  19378. * Common Media Streaming Format
  19379. *
  19380. * @internal
  19381. */
  19382. const CmStreamingFormat = {
  19383. /**
  19384. * HTTP Live Streaming (HLS)
  19385. */
  19386. HLS: 'h'};
  19387. /**
  19388. * Common Media Client Data Streaming Format
  19389. *
  19390. * @group CMCD
  19391. *
  19392. * @enum
  19393. *
  19394. * @beta
  19395. */
  19396. const CmcdStreamingFormat = CmStreamingFormat;
  19397. /**
  19398. * CMCD object header name.
  19399. *
  19400. * @group CMCD
  19401. *
  19402. * @beta
  19403. */
  19404. const CMCD_OBJECT = 'CMCD-Object';
  19405. /**
  19406. * CMCD request header name.
  19407. *
  19408. * @group CMCD
  19409. *
  19410. * @beta
  19411. */
  19412. const CMCD_REQUEST = 'CMCD-Request';
  19413. /**
  19414. * CMCD session header name.
  19415. *
  19416. * @group CMCD
  19417. *
  19418. * @beta
  19419. */
  19420. const CMCD_SESSION = 'CMCD-Session';
  19421. /**
  19422. * CMCD status header name.
  19423. *
  19424. * @group CMCD
  19425. *
  19426. * @beta
  19427. */
  19428. const CMCD_STATUS = 'CMCD-Status';
  19429. /**
  19430. * CMCD header fields.
  19431. *
  19432. * @group CMCD
  19433. *
  19434. * @enum
  19435. *
  19436. * @beta
  19437. */
  19438. const CmcdHeaderField = {
  19439. /**
  19440. * keys whose values vary with the object being requested.
  19441. */
  19442. OBJECT: CMCD_OBJECT,
  19443. /**
  19444. * keys whose values vary with each request.
  19445. */
  19446. REQUEST: CMCD_REQUEST,
  19447. /**
  19448. * keys whose values are expected to be invariant over the life of the session.
  19449. */
  19450. SESSION: CMCD_SESSION,
  19451. /**
  19452. * keys whose values do not vary with every request or object.
  19453. */
  19454. STATUS: CMCD_STATUS
  19455. };
  19456. /**
  19457. * The map of CMCD header fields to official CMCD keys.
  19458. *
  19459. * @internal
  19460. *
  19461. * @group CMCD
  19462. */
  19463. const CmcdHeaderMap = {
  19464. [CmcdHeaderField.OBJECT]: ['br', 'ab', 'd', 'ot', 'tb', 'tpb', 'lb', 'tab', 'lab', 'url'],
  19465. [CmcdHeaderField.REQUEST]: ['pb', 'bl', 'tbl', 'dl', 'ltc', 'mtp', 'nor', 'nrr', 'rc', 'sn', 'sta', 'su', 'ttfb', 'ttfbb', 'ttlb', 'cmsdd', 'cmsds', 'smrt', 'df', 'cs'],
  19466. [CmcdHeaderField.SESSION]: ['cid', 'pr', 'sf', 'sid', 'st', 'v', 'msd'],
  19467. [CmcdHeaderField.STATUS]: ['bs', 'bsd', 'cdn', 'rtp', 'bg', 'pt', 'ec', 'e']
  19468. };
  19469. /**
  19470. * Structured Field Item
  19471. *
  19472. * @group Structured Field
  19473. *
  19474. * @beta
  19475. */
  19476. class SfItem {
  19477. constructor(value, params) {
  19478. if (Array.isArray(value)) {
  19479. value = value.map(v => v instanceof SfItem ? v : new SfItem(v));
  19480. }
  19481. this.value = value;
  19482. this.params = params;
  19483. }
  19484. }
  19485. const DICT = 'Dict';
  19486. function format(value) {
  19487. if (Array.isArray(value)) {
  19488. return JSON.stringify(value);
  19489. }
  19490. if (value instanceof Map) {
  19491. return 'Map{}';
  19492. }
  19493. if (value instanceof Set) {
  19494. return 'Set{}';
  19495. }
  19496. if (typeof value === 'object') {
  19497. return JSON.stringify(value);
  19498. }
  19499. return String(value);
  19500. }
  19501. function throwError(action, src, type, cause) {
  19502. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  19503. cause
  19504. });
  19505. }
  19506. function serializeError(src, type, cause) {
  19507. return throwError('serialize', src, type, cause);
  19508. }
  19509. /**
  19510. * A class to represent structured field tokens when `Symbol` is not available.
  19511. *
  19512. * @group Structured Field
  19513. *
  19514. * @beta
  19515. */
  19516. class SfToken {
  19517. constructor(description) {
  19518. this.description = description;
  19519. }
  19520. }
  19521. const BARE_ITEM = 'Bare Item';
  19522. const BOOLEAN = 'Boolean';
  19523. // 4.1.9. Serializing a Boolean
  19524. //
  19525. // Given a Boolean as input_boolean, return an ASCII string suitable for
  19526. // use in a HTTP field value.
  19527. //
  19528. // 1. If input_boolean is not a boolean, fail serialization.
  19529. //
  19530. // 2. Let output be an empty string.
  19531. //
  19532. // 3. Append "?" to output.
  19533. //
  19534. // 4. If input_boolean is true, append "1" to output.
  19535. //
  19536. // 5. If input_boolean is false, append "0" to output.
  19537. //
  19538. // 6. Return output.
  19539. function serializeBoolean(value) {
  19540. if (typeof value !== 'boolean') {
  19541. throw serializeError(value, BOOLEAN);
  19542. }
  19543. return value ? '?1' : '?0';
  19544. }
  19545. /**
  19546. * Encodes binary data to base64
  19547. *
  19548. * @param binary - The binary data to encode
  19549. * @returns The base64 encoded string
  19550. *
  19551. * @group Utils
  19552. *
  19553. * @beta
  19554. */
  19555. function encodeBase64(binary) {
  19556. return btoa(String.fromCharCode(...binary));
  19557. }
  19558. const BYTES = 'Byte Sequence';
  19559. // 4.1.8. Serializing a Byte Sequence
  19560. //
  19561. // Given a Byte Sequence as input_bytes, return an ASCII string suitable
  19562. // for use in a HTTP field value.
  19563. //
  19564. // 1. If input_bytes is not a sequence of bytes, fail serialization.
  19565. //
  19566. // 2. Let output be an empty string.
  19567. //
  19568. // 3. Append ":" to output.
  19569. //
  19570. // 4. Append the result of base64-encoding input_bytes as per
  19571. // [RFC4648], Section 4, taking account of the requirements below.
  19572. //
  19573. // 5. Append ":" to output.
  19574. //
  19575. // 6. Return output.
  19576. //
  19577. // The encoded data is required to be padded with "=", as per [RFC4648],
  19578. // Section 3.2.
  19579. //
  19580. // Likewise, encoded data SHOULD have pad bits set to zero, as per
  19581. // [RFC4648], Section 3.5, unless it is not possible to do so due to
  19582. // implementation constraints.
  19583. function serializeByteSequence(value) {
  19584. if (ArrayBuffer.isView(value) === false) {
  19585. throw serializeError(value, BYTES);
  19586. }
  19587. return `:${encodeBase64(value)}:`;
  19588. }
  19589. const INTEGER = 'Integer';
  19590. function isInvalidInt(value) {
  19591. return value < -999999999999999 || 999999999999999 < value;
  19592. }
  19593. // 4.1.4. Serializing an Integer
  19594. //
  19595. // Given an Integer as input_integer, return an ASCII string suitable
  19596. // for use in a HTTP field value.
  19597. //
  19598. // 1. If input_integer is not an integer in the range of
  19599. // -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
  19600. // serialization.
  19601. //
  19602. // 2. Let output be an empty string.
  19603. //
  19604. // 3. If input_integer is less than (but not equal to) 0, append "-" to
  19605. // output.
  19606. //
  19607. // 4. Append input_integer's numeric value represented in base 10 using
  19608. // only decimal digits to output.
  19609. //
  19610. // 5. Return output.
  19611. function serializeInteger(value) {
  19612. if (isInvalidInt(value)) {
  19613. throw serializeError(value, INTEGER);
  19614. }
  19615. return value.toString();
  19616. }
  19617. // 4.1.10. Serializing a Date
  19618. //
  19619. // Given a Date as input_integer, return an ASCII string suitable for
  19620. // use in an HTTP field value.
  19621. // 1. Let output be "@".
  19622. // 2. Append to output the result of running Serializing an Integer
  19623. // with input_date (Section 4.1.4).
  19624. // 3. Return output.
  19625. function serializeDate(value) {
  19626. return `@${serializeInteger(value.getTime() / 1000)}`;
  19627. }
  19628. /**
  19629. * This implements the rounding procedure described in step 2 of the "Serializing a Decimal" specification.
  19630. * This rounding style is known as "even rounding", "banker's rounding", or "commercial rounding".
  19631. *
  19632. * @param value - The value to round
  19633. * @param precision - The number of decimal places to round to
  19634. * @returns The rounded value
  19635. *
  19636. * @group Utils
  19637. *
  19638. * @beta
  19639. */
  19640. function roundToEven(value, precision) {
  19641. if (value < 0) {
  19642. return -roundToEven(-value, precision);
  19643. }
  19644. const decimalShift = Math.pow(10, precision);
  19645. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  19646. if (isEquidistant) {
  19647. // If the tail of the decimal place is 'equidistant' we round to the nearest even value
  19648. const flooredValue = Math.floor(value * decimalShift);
  19649. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  19650. } else {
  19651. // Otherwise, proceed as normal
  19652. return Math.round(value * decimalShift) / decimalShift;
  19653. }
  19654. }
  19655. const DECIMAL = 'Decimal';
  19656. // 4.1.5. Serializing a Decimal
  19657. //
  19658. // Given a decimal number as input_decimal, return an ASCII string
  19659. // suitable for use in a HTTP field value.
  19660. //
  19661. // 1. If input_decimal is not a decimal number, fail serialization.
  19662. //
  19663. // 2. If input_decimal has more than three significant digits to the
  19664. // right of the decimal point, round it to three decimal places,
  19665. // rounding the final digit to the nearest value, or to the even
  19666. // value if it is equidistant.
  19667. //
  19668. // 3. If input_decimal has more than 12 significant digits to the left
  19669. // of the decimal point after rounding, fail serialization.
  19670. //
  19671. // 4. Let output be an empty string.
  19672. //
  19673. // 5. If input_decimal is less than (but not equal to) 0, append "-"
  19674. // to output.
  19675. //
  19676. // 6. Append input_decimal's integer component represented in base 10
  19677. // (using only decimal digits) to output; if it is zero, append
  19678. // "0".
  19679. //
  19680. // 7. Append "." to output.
  19681. //
  19682. // 8. If input_decimal's fractional component is zero, append "0" to
  19683. // output.
  19684. //
  19685. // 9. Otherwise, append the significant digits of input_decimal's
  19686. // fractional component represented in base 10 (using only decimal
  19687. // digits) to output.
  19688. //
  19689. // 10. Return output.
  19690. function serializeDecimal(value) {
  19691. const roundedValue = roundToEven(value, 3); // round to 3 decimal places
  19692. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  19693. throw serializeError(value, DECIMAL);
  19694. }
  19695. const stringValue = roundedValue.toString();
  19696. return stringValue.includes('.') ? stringValue : `${stringValue}.0`;
  19697. }
  19698. const STRING = 'String';
  19699. const STRING_REGEX = /[\x00-\x1f\x7f]+/;
  19700. // 4.1.6. Serializing a String
  19701. //
  19702. // Given a String as input_string, return an ASCII string suitable for
  19703. // use in a HTTP field value.
  19704. //
  19705. // 1. Convert input_string into a sequence of ASCII characters; if
  19706. // conversion fails, fail serialization.
  19707. //
  19708. // 2. If input_string contains characters in the range %x00-1f or %x7f
  19709. // (i.e., not in VCHAR or SP), fail serialization.
  19710. //
  19711. // 3. Let output be the string DQUOTE.
  19712. //
  19713. // 4. For each character char in input_string:
  19714. //
  19715. // 1. If char is "\" or DQUOTE:
  19716. //
  19717. // 1. Append "\" to output.
  19718. //
  19719. // 2. Append char to output.
  19720. //
  19721. // 5. Append DQUOTE to output.
  19722. //
  19723. // 6. Return output.
  19724. function serializeString(value) {
  19725. if (STRING_REGEX.test(value)) {
  19726. throw serializeError(value, STRING);
  19727. }
  19728. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  19729. }
  19730. /**
  19731. * Converts a symbol to a string.
  19732. *
  19733. * @param symbol - The symbol to convert.
  19734. *
  19735. * @returns The string representation of the symbol.
  19736. *
  19737. * @internal
  19738. */
  19739. function symbolToStr(symbol) {
  19740. return symbol.description || symbol.toString().slice(7, -1);
  19741. }
  19742. const TOKEN = 'Token';
  19743. function serializeToken(token) {
  19744. const value = symbolToStr(token);
  19745. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  19746. throw serializeError(value, TOKEN);
  19747. }
  19748. return value;
  19749. }
  19750. // 4.1.3.1. Serializing a Bare Item
  19751. //
  19752. // Given an Item as input_item, return an ASCII string suitable for use
  19753. // in a HTTP field value.
  19754. //
  19755. // 1. If input_item is an Integer, return the result of running
  19756. // Serializing an Integer (Section 4.1.4) with input_item.
  19757. //
  19758. // 2. If input_item is a Decimal, return the result of running
  19759. // Serializing a Decimal (Section 4.1.5) with input_item.
  19760. //
  19761. // 3. If input_item is a String, return the result of running
  19762. // Serializing a String (Section 4.1.6) with input_item.
  19763. //
  19764. // 4. If input_item is a Token, return the result of running
  19765. // Serializing a Token (Section 4.1.7) with input_item.
  19766. //
  19767. // 5. If input_item is a Boolean, return the result of running
  19768. // Serializing a Boolean (Section 4.1.9) with input_item.
  19769. //
  19770. // 6. If input_item is a Byte Sequence, return the result of running
  19771. // Serializing a Byte Sequence (Section 4.1.8) with input_item.
  19772. //
  19773. // 7. If input_item is a Date, return the result of running Serializing
  19774. // a Date (Section 4.1.10) with input_item.
  19775. //
  19776. // 8. Otherwise, fail serialization.
  19777. function serializeBareItem(value) {
  19778. switch (typeof value) {
  19779. case 'number':
  19780. if (!isFiniteNumber(value)) {
  19781. throw serializeError(value, BARE_ITEM);
  19782. }
  19783. if (Number.isInteger(value)) {
  19784. return serializeInteger(value);
  19785. }
  19786. return serializeDecimal(value);
  19787. case 'string':
  19788. return serializeString(value);
  19789. case 'symbol':
  19790. return serializeToken(value);
  19791. case 'boolean':
  19792. return serializeBoolean(value);
  19793. case 'object':
  19794. if (value instanceof Date) {
  19795. return serializeDate(value);
  19796. }
  19797. if (value instanceof Uint8Array) {
  19798. return serializeByteSequence(value);
  19799. }
  19800. if (value instanceof SfToken) {
  19801. return serializeToken(value);
  19802. }
  19803. default:
  19804. // fail
  19805. throw serializeError(value, BARE_ITEM);
  19806. }
  19807. }
  19808. const KEY = 'Key';
  19809. // 4.1.1.3. Serializing a Key
  19810. //
  19811. // Given a key as input_key, return an ASCII string suitable for use in
  19812. // a HTTP field value.
  19813. //
  19814. // 1. Convert input_key into a sequence of ASCII characters; if
  19815. // conversion fails, fail serialization.
  19816. //
  19817. // 2. If input_key contains characters not in lcalpha, DIGIT, "_", "-",
  19818. // ".", or "*" fail serialization.
  19819. //
  19820. // 3. If the first character of input_key is not lcalpha or "*", fail
  19821. // serialization.
  19822. //
  19823. // 4. Let output be an empty string.
  19824. //
  19825. // 5. Append input_key to output.
  19826. //
  19827. // 6. Return output.
  19828. function serializeKey(value) {
  19829. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  19830. throw serializeError(value, KEY);
  19831. }
  19832. return value;
  19833. }
  19834. // 4.1.1.2. Serializing Parameters
  19835. //
  19836. // Given an ordered Dictionary as input_parameters (each member having a
  19837. // param_name and a param_value), return an ASCII string suitable for
  19838. // use in a HTTP field value.
  19839. //
  19840. // 1. Let output be an empty string.
  19841. //
  19842. // 2. For each param_name with a value of param_value in
  19843. // input_parameters:
  19844. //
  19845. // 1. Append ";" to output.
  19846. //
  19847. // 2. Append the result of running Serializing a Key
  19848. // (Section 4.1.1.3) with param_name to output.
  19849. //
  19850. // 3. If param_value is not Boolean true:
  19851. //
  19852. // 1. Append "=" to output.
  19853. //
  19854. // 2. Append the result of running Serializing a bare Item
  19855. // (Section 4.1.3.1) with param_value to output.
  19856. //
  19857. // 3. Return output.
  19858. function serializeParams(params) {
  19859. if (params == null) {
  19860. return '';
  19861. }
  19862. return Object.entries(params).map(([key, value]) => {
  19863. if (value === true) {
  19864. return `;${serializeKey(key)}`; // omit true
  19865. }
  19866. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  19867. }).join('');
  19868. }
  19869. // 4.1.3. Serializing an Item
  19870. //
  19871. // Given an Item as bare_item and Parameters as item_parameters, return
  19872. // an ASCII string suitable for use in a HTTP field value.
  19873. //
  19874. // 1. Let output be an empty string.
  19875. //
  19876. // 2. Append the result of running Serializing a Bare Item
  19877. // Section 4.1.3.1 with bare_item to output.
  19878. //
  19879. // 3. Append the result of running Serializing Parameters
  19880. // Section 4.1.1.2 with item_parameters to output.
  19881. //
  19882. // 4. Return output.
  19883. function serializeItem(value) {
  19884. if (value instanceof SfItem) {
  19885. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  19886. } else {
  19887. return serializeBareItem(value);
  19888. }
  19889. }
  19890. // 4.1.1.1. Serializing an Inner List
  19891. //
  19892. // Given an array of (member_value, parameters) tuples as inner_list,
  19893. // and parameters as list_parameters, return an ASCII string suitable
  19894. // for use in a HTTP field value.
  19895. //
  19896. // 1. Let output be the string "(".
  19897. //
  19898. // 2. For each (member_value, parameters) of inner_list:
  19899. //
  19900. // 1. Append the result of running Serializing an Item
  19901. // (Section 4.1.3) with (member_value, parameters) to output.
  19902. //
  19903. // 2. If more values remain in inner_list, append a single SP to
  19904. // output.
  19905. //
  19906. // 3. Append ")" to output.
  19907. //
  19908. // 4. Append the result of running Serializing Parameters
  19909. // (Section 4.1.1.2) with list_parameters to output.
  19910. //
  19911. // 5. Return output.
  19912. function serializeInnerList(value) {
  19913. return `(${value.value.map(serializeItem).join(' ')})${serializeParams(value.params)}`;
  19914. }
  19915. // 4.1.2. Serializing a Dictionary
  19916. //
  19917. // Given an ordered Dictionary as input_dictionary (each member having a
  19918. // member_name and a tuple value of (member_value, parameters)), return
  19919. // an ASCII string suitable for use in a HTTP field value.
  19920. //
  19921. // 1. Let output be an empty string.
  19922. //
  19923. // 2. For each member_name with a value of (member_value, parameters)
  19924. // in input_dictionary:
  19925. //
  19926. // 1. Append the result of running Serializing a Key
  19927. // (Section 4.1.1.3) with member's member_name to output.
  19928. //
  19929. // 2. If member_value is Boolean true:
  19930. //
  19931. // 1. Append the result of running Serializing Parameters
  19932. // (Section 4.1.1.2) with parameters to output.
  19933. //
  19934. // 3. Otherwise:
  19935. //
  19936. // 1. Append "=" to output.
  19937. //
  19938. // 2. If member_value is an array, append the result of running
  19939. // Serializing an Inner List (Section 4.1.1.1) with
  19940. // (member_value, parameters) to output.
  19941. //
  19942. // 3. Otherwise, append the result of running Serializing an
  19943. // Item (Section 4.1.3) with (member_value, parameters) to
  19944. // output.
  19945. //
  19946. // 4. If more members remain in input_dictionary:
  19947. //
  19948. // 1. Append "," to output.
  19949. //
  19950. // 2. Append a single SP to output.
  19951. //
  19952. // 3. Return output.
  19953. function serializeDict(dict, options = {
  19954. whitespace: true
  19955. }) {
  19956. if (typeof dict !== 'object') {
  19957. throw serializeError(dict, DICT);
  19958. }
  19959. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  19960. const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? ' ' : '';
  19961. return Array.from(entries).map(([key, item]) => {
  19962. if (item instanceof SfItem === false) {
  19963. item = new SfItem(item);
  19964. }
  19965. let output = serializeKey(key);
  19966. if (item.value === true) {
  19967. output += serializeParams(item.params);
  19968. } else {
  19969. output += '=';
  19970. if (Array.isArray(item.value)) {
  19971. output += serializeInnerList(item);
  19972. } else {
  19973. output += serializeItem(item);
  19974. }
  19975. }
  19976. return output;
  19977. }).join(`,${optionalWhiteSpace}`);
  19978. }
  19979. /**
  19980. * Encode an object into a structured field dictionary
  19981. *
  19982. * @param value - The structured field dictionary to encode
  19983. * @param options - Encoding options
  19984. *
  19985. * @returns The structured field string
  19986. *
  19987. * @group Structured Field
  19988. *
  19989. * @beta
  19990. */
  19991. function encodeSfDict(value, options) {
  19992. return serializeDict(value, options);
  19993. }
  19994. /**
  19995. * Checks if the given key is a token field.
  19996. *
  19997. * @param key - The key to check.
  19998. *
  19999. * @returns `true` if the key is a token field.
  20000. *
  20001. * @internal
  20002. */
  20003. function isTokenField(key) {
  20004. return ['ot', 'sf', 'st', 'e', 'sta'].includes(key);
  20005. }
  20006. /**
  20007. * Checks if the given value is valid
  20008. *
  20009. * @param value - The value to check.
  20010. *
  20011. * @returns `true` if the key is a value is valid.
  20012. *
  20013. * @internal
  20014. */
  20015. function isValid(value) {
  20016. if (typeof value === 'number') {
  20017. return isFiniteNumber(value);
  20018. }
  20019. return value != null && value !== '' && value !== false;
  20020. }
  20021. /**
  20022. * Constructs a relative path from a URL.
  20023. *
  20024. * @param url - The destination URL
  20025. * @param base - The base URL
  20026. * @returns The relative path
  20027. *
  20028. * @group Utils
  20029. *
  20030. * @beta
  20031. */
  20032. function urlToRelativePath(url, base) {
  20033. const to = new URL(url);
  20034. const from = new URL(base);
  20035. if (to.origin !== from.origin) {
  20036. return url;
  20037. }
  20038. const toPath = to.pathname.split('/').slice(1);
  20039. const fromPath = from.pathname.split('/').slice(1, -1);
  20040. // remove common parents
  20041. while (toPath[0] === fromPath[0]) {
  20042. toPath.shift();
  20043. fromPath.shift();
  20044. }
  20045. // add back paths
  20046. while (fromPath.length) {
  20047. fromPath.shift();
  20048. toPath.unshift('..');
  20049. }
  20050. return toPath.join('/');
  20051. }
  20052. const toRounded = value => Math.round(value);
  20053. const toUrlSafe = (value, options) => {
  20054. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  20055. value = urlToRelativePath(value, options.baseUrl);
  20056. }
  20057. return encodeURIComponent(value);
  20058. };
  20059. const toHundred = value => toRounded(value / 100) * 100;
  20060. /**
  20061. * The default formatters for CMCD values.
  20062. *
  20063. * @group CMCD
  20064. *
  20065. * @beta
  20066. */
  20067. const CmcdFormatters = {
  20068. /**
  20069. * Bitrate (kbps) rounded integer
  20070. */
  20071. br: toRounded,
  20072. /**
  20073. * Duration (milliseconds) rounded integer
  20074. */
  20075. d: toRounded,
  20076. /**
  20077. * Buffer Length (milliseconds) rounded nearest 100ms
  20078. */
  20079. bl: toHundred,
  20080. /**
  20081. * Deadline (milliseconds) rounded nearest 100ms
  20082. */
  20083. dl: toHundred,
  20084. /**
  20085. * Measured Throughput (kbps) rounded nearest 100kbps
  20086. */
  20087. mtp: toHundred,
  20088. /**
  20089. * Next Object Request URL encoded
  20090. */
  20091. nor: toUrlSafe,
  20092. /**
  20093. * Requested maximum throughput (kbps) rounded nearest 100kbps
  20094. */
  20095. rtp: toHundred,
  20096. /**
  20097. * Top Bitrate (kbps) rounded integer
  20098. */
  20099. tb: toRounded
  20100. };
  20101. /**
  20102. * Internal CMCD processing function.
  20103. *
  20104. * @param obj - The CMCD object to process.
  20105. * @param map - The mapping function to use.
  20106. * @param options - Options for encoding.
  20107. *
  20108. * @internal
  20109. *
  20110. * @group CMCD
  20111. */
  20112. function processCmcd(obj, options) {
  20113. const results = {};
  20114. if (obj == null || typeof obj !== 'object') {
  20115. return results;
  20116. }
  20117. const keys = Object.keys(obj).sort();
  20118. const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  20119. const filter = options === null || options === void 0 ? void 0 : options.filter;
  20120. keys.forEach(key => {
  20121. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  20122. return;
  20123. }
  20124. let value = obj[key];
  20125. const formatter = formatters[key];
  20126. if (formatter) {
  20127. value = formatter(value, options);
  20128. }
  20129. // Version should only be reported if not equal to 1.
  20130. if (key === 'v' && value === 1) {
  20131. return;
  20132. }
  20133. // Playback rate should only be sent if not equal to 1.
  20134. if (key == 'pr' && value === 1) {
  20135. return;
  20136. }
  20137. // ignore invalid values
  20138. if (!isValid(value)) {
  20139. return;
  20140. }
  20141. if (isTokenField(key) && typeof value === 'string') {
  20142. value = new SfToken(value);
  20143. }
  20144. results[key] = value;
  20145. });
  20146. return results;
  20147. }
  20148. /**
  20149. * Encode a CMCD object to a string.
  20150. *
  20151. * @param cmcd - The CMCD object to encode.
  20152. * @param options - Options for encoding.
  20153. *
  20154. * @returns The encoded CMCD string.
  20155. *
  20156. * @group CMCD
  20157. *
  20158. * @beta
  20159. */
  20160. function encodeCmcd(cmcd, options = {}) {
  20161. if (!cmcd) {
  20162. return '';
  20163. }
  20164. return encodeSfDict(processCmcd(cmcd, options), _extends({
  20165. whitespace: false
  20166. }, options));
  20167. }
  20168. /**
  20169. * Convert a CMCD data object to request headers
  20170. *
  20171. * @param cmcd - The CMCD data object to convert.
  20172. * @param options - Options for encoding the CMCD object.
  20173. *
  20174. * @returns The CMCD header shards.
  20175. *
  20176. * @group CMCD
  20177. *
  20178. * @beta
  20179. */
  20180. function toCmcdHeaders(cmcd, options = {}) {
  20181. const result = {};
  20182. if (!cmcd) {
  20183. return result;
  20184. }
  20185. const entries = Object.entries(cmcd);
  20186. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  20187. const shards = entries.reduce((acc, entry) => {
  20188. var _a, _b;
  20189. const [key, value] = entry;
  20190. const field = ((_a = headerMap.find(entry => entry[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  20191. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  20192. acc[field][key] = value;
  20193. return acc;
  20194. }, {});
  20195. return Object.entries(shards).reduce((acc, [field, value]) => {
  20196. acc[field] = encodeCmcd(value, options);
  20197. return acc;
  20198. }, result);
  20199. }
  20200. /**
  20201. * Append CMCD query args to a header object.
  20202. *
  20203. * @param headers - The headers to append to.
  20204. * @param cmcd - The CMCD object to append.
  20205. * @param options - Encode options.
  20206. *
  20207. * @returns The headers with the CMCD header shards appended.
  20208. *
  20209. * @group CMCD
  20210. *
  20211. * @beta
  20212. */
  20213. function appendCmcdHeaders(headers, cmcd, options) {
  20214. return _extends(headers, toCmcdHeaders(cmcd, options));
  20215. }
  20216. /**
  20217. * CMCD parameter name.
  20218. *
  20219. * @group CMCD
  20220. *
  20221. * @beta
  20222. */
  20223. const CMCD_PARAM = 'CMCD';
  20224. /**
  20225. * Convert a CMCD data object to a query arg.
  20226. *
  20227. * @param cmcd - The CMCD object to convert.
  20228. * @param options - Options for encoding the CMCD object.
  20229. *
  20230. * @returns The CMCD query arg.
  20231. *
  20232. * @group CMCD
  20233. *
  20234. * @beta
  20235. */
  20236. function toCmcdQuery(cmcd, options = {}) {
  20237. if (!cmcd) {
  20238. return '';
  20239. }
  20240. const params = encodeCmcd(cmcd, options);
  20241. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  20242. }
  20243. const REGEX = /CMCD=[^&#]+/;
  20244. /**
  20245. * Append CMCD query args to a URL.
  20246. *
  20247. * @param url - The URL to append to.
  20248. * @param cmcd - The CMCD object to append.
  20249. * @param options - Options for encoding the CMCD object.
  20250. *
  20251. * @returns The URL with the CMCD query args appended.
  20252. *
  20253. * @group CMCD
  20254. *
  20255. * @beta
  20256. */
  20257. function appendCmcdQuery(url, cmcd, options) {
  20258. // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.
  20259. // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
  20260. const query = toCmcdQuery(cmcd, options);
  20261. if (!query) {
  20262. return url;
  20263. }
  20264. if (REGEX.test(url)) {
  20265. return url.replace(REGEX, query);
  20266. }
  20267. const separator = url.includes('?') ? '&' : '?';
  20268. return `${url}${separator}${query}`;
  20269. }
  20270. /**
  20271. * Controller to deal with Common Media Client Data (CMCD)
  20272. * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
  20273. */
  20274. class CMCDController {
  20275. constructor(hls) {
  20276. this.hls = void 0;
  20277. this.config = void 0;
  20278. this.media = void 0;
  20279. this.sid = void 0;
  20280. this.cid = void 0;
  20281. this.useHeaders = false;
  20282. this.includeKeys = void 0;
  20283. this.initialized = false;
  20284. this.starved = false;
  20285. this.buffering = true;
  20286. this.audioBuffer = void 0;
  20287. this.videoBuffer = void 0;
  20288. this.onWaiting = () => {
  20289. if (this.initialized) {
  20290. this.starved = true;
  20291. }
  20292. this.buffering = true;
  20293. };
  20294. this.onPlaying = () => {
  20295. if (!this.initialized) {
  20296. this.initialized = true;
  20297. }
  20298. this.buffering = false;
  20299. };
  20300. /**
  20301. * Apply CMCD data to a manifest request.
  20302. */
  20303. this.applyPlaylistData = context => {
  20304. try {
  20305. this.apply(context, {
  20306. ot: CmcdObjectType.MANIFEST,
  20307. su: !this.initialized
  20308. });
  20309. } catch (error) {
  20310. this.hls.logger.warn('Could not generate manifest CMCD data.', error);
  20311. }
  20312. };
  20313. /**
  20314. * Apply CMCD data to a segment request
  20315. */
  20316. this.applyFragmentData = context => {
  20317. try {
  20318. const {
  20319. frag,
  20320. part
  20321. } = context;
  20322. const level = this.hls.levels[frag.level];
  20323. const ot = this.getObjectType(frag);
  20324. const data = {
  20325. d: (part || frag).duration * 1000,
  20326. ot
  20327. };
  20328. if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
  20329. data.br = level.bitrate / 1000;
  20330. data.tb = this.getTopBandwidth(ot) / 1000;
  20331. data.bl = this.getBufferLength(ot);
  20332. }
  20333. const next = part ? this.getNextPart(part) : this.getNextFrag(frag);
  20334. if (next != null && next.url && next.url !== frag.url) {
  20335. data.nor = next.url;
  20336. }
  20337. this.apply(context, data);
  20338. } catch (error) {
  20339. this.hls.logger.warn('Could not generate segment CMCD data.', error);
  20340. }
  20341. };
  20342. this.hls = hls;
  20343. const config = this.config = hls.config;
  20344. const {
  20345. cmcd
  20346. } = config;
  20347. if (cmcd != null) {
  20348. config.pLoader = this.createPlaylistLoader();
  20349. config.fLoader = this.createFragmentLoader();
  20350. this.sid = cmcd.sessionId || hls.sessionId;
  20351. this.cid = cmcd.contentId;
  20352. this.useHeaders = cmcd.useHeaders === true;
  20353. this.includeKeys = cmcd.includeKeys;
  20354. this.registerListeners();
  20355. }
  20356. }
  20357. registerListeners() {
  20358. const hls = this.hls;
  20359. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20360. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  20361. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  20362. }
  20363. unregisterListeners() {
  20364. const hls = this.hls;
  20365. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  20366. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  20367. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  20368. }
  20369. destroy() {
  20370. this.unregisterListeners();
  20371. this.onMediaDetached();
  20372. // @ts-ignore
  20373. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  20374. // @ts-ignore
  20375. this.onWaiting = this.onPlaying = this.media = null;
  20376. }
  20377. onMediaAttached(event, data) {
  20378. this.media = data.media;
  20379. this.media.addEventListener('waiting', this.onWaiting);
  20380. this.media.addEventListener('playing', this.onPlaying);
  20381. }
  20382. onMediaDetached() {
  20383. if (!this.media) {
  20384. return;
  20385. }
  20386. this.media.removeEventListener('waiting', this.onWaiting);
  20387. this.media.removeEventListener('playing', this.onPlaying);
  20388. // @ts-ignore
  20389. this.media = null;
  20390. }
  20391. onBufferCreated(event, data) {
  20392. var _data$tracks$audio, _data$tracks$video;
  20393. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  20394. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  20395. }
  20396. /**
  20397. * Create baseline CMCD data
  20398. */
  20399. createData() {
  20400. var _this$media;
  20401. return {
  20402. v: 1,
  20403. sf: CmcdStreamingFormat.HLS,
  20404. sid: this.sid,
  20405. cid: this.cid,
  20406. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  20407. mtp: this.hls.bandwidthEstimate / 1000
  20408. };
  20409. }
  20410. /**
  20411. * Apply CMCD data to a request.
  20412. */
  20413. apply(context, data = {}) {
  20414. // apply baseline data
  20415. _extends(data, this.createData());
  20416. const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  20417. if (this.starved && isVideo) {
  20418. data.bs = true;
  20419. data.su = true;
  20420. this.starved = false;
  20421. }
  20422. if (data.su == null) {
  20423. data.su = this.buffering;
  20424. }
  20425. // TODO: Implement rtp, nrr, dl
  20426. const {
  20427. includeKeys
  20428. } = this;
  20429. if (includeKeys) {
  20430. data = Object.keys(data).reduce((acc, key) => {
  20431. includeKeys.includes(key) && (acc[key] = data[key]);
  20432. return acc;
  20433. }, {});
  20434. }
  20435. const options = {
  20436. baseUrl: context.url
  20437. };
  20438. if (this.useHeaders) {
  20439. if (!context.headers) {
  20440. context.headers = {};
  20441. }
  20442. appendCmcdHeaders(context.headers, data, options);
  20443. } else {
  20444. context.url = appendCmcdQuery(context.url, data, options);
  20445. }
  20446. }
  20447. getNextFrag(fragment) {
  20448. var _this$hls$levels$frag;
  20449. const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  20450. if (levelDetails) {
  20451. const index = fragment.sn - levelDetails.startSN;
  20452. return levelDetails.fragments[index + 1];
  20453. }
  20454. return undefined;
  20455. }
  20456. getNextPart(part) {
  20457. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  20458. const {
  20459. index,
  20460. fragment
  20461. } = part;
  20462. const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;
  20463. if (partList) {
  20464. const {
  20465. sn
  20466. } = fragment;
  20467. for (let i = partList.length - 1; i >= 0; i--) {
  20468. const p = partList[i];
  20469. if (p.index === index && p.fragment.sn === sn) {
  20470. return partList[i + 1];
  20471. }
  20472. }
  20473. }
  20474. return undefined;
  20475. }
  20476. /**
  20477. * The CMCD object type.
  20478. */
  20479. getObjectType(fragment) {
  20480. const {
  20481. type
  20482. } = fragment;
  20483. if (type === 'subtitle') {
  20484. return CmcdObjectType.TIMED_TEXT;
  20485. }
  20486. if (fragment.sn === 'initSegment') {
  20487. return CmcdObjectType.INIT;
  20488. }
  20489. if (type === 'audio') {
  20490. return CmcdObjectType.AUDIO;
  20491. }
  20492. if (type === 'main') {
  20493. if (!this.hls.audioTracks.length) {
  20494. return CmcdObjectType.MUXED;
  20495. }
  20496. return CmcdObjectType.VIDEO;
  20497. }
  20498. return undefined;
  20499. }
  20500. /**
  20501. * Get the highest bitrate.
  20502. */
  20503. getTopBandwidth(type) {
  20504. let bitrate = 0;
  20505. let levels;
  20506. const hls = this.hls;
  20507. if (type === CmcdObjectType.AUDIO) {
  20508. levels = hls.audioTracks;
  20509. } else {
  20510. const max = hls.maxAutoLevel;
  20511. const len = max > -1 ? max + 1 : hls.levels.length;
  20512. levels = hls.levels.slice(0, len);
  20513. }
  20514. levels.forEach(level => {
  20515. if (level.bitrate > bitrate) {
  20516. bitrate = level.bitrate;
  20517. }
  20518. });
  20519. return bitrate > 0 ? bitrate : NaN;
  20520. }
  20521. /**
  20522. * Get the buffer length for a media type in milliseconds
  20523. */
  20524. getBufferLength(type) {
  20525. const media = this.media;
  20526. const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  20527. if (!buffer || !media) {
  20528. return NaN;
  20529. }
  20530. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  20531. return info.len * 1000;
  20532. }
  20533. /**
  20534. * Create a playlist loader
  20535. */
  20536. createPlaylistLoader() {
  20537. const {
  20538. pLoader
  20539. } = this.config;
  20540. const apply = this.applyPlaylistData;
  20541. const Ctor = pLoader || this.config.loader;
  20542. return class CmcdPlaylistLoader {
  20543. constructor(config) {
  20544. this.loader = void 0;
  20545. this.loader = new Ctor(config);
  20546. }
  20547. get stats() {
  20548. return this.loader.stats;
  20549. }
  20550. get context() {
  20551. return this.loader.context;
  20552. }
  20553. destroy() {
  20554. this.loader.destroy();
  20555. }
  20556. abort() {
  20557. this.loader.abort();
  20558. }
  20559. load(context, config, callbacks) {
  20560. apply(context);
  20561. this.loader.load(context, config, callbacks);
  20562. }
  20563. };
  20564. }
  20565. /**
  20566. * Create a playlist loader
  20567. */
  20568. createFragmentLoader() {
  20569. const {
  20570. fLoader
  20571. } = this.config;
  20572. const apply = this.applyFragmentData;
  20573. const Ctor = fLoader || this.config.loader;
  20574. return class CmcdFragmentLoader {
  20575. constructor(config) {
  20576. this.loader = void 0;
  20577. this.loader = new Ctor(config);
  20578. }
  20579. get stats() {
  20580. return this.loader.stats;
  20581. }
  20582. get context() {
  20583. return this.loader.context;
  20584. }
  20585. destroy() {
  20586. this.loader.destroy();
  20587. }
  20588. abort() {
  20589. this.loader.abort();
  20590. }
  20591. load(context, config, callbacks) {
  20592. apply(context);
  20593. this.loader.load(context, config, callbacks);
  20594. }
  20595. };
  20596. }
  20597. }
  20598. const PATHWAY_PENALTY_DURATION_MS = 300000;
  20599. class ContentSteeringController extends Logger {
  20600. constructor(hls) {
  20601. super('content-steering', hls.logger);
  20602. this.hls = void 0;
  20603. this.loader = null;
  20604. this.uri = null;
  20605. this.pathwayId = '.';
  20606. this._pathwayPriority = null;
  20607. this.timeToLoad = 300;
  20608. this.reloadTimer = -1;
  20609. this.updated = 0;
  20610. this.started = false;
  20611. this.enabled = true;
  20612. this.levels = null;
  20613. this.audioTracks = null;
  20614. this.subtitleTracks = null;
  20615. this.penalizedPathways = {};
  20616. this.hls = hls;
  20617. this.registerListeners();
  20618. }
  20619. registerListeners() {
  20620. const hls = this.hls;
  20621. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20622. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20623. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20624. hls.on(Events.ERROR, this.onError, this);
  20625. }
  20626. unregisterListeners() {
  20627. const hls = this.hls;
  20628. if (!hls) {
  20629. return;
  20630. }
  20631. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20632. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20633. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20634. hls.off(Events.ERROR, this.onError, this);
  20635. }
  20636. pathways() {
  20637. return (this.levels || []).reduce((pathways, level) => {
  20638. if (pathways.indexOf(level.pathwayId) === -1) {
  20639. pathways.push(level.pathwayId);
  20640. }
  20641. return pathways;
  20642. }, []);
  20643. }
  20644. get pathwayPriority() {
  20645. return this._pathwayPriority;
  20646. }
  20647. set pathwayPriority(pathwayPriority) {
  20648. this.updatePathwayPriority(pathwayPriority);
  20649. }
  20650. startLoad() {
  20651. this.started = true;
  20652. this.clearTimeout();
  20653. if (this.enabled && this.uri) {
  20654. if (this.updated) {
  20655. const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  20656. if (ttl > 0) {
  20657. this.scheduleRefresh(this.uri, ttl);
  20658. return;
  20659. }
  20660. }
  20661. this.loadSteeringManifest(this.uri);
  20662. }
  20663. }
  20664. stopLoad() {
  20665. this.started = false;
  20666. if (this.loader) {
  20667. this.loader.destroy();
  20668. this.loader = null;
  20669. }
  20670. this.clearTimeout();
  20671. }
  20672. clearTimeout() {
  20673. if (this.reloadTimer !== -1) {
  20674. self.clearTimeout(this.reloadTimer);
  20675. this.reloadTimer = -1;
  20676. }
  20677. }
  20678. destroy() {
  20679. this.unregisterListeners();
  20680. this.stopLoad();
  20681. // @ts-ignore
  20682. this.hls = null;
  20683. this.levels = this.audioTracks = this.subtitleTracks = null;
  20684. }
  20685. removeLevel(levelToRemove) {
  20686. const levels = this.levels;
  20687. if (levels) {
  20688. this.levels = levels.filter(level => level !== levelToRemove);
  20689. }
  20690. }
  20691. onManifestLoading() {
  20692. this.stopLoad();
  20693. this.enabled = true;
  20694. this.timeToLoad = 300;
  20695. this.updated = 0;
  20696. this.uri = null;
  20697. this.pathwayId = '.';
  20698. this.levels = this.audioTracks = this.subtitleTracks = null;
  20699. }
  20700. onManifestLoaded(event, data) {
  20701. const {
  20702. contentSteering
  20703. } = data;
  20704. if (contentSteering === null) {
  20705. return;
  20706. }
  20707. this.pathwayId = contentSteering.pathwayId;
  20708. this.uri = contentSteering.uri;
  20709. if (this.started) {
  20710. this.startLoad();
  20711. }
  20712. }
  20713. onManifestParsed(event, data) {
  20714. this.audioTracks = data.audioTracks;
  20715. this.subtitleTracks = data.subtitleTracks;
  20716. }
  20717. onError(event, data) {
  20718. const {
  20719. errorAction
  20720. } = data;
  20721. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  20722. const levels = this.levels;
  20723. let pathwayPriority = this._pathwayPriority;
  20724. let errorPathway = this.pathwayId;
  20725. if (data.context) {
  20726. const {
  20727. groupId,
  20728. pathwayId,
  20729. type
  20730. } = data.context;
  20731. if (groupId && levels) {
  20732. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  20733. } else if (pathwayId) {
  20734. errorPathway = pathwayId;
  20735. }
  20736. }
  20737. if (!(errorPathway in this.penalizedPathways)) {
  20738. this.penalizedPathways[errorPathway] = performance.now();
  20739. }
  20740. if (!pathwayPriority && levels) {
  20741. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  20742. pathwayPriority = this.pathways();
  20743. }
  20744. if (pathwayPriority && pathwayPriority.length > 1) {
  20745. this.updatePathwayPriority(pathwayPriority);
  20746. errorAction.resolved = this.pathwayId !== errorPathway;
  20747. }
  20748. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  20749. // Error will become fatal in buffer-controller when reaching `appendErrorMaxRetry`
  20750. // Stream-controllers are expected to reduce buffer length even if this is not deemed a QuotaExceededError
  20751. errorAction.resolved = true;
  20752. } else if (!errorAction.resolved) {
  20753. this.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${stringify(pathwayPriority)} penalized: ${stringify(this.penalizedPathways)}`);
  20754. }
  20755. }
  20756. }
  20757. filterParsedLevels(levels) {
  20758. // Filter levels to only include those that are in the initial pathway
  20759. this.levels = levels;
  20760. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  20761. if (pathwayLevels.length === 0) {
  20762. const pathwayId = levels[0].pathwayId;
  20763. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  20764. pathwayLevels = this.getLevelsForPathway(pathwayId);
  20765. this.pathwayId = pathwayId;
  20766. }
  20767. if (pathwayLevels.length !== levels.length) {
  20768. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  20769. }
  20770. return pathwayLevels;
  20771. }
  20772. getLevelsForPathway(pathwayId) {
  20773. if (this.levels === null) {
  20774. return [];
  20775. }
  20776. return this.levels.filter(level => pathwayId === level.pathwayId);
  20777. }
  20778. updatePathwayPriority(pathwayPriority) {
  20779. this._pathwayPriority = pathwayPriority;
  20780. let levels;
  20781. // Evaluate if we should remove the pathway from the penalized list
  20782. const penalizedPathways = this.penalizedPathways;
  20783. const now = performance.now();
  20784. Object.keys(penalizedPathways).forEach(pathwayId => {
  20785. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  20786. delete penalizedPathways[pathwayId];
  20787. }
  20788. });
  20789. for (let i = 0; i < pathwayPriority.length; i++) {
  20790. const pathwayId = pathwayPriority[i];
  20791. if (pathwayId in penalizedPathways) {
  20792. continue;
  20793. }
  20794. if (pathwayId === this.pathwayId) {
  20795. return;
  20796. }
  20797. const selectedIndex = this.hls.nextLoadLevel;
  20798. const selectedLevel = this.hls.levels[selectedIndex];
  20799. levels = this.getLevelsForPathway(pathwayId);
  20800. if (levels.length > 0) {
  20801. this.log(`Setting Pathway to "${pathwayId}"`);
  20802. this.pathwayId = pathwayId;
  20803. reassignFragmentLevelIndexes(levels);
  20804. this.hls.trigger(Events.LEVELS_UPDATED, {
  20805. levels
  20806. });
  20807. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  20808. const levelAfterChange = this.hls.levels[selectedIndex];
  20809. if (selectedLevel && levelAfterChange && this.levels) {
  20810. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  20811. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  20812. }
  20813. this.hls.nextLoadLevel = selectedIndex;
  20814. }
  20815. break;
  20816. }
  20817. }
  20818. }
  20819. getPathwayForGroupId(groupId, type, defaultPathway) {
  20820. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  20821. for (let i = 0; i < levels.length; i++) {
  20822. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  20823. return levels[i].pathwayId;
  20824. }
  20825. }
  20826. return defaultPathway;
  20827. }
  20828. clonePathways(pathwayClones) {
  20829. const levels = this.levels;
  20830. if (!levels) {
  20831. return;
  20832. }
  20833. const audioGroupCloneMap = {};
  20834. const subtitleGroupCloneMap = {};
  20835. pathwayClones.forEach(pathwayClone => {
  20836. const {
  20837. ID: cloneId,
  20838. 'BASE-ID': baseId,
  20839. 'URI-REPLACEMENT': uriReplacement
  20840. } = pathwayClone;
  20841. if (levels.some(level => level.pathwayId === cloneId)) {
  20842. return;
  20843. }
  20844. const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {
  20845. const attributes = new AttrList(baseLevel.attrs);
  20846. attributes['PATHWAY-ID'] = cloneId;
  20847. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  20848. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  20849. if (clonedAudioGroupId) {
  20850. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  20851. attributes.AUDIO = clonedAudioGroupId;
  20852. }
  20853. if (clonedSubtitleGroupId) {
  20854. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  20855. attributes.SUBTITLES = clonedSubtitleGroupId;
  20856. }
  20857. const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  20858. const clonedLevel = new Level({
  20859. attrs: attributes,
  20860. audioCodec: baseLevel.audioCodec,
  20861. bitrate: baseLevel.bitrate,
  20862. height: baseLevel.height,
  20863. name: baseLevel.name,
  20864. url,
  20865. videoCodec: baseLevel.videoCodec,
  20866. width: baseLevel.width
  20867. });
  20868. if (baseLevel.audioGroups) {
  20869. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  20870. clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  20871. }
  20872. }
  20873. if (baseLevel.subtitleGroups) {
  20874. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  20875. clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  20876. }
  20877. }
  20878. return clonedLevel;
  20879. });
  20880. levels.push(...clonedVariants);
  20881. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  20882. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  20883. });
  20884. }
  20885. loadSteeringManifest(uri) {
  20886. const config = this.hls.config;
  20887. const Loader = config.loader;
  20888. if (this.loader) {
  20889. this.loader.destroy();
  20890. }
  20891. this.loader = new Loader(config);
  20892. let url;
  20893. try {
  20894. url = new self.URL(uri);
  20895. } catch (error) {
  20896. this.enabled = false;
  20897. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  20898. return;
  20899. }
  20900. if (url.protocol !== 'data:') {
  20901. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  20902. url.searchParams.set('_HLS_pathway', this.pathwayId);
  20903. url.searchParams.set('_HLS_throughput', '' + throughput);
  20904. }
  20905. const context = {
  20906. responseType: 'json',
  20907. url: url.href
  20908. };
  20909. const loadPolicy = config.steeringManifestLoadPolicy.default;
  20910. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  20911. const loaderConfig = {
  20912. loadPolicy,
  20913. timeout: loadPolicy.maxLoadTimeMs,
  20914. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  20915. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  20916. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  20917. };
  20918. const callbacks = {
  20919. onSuccess: (response, stats, context, networkDetails) => {
  20920. this.log(`Loaded steering manifest: "${url}"`);
  20921. const steeringData = response.data;
  20922. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  20923. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  20924. return;
  20925. }
  20926. this.updated = performance.now();
  20927. this.timeToLoad = steeringData.TTL;
  20928. const {
  20929. 'RELOAD-URI': reloadUri,
  20930. 'PATHWAY-CLONES': pathwayClones,
  20931. 'PATHWAY-PRIORITY': pathwayPriority
  20932. } = steeringData;
  20933. if (reloadUri) {
  20934. try {
  20935. this.uri = new self.URL(reloadUri, url).href;
  20936. } catch (error) {
  20937. this.enabled = false;
  20938. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  20939. return;
  20940. }
  20941. }
  20942. this.scheduleRefresh(this.uri || context.url);
  20943. if (pathwayClones) {
  20944. this.clonePathways(pathwayClones);
  20945. }
  20946. const loadedSteeringData = {
  20947. steeringManifest: steeringData,
  20948. url: url.toString()
  20949. };
  20950. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  20951. if (pathwayPriority) {
  20952. this.updatePathwayPriority(pathwayPriority);
  20953. }
  20954. },
  20955. onError: (error, context, networkDetails, stats) => {
  20956. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);
  20957. this.stopLoad();
  20958. if (error.code === 410) {
  20959. this.enabled = false;
  20960. this.log(`Steering manifest ${context.url} no longer available`);
  20961. return;
  20962. }
  20963. let ttl = this.timeToLoad * 1000;
  20964. if (error.code === 429) {
  20965. const loader = this.loader;
  20966. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  20967. const retryAfter = loader.getResponseHeader('Retry-After');
  20968. if (retryAfter) {
  20969. ttl = parseFloat(retryAfter) * 1000;
  20970. }
  20971. }
  20972. this.log(`Steering manifest ${context.url} rate limited`);
  20973. return;
  20974. }
  20975. this.scheduleRefresh(this.uri || context.url, ttl);
  20976. },
  20977. onTimeout: (stats, context, networkDetails) => {
  20978. this.log(`Timeout loading steering manifest (${context.url})`);
  20979. this.scheduleRefresh(this.uri || context.url);
  20980. }
  20981. };
  20982. this.log(`Requesting steering manifest: ${url}`);
  20983. this.loader.load(context, loaderConfig, callbacks);
  20984. }
  20985. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {
  20986. this.clearTimeout();
  20987. this.reloadTimer = self.setTimeout(() => {
  20988. var _this$hls;
  20989. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  20990. if (media && !media.ended) {
  20991. this.loadSteeringManifest(uri);
  20992. return;
  20993. }
  20994. this.scheduleRefresh(uri, this.timeToLoad * 1000);
  20995. }, ttlMs);
  20996. }
  20997. }
  20998. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  20999. if (!tracks) {
  21000. return;
  21001. }
  21002. Object.keys(groupCloneMap).forEach(audioGroupId => {
  21003. const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {
  21004. const clonedTrack = _extends({}, track);
  21005. clonedTrack.details = undefined;
  21006. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  21007. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  21008. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  21009. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  21010. return clonedTrack;
  21011. });
  21012. tracks.push(...clonedTracks);
  21013. });
  21014. }
  21015. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  21016. const {
  21017. HOST: host,
  21018. PARAMS: params,
  21019. [perOptionKey]: perOptionUris
  21020. } = uriReplacement;
  21021. let perVariantUri;
  21022. if (stableId) {
  21023. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  21024. if (perVariantUri) {
  21025. uri = perVariantUri;
  21026. }
  21027. }
  21028. const url = new self.URL(uri);
  21029. if (host && !perVariantUri) {
  21030. url.host = host;
  21031. }
  21032. if (params) {
  21033. Object.keys(params).sort().forEach(key => {
  21034. if (key) {
  21035. url.searchParams.set(key, params[key]);
  21036. }
  21037. });
  21038. }
  21039. return url.href;
  21040. }
  21041. function addEventListener(el, type, listener) {
  21042. removeEventListener(el, type, listener);
  21043. el.addEventListener(type, listener);
  21044. }
  21045. function removeEventListener(el, type, listener) {
  21046. el.removeEventListener(type, listener);
  21047. }
  21048. /**
  21049. * Controller to deal with encrypted media extensions (EME)
  21050. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  21051. *
  21052. * @class
  21053. * @constructor
  21054. */
  21055. class EMEController extends Logger {
  21056. constructor(hls) {
  21057. super('eme', hls.logger);
  21058. this.hls = void 0;
  21059. this.config = void 0;
  21060. this.media = null;
  21061. this.keyFormatPromise = null;
  21062. this.keySystemAccessPromises = {};
  21063. this._requestLicenseFailureCount = 0;
  21064. this.mediaKeySessions = [];
  21065. this.keyIdToKeySessionPromise = {};
  21066. this.mediaKeys = null;
  21067. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  21068. this.onWaitingForKey = event => {
  21069. this.log(`"${event.type}" event`);
  21070. };
  21071. this.hls = hls;
  21072. this.config = hls.config;
  21073. this.registerListeners();
  21074. }
  21075. destroy() {
  21076. this.onDestroying();
  21077. this.onMediaDetached();
  21078. // Remove any references that could be held in config options or callbacks
  21079. const config = this.config;
  21080. config.requestMediaKeySystemAccessFunc = null;
  21081. config.licenseXhrSetup = config.licenseResponseCallback = undefined;
  21082. config.drmSystems = config.drmSystemOptions = {};
  21083. // @ts-ignore
  21084. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  21085. // @ts-ignore
  21086. this.onWaitingForKey = null;
  21087. }
  21088. registerListeners() {
  21089. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21090. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21091. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21092. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21093. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  21094. }
  21095. unregisterListeners() {
  21096. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21097. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21098. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21099. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21100. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  21101. }
  21102. getLicenseServerUrl(keySystem) {
  21103. const {
  21104. drmSystems,
  21105. widevineLicenseUrl
  21106. } = this.config;
  21107. const keySystemConfiguration = drmSystems[keySystem];
  21108. if (keySystemConfiguration) {
  21109. return keySystemConfiguration.licenseUrl;
  21110. }
  21111. // For backward compatibility
  21112. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  21113. return widevineLicenseUrl;
  21114. }
  21115. }
  21116. getLicenseServerUrlOrThrow(keySystem) {
  21117. const url = this.getLicenseServerUrl(keySystem);
  21118. if (url === undefined) {
  21119. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  21120. }
  21121. return url;
  21122. }
  21123. getServerCertificateUrl(keySystem) {
  21124. const {
  21125. drmSystems
  21126. } = this.config;
  21127. const keySystemConfiguration = drmSystems[keySystem];
  21128. if (keySystemConfiguration) {
  21129. return keySystemConfiguration.serverCertificateUrl;
  21130. } else {
  21131. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  21132. }
  21133. }
  21134. attemptKeySystemAccess(keySystemsToAttempt) {
  21135. const levels = this.hls.levels;
  21136. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  21137. const audioCodecs = levels.map(level => level.audioCodec).filter(uniqueCodec);
  21138. const videoCodecs = levels.map(level => level.videoCodec).filter(uniqueCodec);
  21139. if (audioCodecs.length + videoCodecs.length === 0) {
  21140. videoCodecs.push('avc1.42e01e');
  21141. }
  21142. return new Promise((resolve, reject) => {
  21143. const attempt = keySystems => {
  21144. const keySystem = keySystems.shift();
  21145. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then(mediaKeys => resolve({
  21146. keySystem,
  21147. mediaKeys
  21148. })).catch(error => {
  21149. if (keySystems.length) {
  21150. attempt(keySystems);
  21151. } else if (error instanceof EMEKeyError) {
  21152. reject(error);
  21153. } else {
  21154. reject(new EMEKeyError({
  21155. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21156. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  21157. error,
  21158. fatal: true
  21159. }, error.message));
  21160. }
  21161. });
  21162. };
  21163. attempt(keySystemsToAttempt);
  21164. });
  21165. }
  21166. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  21167. const {
  21168. requestMediaKeySystemAccessFunc
  21169. } = this.config;
  21170. if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {
  21171. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  21172. if (requestMediaKeySystemAccess === null && self.location.protocol === 'http:') {
  21173. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  21174. }
  21175. return Promise.reject(new Error(errMessage));
  21176. }
  21177. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  21178. }
  21179. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  21180. // This can throw, but is caught in event handler callpath
  21181. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  21182. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  21183. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  21184. if (!keySystemAccess) {
  21185. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);
  21186. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  21187. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  21188. keySystemAccess
  21189. };
  21190. keySystemAccess.catch(error => {
  21191. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  21192. });
  21193. return keySystemAccess.then(mediaKeySystemAccess => {
  21194. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  21195. const certificateRequest = this.fetchServerCertificate(keySystem);
  21196. this.log(`Create media-keys for "${keySystem}"`);
  21197. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then(mediaKeys => {
  21198. this.log(`Media-keys created for "${keySystem}"`);
  21199. _keySystemAccessPromises.hasMediaKeys = true;
  21200. return certificateRequest.then(certificate => {
  21201. if (certificate) {
  21202. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  21203. }
  21204. return mediaKeys;
  21205. });
  21206. });
  21207. _keySystemAccessPromises.mediaKeys.catch(error => {
  21208. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  21209. });
  21210. return _keySystemAccessPromises.mediaKeys;
  21211. });
  21212. }
  21213. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  21214. }
  21215. createMediaKeySessionContext({
  21216. decryptdata,
  21217. keySystem,
  21218. mediaKeys
  21219. }) {
  21220. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  21221. const mediaKeysSession = mediaKeys.createSession();
  21222. const mediaKeySessionContext = {
  21223. decryptdata,
  21224. keySystem,
  21225. mediaKeys,
  21226. mediaKeysSession,
  21227. keyStatus: 'status-pending'
  21228. };
  21229. this.mediaKeySessions.push(mediaKeySessionContext);
  21230. return mediaKeySessionContext;
  21231. }
  21232. renewKeySession(mediaKeySessionContext) {
  21233. const decryptdata = mediaKeySessionContext.decryptdata;
  21234. if (decryptdata.pssh) {
  21235. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  21236. const keyId = this.getKeyIdString(decryptdata);
  21237. const scheme = 'cenc';
  21238. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, 'expired');
  21239. } else {
  21240. this.warn(`Could not renew expired session. Missing pssh initData.`);
  21241. }
  21242. this.removeSession(mediaKeySessionContext);
  21243. }
  21244. getKeyIdString(decryptdata) {
  21245. if (!decryptdata) {
  21246. throw new Error('Could not read keyId of undefined decryptdata');
  21247. }
  21248. if (decryptdata.keyId === null) {
  21249. throw new Error('keyId is null');
  21250. }
  21251. return Hex.hexDump(decryptdata.keyId);
  21252. }
  21253. updateKeySession(mediaKeySessionContext, data) {
  21254. var _mediaKeySessionConte;
  21255. const keySession = mediaKeySessionContext.mediaKeysSession;
  21256. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  21257. } (data length: ${data ? data.byteLength : data})`);
  21258. return keySession.update(data);
  21259. }
  21260. getSelectedKeySystemFormats() {
  21261. return Object.keys(this.keySystemAccessPromises).map(keySystem => ({
  21262. keySystem,
  21263. hasMediaKeys: this.keySystemAccessPromises[keySystem].hasMediaKeys
  21264. })).filter(({
  21265. hasMediaKeys
  21266. }) => !!hasMediaKeys).map(({
  21267. keySystem
  21268. }) => keySystemDomainToKeySystemFormat(keySystem)).filter(keySystem => !!keySystem);
  21269. }
  21270. getKeySystemAccess(keySystemsToAttempt) {
  21271. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  21272. keySystem,
  21273. mediaKeys
  21274. }) => {
  21275. return this.attemptSetMediaKeys(keySystem, mediaKeys);
  21276. });
  21277. }
  21278. selectKeySystem(keySystemsToAttempt) {
  21279. return new Promise((resolve, reject) => {
  21280. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  21281. keySystem
  21282. }) => {
  21283. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  21284. if (keySystemFormat) {
  21285. resolve(keySystemFormat);
  21286. } else {
  21287. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  21288. }
  21289. }).catch(reject);
  21290. });
  21291. }
  21292. selectKeySystemFormat(frag) {
  21293. const keyFormats = Object.keys(frag.levelkeys || {});
  21294. if (!this.keyFormatPromise) {
  21295. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(', ')}`);
  21296. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  21297. }
  21298. return this.keyFormatPromise;
  21299. }
  21300. getKeyFormatPromise(keyFormats) {
  21301. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  21302. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter(value => !!value && keySystemsInConfig.indexOf(value) !== -1);
  21303. return this.selectKeySystem(keySystemsToAttempt);
  21304. }
  21305. loadKey(data) {
  21306. const decryptdata = data.keyInfo.decryptdata;
  21307. const keyId = this.getKeyIdString(decryptdata);
  21308. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  21309. this.log(`Starting session for key ${keyDetails}`);
  21310. let keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  21311. if (!keyContextPromise) {
  21312. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({
  21313. keySystem,
  21314. mediaKeys
  21315. }) => {
  21316. this.throwIfDestroyed();
  21317. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  21318. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  21319. this.throwIfDestroyed();
  21320. return this.createMediaKeySessionContext({
  21321. keySystem,
  21322. mediaKeys,
  21323. decryptdata
  21324. });
  21325. });
  21326. });
  21327. const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then(keySessionContext => {
  21328. const scheme = 'cenc';
  21329. const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  21330. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, 'playlist-key');
  21331. });
  21332. keySessionContextPromise.catch(error => this.handleError(error));
  21333. }
  21334. return keyContextPromise;
  21335. }
  21336. throwIfDestroyed(message = 'Invalid state') {
  21337. if (!this.hls) {
  21338. throw new Error('invalid state');
  21339. }
  21340. }
  21341. handleError(error) {
  21342. if (!this.hls) {
  21343. return;
  21344. }
  21345. this.error(error.message);
  21346. if (error instanceof EMEKeyError) {
  21347. this.hls.trigger(Events.ERROR, error.data);
  21348. } else {
  21349. this.hls.trigger(Events.ERROR, {
  21350. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21351. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  21352. error,
  21353. fatal: true
  21354. });
  21355. }
  21356. }
  21357. getKeySystemForKeyPromise(decryptdata) {
  21358. const keyId = this.getKeyIdString(decryptdata);
  21359. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  21360. if (!mediaKeySessionContext) {
  21361. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  21362. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  21363. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21364. }
  21365. return mediaKeySessionContext;
  21366. }
  21367. getKeySystemSelectionPromise(keySystemsToAttempt) {
  21368. if (!keySystemsToAttempt.length) {
  21369. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  21370. }
  21371. if (keySystemsToAttempt.length === 0) {
  21372. throw new EMEKeyError({
  21373. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21374. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  21375. fatal: true
  21376. }, `Missing key-system license configuration options ${stringify({
  21377. drmSystems: this.config.drmSystems
  21378. })}`);
  21379. }
  21380. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21381. }
  21382. attemptSetMediaKeys(keySystem, mediaKeys) {
  21383. if (this.mediaKeys === mediaKeys) {
  21384. return Promise.resolve();
  21385. }
  21386. const queue = this.setMediaKeysQueue.slice();
  21387. this.log(`Setting media-keys for "${keySystem}"`);
  21388. // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations
  21389. // can be queued for execution for multiple key sessions.
  21390. const setMediaKeysPromise = Promise.all(queue).then(() => {
  21391. if (!this.media) {
  21392. this.mediaKeys = null;
  21393. throw new Error('Attempted to set mediaKeys without media element attached');
  21394. }
  21395. return this.media.setMediaKeys(mediaKeys);
  21396. });
  21397. this.mediaKeys = mediaKeys;
  21398. this.setMediaKeysQueue.push(setMediaKeysPromise);
  21399. return setMediaKeysPromise.then(() => {
  21400. this.log(`Media-keys set for "${keySystem}"`);
  21401. queue.push(setMediaKeysPromise);
  21402. this.setMediaKeysQueue = this.setMediaKeysQueue.filter(p => queue.indexOf(p) === -1);
  21403. });
  21404. }
  21405. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  21406. var _this$config$drmSyste, _this$config$drmSyste2;
  21407. const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;
  21408. if (generateRequestFilter) {
  21409. try {
  21410. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  21411. if (!mappedInitData) {
  21412. throw new Error('Invalid response from configured generateRequest filter');
  21413. }
  21414. initDataType = mappedInitData.initDataType;
  21415. initData = mappedInitData.initData ? mappedInitData.initData : null;
  21416. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  21417. } catch (error) {
  21418. var _this$hls;
  21419. this.warn(error.message);
  21420. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  21421. throw error;
  21422. }
  21423. }
  21424. }
  21425. if (initData === null) {
  21426. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  21427. return Promise.resolve(context);
  21428. }
  21429. const keyId = this.getKeyIdString(context.decryptdata);
  21430. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  21431. const licenseStatus = new EventEmitter();
  21432. const onmessage = context._onmessage = event => {
  21433. const keySession = context.mediaKeysSession;
  21434. if (!keySession) {
  21435. licenseStatus.emit('error', new Error('invalid state'));
  21436. return;
  21437. }
  21438. const {
  21439. messageType,
  21440. message
  21441. } = event;
  21442. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  21443. if (messageType === 'license-request' || messageType === 'license-renewal') {
  21444. this.renewLicense(context, message).catch(error => {
  21445. if (licenseStatus.eventNames().length) {
  21446. licenseStatus.emit('error', error);
  21447. } else {
  21448. this.handleError(error);
  21449. }
  21450. });
  21451. } else if (messageType === 'license-release') {
  21452. if (context.keySystem === KeySystems.FAIRPLAY) {
  21453. this.updateKeySession(context, strToUtf8array('acknowledged'));
  21454. this.removeSession(context);
  21455. }
  21456. } else {
  21457. this.warn(`unhandled media key message type "${messageType}"`);
  21458. }
  21459. };
  21460. const onkeystatuseschange = context._onkeystatuseschange = event => {
  21461. const keySession = context.mediaKeysSession;
  21462. if (!keySession) {
  21463. licenseStatus.emit('error', new Error('invalid state'));
  21464. return;
  21465. }
  21466. this.onKeyStatusChange(context);
  21467. const keyStatus = context.keyStatus;
  21468. licenseStatus.emit('keyStatus', keyStatus);
  21469. if (keyStatus === 'expired') {
  21470. this.warn(`${context.keySystem} expired for key ${keyId}`);
  21471. this.renewKeySession(context);
  21472. }
  21473. };
  21474. addEventListener(context.mediaKeysSession, 'message', onmessage);
  21475. addEventListener(context.mediaKeysSession, 'keystatuseschange', onkeystatuseschange);
  21476. const keyUsablePromise = new Promise((resolve, reject) => {
  21477. licenseStatus.on('error', reject);
  21478. licenseStatus.on('keyStatus', keyStatus => {
  21479. if (keyStatus.startsWith('usable')) {
  21480. resolve();
  21481. } else if (keyStatus === 'output-restricted') {
  21482. reject(new EMEKeyError({
  21483. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21484. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  21485. fatal: false
  21486. }, 'HDCP level output restricted'));
  21487. } else if (keyStatus === 'internal-error') {
  21488. reject(new EMEKeyError({
  21489. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21490. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  21491. fatal: true
  21492. }, `key status changed to "${keyStatus}"`));
  21493. } else if (keyStatus === 'expired') {
  21494. reject(new Error('key expired while generating request'));
  21495. } else {
  21496. this.warn(`unhandled key status change "${keyStatus}"`);
  21497. }
  21498. });
  21499. });
  21500. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  21501. var _context$mediaKeysSes;
  21502. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  21503. }).catch(error => {
  21504. throw new EMEKeyError({
  21505. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21506. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  21507. error,
  21508. fatal: false
  21509. }, `Error generating key-session request: ${error}`);
  21510. }).then(() => keyUsablePromise).catch(error => {
  21511. licenseStatus.removeAllListeners();
  21512. this.removeSession(context);
  21513. throw error;
  21514. }).then(() => {
  21515. licenseStatus.removeAllListeners();
  21516. return context;
  21517. });
  21518. }
  21519. onKeyStatusChange(mediaKeySessionContext) {
  21520. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status, keyId) => {
  21521. // keyStatuses.forEach is not standard API so the callback value looks weird on xboxone
  21522. // xboxone callback(keyId, status) so we need to exchange them
  21523. if (typeof keyId === 'string' && typeof status === 'object') {
  21524. const temp = keyId;
  21525. keyId = status;
  21526. status = temp;
  21527. }
  21528. this.log(`key status change "${status}" for keyStatuses keyId: ${Hex.hexDump('buffer' in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`);
  21529. mediaKeySessionContext.keyStatus = status;
  21530. });
  21531. }
  21532. fetchServerCertificate(keySystem) {
  21533. const config = this.config;
  21534. const Loader = config.loader;
  21535. const certLoader = new Loader(config);
  21536. const url = this.getServerCertificateUrl(keySystem);
  21537. if (!url) {
  21538. return Promise.resolve();
  21539. }
  21540. this.log(`Fetching server certificate for "${keySystem}"`);
  21541. return new Promise((resolve, reject) => {
  21542. const loaderContext = {
  21543. responseType: 'arraybuffer',
  21544. url
  21545. };
  21546. const loadPolicy = config.certLoadPolicy.default;
  21547. const loaderConfig = {
  21548. loadPolicy,
  21549. timeout: loadPolicy.maxLoadTimeMs,
  21550. maxRetry: 0,
  21551. retryDelay: 0,
  21552. maxRetryDelay: 0
  21553. };
  21554. const loaderCallbacks = {
  21555. onSuccess: (response, stats, context, networkDetails) => {
  21556. resolve(response.data);
  21557. },
  21558. onError: (response, contex, networkDetails, stats) => {
  21559. reject(new EMEKeyError({
  21560. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21561. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  21562. fatal: true,
  21563. networkDetails,
  21564. response: _objectSpread2({
  21565. url: loaderContext.url,
  21566. data: undefined
  21567. }, response)
  21568. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  21569. },
  21570. onTimeout: (stats, context, networkDetails) => {
  21571. reject(new EMEKeyError({
  21572. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21573. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  21574. fatal: true,
  21575. networkDetails,
  21576. response: {
  21577. url: loaderContext.url,
  21578. data: undefined
  21579. }
  21580. }, `"${keySystem}" certificate request timed out (${url})`));
  21581. },
  21582. onAbort: (stats, context, networkDetails) => {
  21583. reject(new Error('aborted'));
  21584. }
  21585. };
  21586. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  21587. });
  21588. }
  21589. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  21590. return new Promise((resolve, reject) => {
  21591. mediaKeys.setServerCertificate(cert).then(success => {
  21592. this.log(`setServerCertificate ${success ? 'success' : 'not supported by CDM'} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  21593. resolve(mediaKeys);
  21594. }).catch(error => {
  21595. reject(new EMEKeyError({
  21596. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21597. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  21598. error,
  21599. fatal: true
  21600. }, error.message));
  21601. });
  21602. });
  21603. }
  21604. renewLicense(context, keyMessage) {
  21605. return this.requestLicense(context, new Uint8Array(keyMessage)).then(data => {
  21606. return this.updateKeySession(context, new Uint8Array(data)).catch(error => {
  21607. throw new EMEKeyError({
  21608. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21609. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  21610. error,
  21611. fatal: true
  21612. }, error.message);
  21613. });
  21614. });
  21615. }
  21616. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  21617. // On Edge, the raw license message is UTF-16-encoded XML. We need
  21618. // to unpack the Challenge element (base64-encoded string containing the
  21619. // actual license request) and any HttpHeader elements (sent as request
  21620. // headers).
  21621. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  21622. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  21623. if (!xmlString.includes('PlayReadyKeyMessage')) {
  21624. // This does not appear to be a wrapped message as on Edge. Some
  21625. // clients do not need this unwrapping, so we will assume this is one of
  21626. // them. Note that "xml" at this point probably looks like random
  21627. // garbage, since we interpreted UTF-8 as UTF-16.
  21628. xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
  21629. return licenseChallenge;
  21630. }
  21631. const keyMessageXml = new DOMParser().parseFromString(xmlString, 'application/xml');
  21632. // Set request headers.
  21633. const headers = keyMessageXml.querySelectorAll('HttpHeader');
  21634. if (headers.length > 0) {
  21635. let header;
  21636. for (let i = 0, len = headers.length; i < len; i++) {
  21637. var _header$querySelector, _header$querySelector2;
  21638. header = headers[i];
  21639. const name = (_header$querySelector = header.querySelector('name')) == null ? void 0 : _header$querySelector.textContent;
  21640. const value = (_header$querySelector2 = header.querySelector('value')) == null ? void 0 : _header$querySelector2.textContent;
  21641. if (name && value) {
  21642. xhr.setRequestHeader(name, value);
  21643. }
  21644. }
  21645. }
  21646. const challengeElement = keyMessageXml.querySelector('Challenge');
  21647. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  21648. if (!challengeText) {
  21649. throw new Error(`Cannot find <Challenge> in key message`);
  21650. }
  21651. return strToUtf8array(atob(challengeText));
  21652. }
  21653. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  21654. const licenseXhrSetup = this.config.licenseXhrSetup;
  21655. if (!licenseXhrSetup) {
  21656. xhr.open('POST', url, true);
  21657. return Promise.resolve({
  21658. xhr,
  21659. licenseChallenge
  21660. });
  21661. }
  21662. return Promise.resolve().then(() => {
  21663. if (!keysListItem.decryptdata) {
  21664. throw new Error('Key removed');
  21665. }
  21666. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  21667. }).catch(error => {
  21668. if (!keysListItem.decryptdata) {
  21669. // Key session removed. Cancel license request.
  21670. throw error;
  21671. }
  21672. // let's try to open before running setup
  21673. xhr.open('POST', url, true);
  21674. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  21675. }).then(licenseXhrSetupResult => {
  21676. // if licenseXhrSetup did not yet call open, let's do it now
  21677. if (!xhr.readyState) {
  21678. xhr.open('POST', url, true);
  21679. }
  21680. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  21681. return {
  21682. xhr,
  21683. licenseChallenge: finalLicenseChallenge
  21684. };
  21685. });
  21686. }
  21687. requestLicense(keySessionContext, licenseChallenge) {
  21688. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  21689. return new Promise((resolve, reject) => {
  21690. const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  21691. this.log(`Sending license request to URL: ${url}`);
  21692. const xhr = new XMLHttpRequest();
  21693. xhr.responseType = 'arraybuffer';
  21694. xhr.onreadystatechange = () => {
  21695. if (!this.hls || !keySessionContext.mediaKeysSession) {
  21696. return reject(new Error('invalid state'));
  21697. }
  21698. if (xhr.readyState === 4) {
  21699. if (xhr.status === 200) {
  21700. this._requestLicenseFailureCount = 0;
  21701. let data = xhr.response;
  21702. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  21703. const licenseResponseCallback = this.config.licenseResponseCallback;
  21704. if (licenseResponseCallback) {
  21705. try {
  21706. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  21707. } catch (error) {
  21708. this.error(error);
  21709. }
  21710. }
  21711. resolve(data);
  21712. } else {
  21713. const retryConfig = keyLoadPolicy.errorRetry;
  21714. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  21715. this._requestLicenseFailureCount++;
  21716. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  21717. reject(new EMEKeyError({
  21718. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21719. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  21720. fatal: true,
  21721. networkDetails: xhr,
  21722. response: {
  21723. url,
  21724. data: undefined,
  21725. code: xhr.status,
  21726. text: xhr.statusText
  21727. }
  21728. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  21729. } else {
  21730. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  21731. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  21732. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  21733. }
  21734. }
  21735. }
  21736. };
  21737. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  21738. keySessionContext.licenseXhr.abort();
  21739. }
  21740. keySessionContext.licenseXhr = xhr;
  21741. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  21742. xhr,
  21743. licenseChallenge
  21744. }) => {
  21745. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  21746. licenseChallenge = this.unpackPlayReadyKeyMessage(xhr, licenseChallenge);
  21747. }
  21748. xhr.send(licenseChallenge);
  21749. });
  21750. });
  21751. }
  21752. onDestroying() {
  21753. this.unregisterListeners();
  21754. this._clear();
  21755. }
  21756. onMediaAttached(event, data) {
  21757. if (!this.config.emeEnabled) {
  21758. return;
  21759. }
  21760. const media = data.media;
  21761. // keep reference of media
  21762. this.media = media;
  21763. addEventListener(media, 'waitingforkey', this.onWaitingForKey);
  21764. }
  21765. onMediaDetached() {
  21766. const media = this.media;
  21767. if (media) {
  21768. removeEventListener(media, 'waitingforkey', this.onWaitingForKey);
  21769. this.media = null;
  21770. this.mediaKeys = null;
  21771. }
  21772. }
  21773. _clear() {
  21774. var _media$setMediaKeys;
  21775. this._requestLicenseFailureCount = 0;
  21776. this.keyIdToKeySessionPromise = {};
  21777. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  21778. return;
  21779. }
  21780. const media = this.media;
  21781. const mediaKeysList = this.mediaKeySessions.slice();
  21782. this.mediaKeySessions = [];
  21783. this.mediaKeys = null;
  21784. LevelKey.clearKeyUriToKeyIdMap();
  21785. // Close all sessions and remove media keys from the video element.
  21786. const keySessionCount = mediaKeysList.length;
  21787. EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map(mediaKeySessionContext => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch(error => {
  21788. var _this$hls2;
  21789. this.log(`Could not clear media keys: ${error}`);
  21790. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {
  21791. type: ErrorTypes.OTHER_ERROR,
  21792. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  21793. fatal: false,
  21794. error: new Error(`Could not clear media keys: ${error}`)
  21795. });
  21796. }))).catch(error => {
  21797. var _this$hls3;
  21798. this.log(`Could not close sessions and clear media keys: ${error}`);
  21799. (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {
  21800. type: ErrorTypes.OTHER_ERROR,
  21801. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  21802. fatal: false,
  21803. error: new Error(`Could not close sessions and clear media keys: ${error}`)
  21804. });
  21805. }).then(() => {
  21806. if (keySessionCount) {
  21807. this.log('finished closing key sessions and clearing media keys');
  21808. }
  21809. });
  21810. }
  21811. onManifestLoading() {
  21812. this.keyFormatPromise = null;
  21813. }
  21814. onManifestLoaded(event, {
  21815. sessionKeys
  21816. }) {
  21817. if (!sessionKeys || !this.config.emeEnabled) {
  21818. return;
  21819. }
  21820. if (!this.keyFormatPromise) {
  21821. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  21822. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  21823. formats.push(sessionKey.keyFormat);
  21824. }
  21825. return formats;
  21826. }, []);
  21827. this.log(`Selecting key-system from session-keys ${keyFormats.join(', ')}`);
  21828. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  21829. }
  21830. }
  21831. removeSession(mediaKeySessionContext) {
  21832. const {
  21833. mediaKeysSession,
  21834. licenseXhr
  21835. } = mediaKeySessionContext;
  21836. if (mediaKeysSession) {
  21837. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  21838. if (mediaKeySessionContext._onmessage) {
  21839. mediaKeysSession.removeEventListener('message', mediaKeySessionContext._onmessage);
  21840. mediaKeySessionContext._onmessage = undefined;
  21841. }
  21842. if (mediaKeySessionContext._onkeystatuseschange) {
  21843. mediaKeysSession.removeEventListener('keystatuseschange', mediaKeySessionContext._onkeystatuseschange);
  21844. mediaKeySessionContext._onkeystatuseschange = undefined;
  21845. }
  21846. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  21847. licenseXhr.abort();
  21848. }
  21849. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = undefined;
  21850. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  21851. if (index > -1) {
  21852. this.mediaKeySessions.splice(index, 1);
  21853. }
  21854. const {
  21855. drmSystemOptions
  21856. } = this.config;
  21857. const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {
  21858. self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8000);
  21859. mediaKeysSession.remove().then(resolve);
  21860. }) : Promise.resolve();
  21861. return removePromise.catch(error => {
  21862. var _this$hls4;
  21863. this.log(`Could not remove session: ${error}`);
  21864. (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {
  21865. type: ErrorTypes.OTHER_ERROR,
  21866. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  21867. fatal: false,
  21868. error: new Error(`Could not remove session: ${error}`)
  21869. });
  21870. }).then(() => {
  21871. return mediaKeysSession.close();
  21872. }).catch(error => {
  21873. var _this$hls5;
  21874. this.log(`Could not close session: ${error}`);
  21875. (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {
  21876. type: ErrorTypes.OTHER_ERROR,
  21877. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  21878. fatal: false,
  21879. error: new Error(`Could not close session: ${error}`)
  21880. });
  21881. });
  21882. }
  21883. }
  21884. }
  21885. EMEController.CDMCleanupPromise = void 0;
  21886. class EMEKeyError extends Error {
  21887. constructor(data, message) {
  21888. super(message);
  21889. this.data = void 0;
  21890. data.error || (data.error = new Error(message));
  21891. this.data = data;
  21892. data.err = data.error;
  21893. }
  21894. }
  21895. class FPSController {
  21896. constructor(hls) {
  21897. this.hls = void 0;
  21898. this.isVideoPlaybackQualityAvailable = false;
  21899. this.timer = void 0;
  21900. this.media = null;
  21901. this.lastTime = void 0;
  21902. this.lastDroppedFrames = 0;
  21903. this.lastDecodedFrames = 0;
  21904. // stream controller must be provided as a dependency!
  21905. this.streamController = void 0;
  21906. this.hls = hls;
  21907. this.registerListeners();
  21908. }
  21909. setStreamController(streamController) {
  21910. this.streamController = streamController;
  21911. }
  21912. registerListeners() {
  21913. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21914. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21915. }
  21916. unregisterListeners() {
  21917. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21918. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21919. }
  21920. destroy() {
  21921. if (this.timer) {
  21922. clearInterval(this.timer);
  21923. }
  21924. this.unregisterListeners();
  21925. this.isVideoPlaybackQualityAvailable = false;
  21926. this.media = null;
  21927. }
  21928. onMediaAttaching(event, data) {
  21929. const config = this.hls.config;
  21930. if (config.capLevelOnFPSDrop) {
  21931. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  21932. this.media = media;
  21933. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  21934. this.isVideoPlaybackQualityAvailable = true;
  21935. }
  21936. self.clearInterval(this.timer);
  21937. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  21938. }
  21939. }
  21940. onMediaDetaching() {
  21941. this.media = null;
  21942. }
  21943. checkFPS(video, decodedFrames, droppedFrames) {
  21944. const currentTime = performance.now();
  21945. if (decodedFrames) {
  21946. if (this.lastTime) {
  21947. const currentPeriod = currentTime - this.lastTime;
  21948. const currentDropped = droppedFrames - this.lastDroppedFrames;
  21949. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  21950. const droppedFPS = 1000 * currentDropped / currentPeriod;
  21951. const hls = this.hls;
  21952. hls.trigger(Events.FPS_DROP, {
  21953. currentDropped: currentDropped,
  21954. currentDecoded: currentDecoded,
  21955. totalDroppedFrames: droppedFrames
  21956. });
  21957. if (droppedFPS > 0) {
  21958. // hls.logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  21959. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  21960. let currentLevel = hls.currentLevel;
  21961. hls.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  21962. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  21963. currentLevel = currentLevel - 1;
  21964. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  21965. level: currentLevel,
  21966. droppedLevel: hls.currentLevel
  21967. });
  21968. hls.autoLevelCapping = currentLevel;
  21969. this.streamController.nextLevelSwitch();
  21970. }
  21971. }
  21972. }
  21973. }
  21974. this.lastTime = currentTime;
  21975. this.lastDroppedFrames = droppedFrames;
  21976. this.lastDecodedFrames = decodedFrames;
  21977. }
  21978. }
  21979. checkFPSInterval() {
  21980. const video = this.media;
  21981. if (video) {
  21982. if (this.isVideoPlaybackQualityAvailable) {
  21983. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  21984. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  21985. } else {
  21986. // HTMLVideoElement doesn't include the webkit types
  21987. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  21988. }
  21989. }
  21990. }
  21991. }
  21992. function sendAddTrackEvent(track, videoEl) {
  21993. let event;
  21994. try {
  21995. event = new Event('addtrack');
  21996. } catch (err) {
  21997. // for IE11
  21998. event = document.createEvent('Event');
  21999. event.initEvent('addtrack', false, false);
  22000. }
  22001. event.track = track;
  22002. videoEl.dispatchEvent(event);
  22003. }
  22004. function addCueToTrack(track, cue) {
  22005. // Sometimes there are cue overlaps on segmented vtts so the same
  22006. // cue can appear more than once in different vtt files.
  22007. // This avoid showing duplicated cues with same timecode and text.
  22008. const mode = track.mode;
  22009. if (mode === 'disabled') {
  22010. track.mode = 'hidden';
  22011. }
  22012. if (track.cues && !track.cues.getCueById(cue.id)) {
  22013. try {
  22014. track.addCue(cue);
  22015. if (!track.cues.getCueById(cue.id)) {
  22016. throw new Error(`addCue is failed for: ${cue}`);
  22017. }
  22018. } catch (err) {
  22019. logger.debug(`[texttrack-utils]: ${err}`);
  22020. try {
  22021. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  22022. textTrackCue.id = cue.id;
  22023. track.addCue(textTrackCue);
  22024. } catch (err2) {
  22025. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  22026. }
  22027. }
  22028. }
  22029. if (mode === 'disabled') {
  22030. track.mode = mode;
  22031. }
  22032. }
  22033. function clearCurrentCues(track, enterHandler) {
  22034. // When track.mode is disabled, track.cues will be null.
  22035. // To guarantee the removal of cues, we need to temporarily
  22036. // change the mode to hidden
  22037. const mode = track.mode;
  22038. if (mode === 'disabled') {
  22039. track.mode = 'hidden';
  22040. }
  22041. if (track.cues) {
  22042. for (let i = track.cues.length; i--;) {
  22043. if (enterHandler) {
  22044. track.cues[i].removeEventListener('enter', enterHandler);
  22045. }
  22046. track.removeCue(track.cues[i]);
  22047. }
  22048. }
  22049. if (mode === 'disabled') {
  22050. track.mode = mode;
  22051. }
  22052. }
  22053. function removeCuesInRange(track, start, end, predicate) {
  22054. const mode = track.mode;
  22055. if (mode === 'disabled') {
  22056. track.mode = 'hidden';
  22057. }
  22058. if (track.cues && track.cues.length > 0) {
  22059. const cues = getCuesInRange(track.cues, start, end);
  22060. for (let i = 0; i < cues.length; i++) {
  22061. if (!predicate || predicate(cues[i])) {
  22062. track.removeCue(cues[i]);
  22063. }
  22064. }
  22065. }
  22066. if (mode === 'disabled') {
  22067. track.mode = mode;
  22068. }
  22069. }
  22070. // Find first cue starting at or after given time.
  22071. // Modified version of binary search O(log(n)).
  22072. function getFirstCueIndexFromTime(cues, time) {
  22073. // If first cue starts at or after time, start there
  22074. if (time <= cues[0].startTime) {
  22075. return 0;
  22076. }
  22077. // If the last cue ends before time there is no overlap
  22078. const len = cues.length - 1;
  22079. if (time > cues[len].endTime) {
  22080. return -1;
  22081. }
  22082. let left = 0;
  22083. let right = len;
  22084. let mid;
  22085. while (left <= right) {
  22086. mid = Math.floor((right + left) / 2);
  22087. if (time < cues[mid].startTime) {
  22088. right = mid - 1;
  22089. } else if (time > cues[mid].startTime && left < len) {
  22090. left = mid + 1;
  22091. } else {
  22092. // If it's not lower or higher, it must be equal.
  22093. return mid;
  22094. }
  22095. }
  22096. // At this point, left and right have swapped.
  22097. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  22098. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  22099. }
  22100. function getCuesInRange(cues, start, end) {
  22101. const cuesFound = [];
  22102. const firstCueInRange = getFirstCueIndexFromTime(cues, start);
  22103. if (firstCueInRange > -1) {
  22104. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  22105. const cue = cues[i];
  22106. if (cue.startTime >= start && cue.endTime <= end) {
  22107. cuesFound.push(cue);
  22108. } else if (cue.startTime > end) {
  22109. return cuesFound;
  22110. }
  22111. }
  22112. }
  22113. return cuesFound;
  22114. }
  22115. function filterSubtitleTracks(textTrackList) {
  22116. const tracks = [];
  22117. for (let i = 0; i < textTrackList.length; i++) {
  22118. const track = textTrackList[i];
  22119. // Edge adds a track without a label; we don't want to use it
  22120. if ((track.kind === 'subtitles' || track.kind === 'captions') && track.label) {
  22121. tracks.push(textTrackList[i]);
  22122. }
  22123. }
  22124. return tracks;
  22125. }
  22126. class SubtitleTrackController extends BasePlaylistController {
  22127. constructor(hls) {
  22128. super(hls, 'subtitle-track-controller');
  22129. this.media = null;
  22130. this.tracks = [];
  22131. this.groupIds = null;
  22132. this.tracksInGroup = [];
  22133. this.trackId = -1;
  22134. this.currentTrack = null;
  22135. this.selectDefaultTrack = true;
  22136. this.queuedDefaultTrack = -1;
  22137. this.useTextTrackPolling = false;
  22138. this.subtitlePollingInterval = -1;
  22139. this._subtitleDisplay = true;
  22140. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  22141. this.onTextTracksChanged = () => {
  22142. if (!this.useTextTrackPolling) {
  22143. self.clearInterval(this.subtitlePollingInterval);
  22144. }
  22145. // Media is undefined when switching streams via loadSource()
  22146. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  22147. return;
  22148. }
  22149. let textTrack = null;
  22150. const tracks = filterSubtitleTracks(this.media.textTracks);
  22151. for (let i = 0; i < tracks.length; i++) {
  22152. if (tracks[i].mode === 'hidden') {
  22153. // Do not break in case there is a following track with showing.
  22154. textTrack = tracks[i];
  22155. } else if (tracks[i].mode === 'showing') {
  22156. textTrack = tracks[i];
  22157. break;
  22158. }
  22159. }
  22160. // Find internal track index for TextTrack
  22161. const trackId = this.findTrackForTextTrack(textTrack);
  22162. if (this.subtitleTrack !== trackId) {
  22163. this.setSubtitleTrack(trackId);
  22164. }
  22165. };
  22166. this.registerListeners();
  22167. }
  22168. destroy() {
  22169. this.unregisterListeners();
  22170. this.tracks.length = 0;
  22171. this.tracksInGroup.length = 0;
  22172. this.currentTrack = null;
  22173. // @ts-ignore
  22174. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  22175. super.destroy();
  22176. }
  22177. get subtitleDisplay() {
  22178. return this._subtitleDisplay;
  22179. }
  22180. set subtitleDisplay(value) {
  22181. this._subtitleDisplay = value;
  22182. if (this.trackId > -1) {
  22183. this.toggleTrackModes();
  22184. }
  22185. }
  22186. registerListeners() {
  22187. const {
  22188. hls
  22189. } = this;
  22190. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  22191. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22192. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22193. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  22194. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  22195. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  22196. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  22197. hls.on(Events.ERROR, this.onError, this);
  22198. }
  22199. unregisterListeners() {
  22200. const {
  22201. hls
  22202. } = this;
  22203. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  22204. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22205. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22206. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  22207. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  22208. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  22209. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  22210. hls.off(Events.ERROR, this.onError, this);
  22211. }
  22212. // Listen for subtitle track change, then extract the current track ID.
  22213. onMediaAttached(event, data) {
  22214. this.media = data.media;
  22215. if (!this.media) {
  22216. return;
  22217. }
  22218. if (this.queuedDefaultTrack > -1) {
  22219. this.subtitleTrack = this.queuedDefaultTrack;
  22220. this.queuedDefaultTrack = -1;
  22221. }
  22222. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  22223. if (this.useTextTrackPolling) {
  22224. this.pollTrackChange(500);
  22225. } else {
  22226. this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
  22227. }
  22228. }
  22229. pollTrackChange(timeout) {
  22230. self.clearInterval(this.subtitlePollingInterval);
  22231. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  22232. }
  22233. onMediaDetaching(event, data) {
  22234. const media = this.media;
  22235. if (!media) {
  22236. return;
  22237. }
  22238. const transferringMedia = !!data.transferMedia;
  22239. self.clearInterval(this.subtitlePollingInterval);
  22240. if (!this.useTextTrackPolling) {
  22241. media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
  22242. }
  22243. if (this.trackId > -1) {
  22244. this.queuedDefaultTrack = this.trackId;
  22245. }
  22246. // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
  22247. this.subtitleTrack = -1;
  22248. this.media = null;
  22249. if (transferringMedia) {
  22250. return;
  22251. }
  22252. const textTracks = filterSubtitleTracks(media.textTracks);
  22253. // Clear loaded cues on media detachment from tracks
  22254. textTracks.forEach(track => {
  22255. clearCurrentCues(track);
  22256. });
  22257. }
  22258. onManifestLoading() {
  22259. this.tracks = [];
  22260. this.groupIds = null;
  22261. this.tracksInGroup = [];
  22262. this.trackId = -1;
  22263. this.currentTrack = null;
  22264. this.selectDefaultTrack = true;
  22265. }
  22266. // Fired whenever a new manifest is loaded.
  22267. onManifestParsed(event, data) {
  22268. this.tracks = data.subtitleTracks;
  22269. }
  22270. onSubtitleTrackLoaded(event, data) {
  22271. const {
  22272. id,
  22273. groupId,
  22274. details
  22275. } = data;
  22276. const trackInActiveGroup = this.tracksInGroup[id];
  22277. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  22278. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  22279. return;
  22280. }
  22281. const curDetails = trackInActiveGroup.details;
  22282. trackInActiveGroup.details = data.details;
  22283. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  22284. if (id === this.trackId) {
  22285. this.playlistLoaded(id, data, curDetails);
  22286. }
  22287. }
  22288. onLevelLoading(event, data) {
  22289. this.switchLevel(data.level);
  22290. }
  22291. onLevelSwitching(event, data) {
  22292. this.switchLevel(data.level);
  22293. }
  22294. switchLevel(levelIndex) {
  22295. const levelInfo = this.hls.levels[levelIndex];
  22296. if (!levelInfo) {
  22297. return;
  22298. }
  22299. const subtitleGroups = levelInfo.subtitleGroups || null;
  22300. const currentGroups = this.groupIds;
  22301. let currentTrack = this.currentTrack;
  22302. if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some(groupId => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {
  22303. this.groupIds = subtitleGroups;
  22304. this.trackId = -1;
  22305. this.currentTrack = null;
  22306. const subtitleTracks = this.tracks.filter(track => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  22307. if (subtitleTracks.length) {
  22308. // Disable selectDefaultTrack if there are no default tracks
  22309. if (this.selectDefaultTrack && !subtitleTracks.some(track => track.default)) {
  22310. this.selectDefaultTrack = false;
  22311. }
  22312. // track.id should match hls.audioTracks index
  22313. subtitleTracks.forEach((track, i) => {
  22314. track.id = i;
  22315. });
  22316. } else if (!currentTrack && !this.tracksInGroup.length) {
  22317. // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks
  22318. return;
  22319. }
  22320. this.tracksInGroup = subtitleTracks;
  22321. // Find preferred track
  22322. const subtitlePreference = this.hls.config.subtitlePreference;
  22323. if (!currentTrack && subtitlePreference) {
  22324. this.selectDefaultTrack = false;
  22325. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  22326. if (groupIndex > -1) {
  22327. currentTrack = subtitleTracks[groupIndex];
  22328. } else {
  22329. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  22330. currentTrack = this.tracks[allIndex];
  22331. }
  22332. }
  22333. // Select initial track
  22334. let trackId = this.findTrackId(currentTrack);
  22335. if (trackId === -1 && currentTrack) {
  22336. trackId = this.findTrackId(null);
  22337. }
  22338. // Dispatch events and load track if needed
  22339. const subtitleTracksUpdated = {
  22340. subtitleTracks
  22341. };
  22342. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(',')}" group-id`);
  22343. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  22344. if (trackId !== -1 && this.trackId === -1) {
  22345. this.setSubtitleTrack(trackId);
  22346. }
  22347. }
  22348. }
  22349. findTrackId(currentTrack) {
  22350. const tracks = this.tracksInGroup;
  22351. const selectDefault = this.selectDefaultTrack;
  22352. for (let i = 0; i < tracks.length; i++) {
  22353. const track = tracks[i];
  22354. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  22355. continue;
  22356. }
  22357. if (!currentTrack || matchesOption(track, currentTrack)) {
  22358. return i;
  22359. }
  22360. }
  22361. if (currentTrack) {
  22362. for (let i = 0; i < tracks.length; i++) {
  22363. const track = tracks[i];
  22364. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  22365. return i;
  22366. }
  22367. }
  22368. for (let i = 0; i < tracks.length; i++) {
  22369. const track = tracks[i];
  22370. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  22371. return i;
  22372. }
  22373. }
  22374. }
  22375. return -1;
  22376. }
  22377. findTrackForTextTrack(textTrack) {
  22378. if (textTrack) {
  22379. const tracks = this.tracksInGroup;
  22380. for (let i = 0; i < tracks.length; i++) {
  22381. const track = tracks[i];
  22382. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  22383. return i;
  22384. }
  22385. }
  22386. }
  22387. return -1;
  22388. }
  22389. onError(event, data) {
  22390. if (data.fatal || !data.context) {
  22391. return;
  22392. }
  22393. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  22394. this.checkRetry(data);
  22395. }
  22396. }
  22397. get allSubtitleTracks() {
  22398. return this.tracks;
  22399. }
  22400. /** get alternate subtitle tracks list from playlist **/
  22401. get subtitleTracks() {
  22402. return this.tracksInGroup;
  22403. }
  22404. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  22405. get subtitleTrack() {
  22406. return this.trackId;
  22407. }
  22408. set subtitleTrack(newId) {
  22409. this.selectDefaultTrack = false;
  22410. this.setSubtitleTrack(newId);
  22411. }
  22412. setSubtitleOption(subtitleOption) {
  22413. this.hls.config.subtitlePreference = subtitleOption;
  22414. if (subtitleOption) {
  22415. if (subtitleOption.id === -1) {
  22416. this.setSubtitleTrack(-1);
  22417. return null;
  22418. }
  22419. const allSubtitleTracks = this.allSubtitleTracks;
  22420. this.selectDefaultTrack = false;
  22421. if (allSubtitleTracks.length) {
  22422. // First see if current option matches (no switch op)
  22423. const currentTrack = this.currentTrack;
  22424. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  22425. return currentTrack;
  22426. }
  22427. // Find option in current group
  22428. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  22429. if (groupIndex > -1) {
  22430. const track = this.tracksInGroup[groupIndex];
  22431. this.setSubtitleTrack(groupIndex);
  22432. return track;
  22433. } else if (currentTrack) {
  22434. // If this is not the initial selection return null
  22435. // option should have matched one in active group
  22436. return null;
  22437. } else {
  22438. // Find the option in all tracks for initial selection
  22439. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  22440. if (allIndex > -1) {
  22441. return allSubtitleTracks[allIndex];
  22442. }
  22443. }
  22444. }
  22445. }
  22446. return null;
  22447. }
  22448. loadPlaylist(hlsUrlParameters) {
  22449. super.loadPlaylist();
  22450. if (this.shouldLoadPlaylist(this.currentTrack)) {
  22451. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  22452. }
  22453. }
  22454. loadingPlaylist(currentTrack, hlsUrlParameters) {
  22455. super.loadingPlaylist(currentTrack, hlsUrlParameters);
  22456. const id = currentTrack.id;
  22457. const groupId = currentTrack.groupId;
  22458. const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  22459. const details = currentTrack.details;
  22460. const age = details == null ? void 0 : details.age;
  22461. this.log(`Loading subtitle ${id} "${currentTrack.name}" lang:${currentTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);
  22462. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  22463. url,
  22464. id,
  22465. groupId,
  22466. deliveryDirectives: hlsUrlParameters || null,
  22467. track: currentTrack
  22468. });
  22469. }
  22470. /**
  22471. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  22472. * This operates on the DOM textTracks.
  22473. * A value of -1 will disable all subtitle tracks.
  22474. */
  22475. toggleTrackModes() {
  22476. const {
  22477. media
  22478. } = this;
  22479. if (!media) {
  22480. return;
  22481. }
  22482. const textTracks = filterSubtitleTracks(media.textTracks);
  22483. const currentTrack = this.currentTrack;
  22484. let nextTrack;
  22485. if (currentTrack) {
  22486. nextTrack = textTracks.filter(textTrack => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  22487. if (!nextTrack) {
  22488. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  22489. }
  22490. }
  22491. [].slice.call(textTracks).forEach(track => {
  22492. if (track.mode !== 'disabled' && track !== nextTrack) {
  22493. track.mode = 'disabled';
  22494. }
  22495. });
  22496. if (nextTrack) {
  22497. const mode = this.subtitleDisplay ? 'showing' : 'hidden';
  22498. if (nextTrack.mode !== mode) {
  22499. nextTrack.mode = mode;
  22500. }
  22501. }
  22502. }
  22503. /**
  22504. * This method is responsible for validating the subtitle index and periodically reloading if live.
  22505. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  22506. */
  22507. setSubtitleTrack(newId) {
  22508. const tracks = this.tracksInGroup;
  22509. // setting this.subtitleTrack will trigger internal logic
  22510. // if media has not been attached yet, it will fail
  22511. // we keep a reference to the default track id
  22512. // and we'll set subtitleTrack when onMediaAttached is triggered
  22513. if (!this.media) {
  22514. this.queuedDefaultTrack = newId;
  22515. return;
  22516. }
  22517. // exit if track id as already set or invalid
  22518. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  22519. this.warn(`Invalid subtitle track id: ${newId}`);
  22520. return;
  22521. }
  22522. this.selectDefaultTrack = false;
  22523. const lastTrack = this.currentTrack;
  22524. const track = tracks[newId] || null;
  22525. this.trackId = newId;
  22526. this.currentTrack = track;
  22527. this.toggleTrackModes();
  22528. if (!track) {
  22529. // switch to -1
  22530. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  22531. id: newId
  22532. });
  22533. return;
  22534. }
  22535. const trackLoaded = !!track.details && !track.details.live;
  22536. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  22537. return;
  22538. }
  22539. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ''));
  22540. const {
  22541. id,
  22542. groupId = '',
  22543. name,
  22544. type,
  22545. url
  22546. } = track;
  22547. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  22548. id,
  22549. groupId,
  22550. name,
  22551. type,
  22552. url
  22553. });
  22554. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  22555. this.loadPlaylist(hlsUrlParameters);
  22556. }
  22557. }
  22558. /**
  22559. * Generate a random v4 UUID
  22560. *
  22561. * @returns A random v4 UUID
  22562. *
  22563. * @group Utils
  22564. *
  22565. * @beta
  22566. */
  22567. function uuid() {
  22568. try {
  22569. return crypto.randomUUID();
  22570. } catch (error) {
  22571. try {
  22572. const url = URL.createObjectURL(new Blob());
  22573. const uuid = url.toString();
  22574. URL.revokeObjectURL(url);
  22575. return uuid.slice(uuid.lastIndexOf('/') + 1);
  22576. } catch (error) {
  22577. let dt = new Date().getTime();
  22578. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  22579. const r = (dt + Math.random() * 16) % 16 | 0;
  22580. dt = Math.floor(dt / 16);
  22581. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  22582. });
  22583. return uuid;
  22584. }
  22585. }
  22586. }
  22587. // From https://github.com/darkskyapp/string-hash
  22588. function hash(text) {
  22589. let hash = 5381;
  22590. let i = text.length;
  22591. while (i) {
  22592. hash = hash * 33 ^ text.charCodeAt(--i);
  22593. }
  22594. return (hash >>> 0).toString();
  22595. }
  22596. const ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  22597. let TimelineOccupancy = /*#__PURE__*/function (TimelineOccupancy) {
  22598. TimelineOccupancy[TimelineOccupancy["Point"] = 0] = "Point";
  22599. TimelineOccupancy[TimelineOccupancy["Range"] = 1] = "Range";
  22600. return TimelineOccupancy;
  22601. }({});
  22602. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  22603. return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;
  22604. }
  22605. class InterstitialEvent {
  22606. constructor(dateRange, base) {
  22607. this.base = void 0;
  22608. this._duration = null;
  22609. this._timelineStart = null;
  22610. this.appendInPlaceDisabled = void 0;
  22611. this.appendInPlaceStarted = void 0;
  22612. this.dateRange = void 0;
  22613. this.hasPlayed = false;
  22614. this.cumulativeDuration = 0;
  22615. this.resumeOffset = NaN;
  22616. this.playoutLimit = NaN;
  22617. this.restrictions = {
  22618. skip: false,
  22619. jump: false
  22620. };
  22621. this.snapOptions = {
  22622. out: false,
  22623. in: false
  22624. };
  22625. this.assetList = [];
  22626. this.assetListLoader = void 0;
  22627. this.assetListResponse = null;
  22628. this.resumeAnchor = void 0;
  22629. this.error = void 0;
  22630. this.resetOnResume = void 0;
  22631. this.base = base;
  22632. this.dateRange = dateRange;
  22633. this.setDateRange(dateRange);
  22634. }
  22635. setDateRange(dateRange) {
  22636. this.dateRange = dateRange;
  22637. this.resumeOffset = dateRange.attr.optionalFloat('X-RESUME-OFFSET', this.resumeOffset);
  22638. this.playoutLimit = dateRange.attr.optionalFloat('X-PLAYOUT-LIMIT', this.playoutLimit);
  22639. this.restrictions = dateRange.attr.enumeratedStringList('X-RESTRICT', this.restrictions);
  22640. this.snapOptions = dateRange.attr.enumeratedStringList('X-SNAP', this.snapOptions);
  22641. }
  22642. reset() {
  22643. var _this$assetListLoader;
  22644. this.appendInPlaceStarted = false;
  22645. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  22646. this.assetListLoader = undefined;
  22647. if (!this.supplementsPrimary) {
  22648. this.assetListResponse = null;
  22649. this.assetList = [];
  22650. this._duration = null;
  22651. }
  22652. // `error?` is reset when seeking back over interstitial `startOffset`
  22653. // using `schedule.resetErrorsInRange(start, end)`.
  22654. }
  22655. isAssetPastPlayoutLimit(assetIndex) {
  22656. var _this$assetList$asset;
  22657. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  22658. return true;
  22659. }
  22660. const playoutLimit = this.playoutLimit;
  22661. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  22662. return false;
  22663. }
  22664. if (playoutLimit === 0) {
  22665. return true;
  22666. }
  22667. const assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  22668. return assetOffset > playoutLimit;
  22669. }
  22670. findAssetIndex(asset) {
  22671. const index = this.assetList.indexOf(asset);
  22672. return index;
  22673. }
  22674. get identifier() {
  22675. return this.dateRange.id;
  22676. }
  22677. get startDate() {
  22678. return this.dateRange.startDate;
  22679. }
  22680. get startTime() {
  22681. // Primary media timeline start time
  22682. const startTime = this.dateRange.startTime;
  22683. if (this.snapOptions.out) {
  22684. const frag = this.dateRange.tagAnchor;
  22685. if (frag) {
  22686. return getSnapToFragmentTime(startTime, frag);
  22687. }
  22688. }
  22689. return startTime;
  22690. }
  22691. get startOffset() {
  22692. return this.cue.pre ? 0 : this.startTime;
  22693. }
  22694. get startIsAligned() {
  22695. if (this.startTime === 0 || this.snapOptions.out) {
  22696. return true;
  22697. }
  22698. const frag = this.dateRange.tagAnchor;
  22699. if (frag) {
  22700. const startTime = this.dateRange.startTime;
  22701. const snappedStart = getSnapToFragmentTime(startTime, frag);
  22702. return startTime - snappedStart < 0.1;
  22703. }
  22704. return false;
  22705. }
  22706. get resumptionOffset() {
  22707. const resumeOffset = this.resumeOffset;
  22708. const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  22709. return this.cumulativeDuration + offset;
  22710. }
  22711. get resumeTime() {
  22712. // Primary media timeline resumption time
  22713. const resumeTime = this.startOffset + this.resumptionOffset;
  22714. if (this.snapOptions.in) {
  22715. const frag = this.resumeAnchor;
  22716. if (frag) {
  22717. return getSnapToFragmentTime(resumeTime, frag);
  22718. }
  22719. }
  22720. return resumeTime;
  22721. }
  22722. get appendInPlace() {
  22723. if (this.appendInPlaceStarted) {
  22724. return true;
  22725. }
  22726. if (this.appendInPlaceDisabled) {
  22727. return false;
  22728. }
  22729. if (!this.cue.once && !this.cue.pre &&
  22730. // preroll starts at startPosition before startPosition is known (live)
  22731. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  22732. return true;
  22733. }
  22734. return false;
  22735. }
  22736. set appendInPlace(value) {
  22737. if (this.appendInPlaceStarted) {
  22738. this.resetOnResume = !value;
  22739. return;
  22740. }
  22741. this.appendInPlaceDisabled = !value;
  22742. }
  22743. // Extended timeline start time
  22744. get timelineStart() {
  22745. if (this._timelineStart !== null) {
  22746. return this._timelineStart;
  22747. }
  22748. return this.startTime;
  22749. }
  22750. set timelineStart(value) {
  22751. this._timelineStart = value;
  22752. }
  22753. get duration() {
  22754. const playoutLimit = this.playoutLimit;
  22755. let duration;
  22756. if (this._duration !== null) {
  22757. duration = this._duration;
  22758. } else if (this.dateRange.duration) {
  22759. duration = this.dateRange.duration;
  22760. } else {
  22761. duration = this.dateRange.plannedDuration || 0;
  22762. }
  22763. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  22764. duration = playoutLimit;
  22765. }
  22766. return duration;
  22767. }
  22768. set duration(value) {
  22769. this._duration = value;
  22770. }
  22771. get cue() {
  22772. return this.dateRange.cue;
  22773. }
  22774. get timelineOccupancy() {
  22775. if (this.dateRange.attr['X-TIMELINE-OCCUPIES'] === 'RANGE') {
  22776. return TimelineOccupancy.Range;
  22777. }
  22778. return TimelineOccupancy.Point;
  22779. }
  22780. get supplementsPrimary() {
  22781. return this.dateRange.attr['X-TIMELINE-STYLE'] === 'PRIMARY';
  22782. }
  22783. get contentMayVary() {
  22784. return this.dateRange.attr['X-CONTENT-MAY-VARY'] !== 'NO';
  22785. }
  22786. get assetUrl() {
  22787. return this.dateRange.attr['X-ASSET-URI'];
  22788. }
  22789. get assetListUrl() {
  22790. return this.dateRange.attr['X-ASSET-LIST'];
  22791. }
  22792. get baseUrl() {
  22793. return this.base.url;
  22794. }
  22795. get assetListLoaded() {
  22796. return this.assetList.length > 0 || this.assetListResponse !== null;
  22797. }
  22798. toString() {
  22799. return eventToString(this);
  22800. }
  22801. }
  22802. function getSnapToFragmentTime(time, frag) {
  22803. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  22804. }
  22805. function getInterstitialUrl(uri, sessionId, baseUrl) {
  22806. const url = new self.URL(uri, baseUrl);
  22807. if (url.protocol !== 'data:') {
  22808. url.searchParams.set('_HLS_primary_id', sessionId);
  22809. }
  22810. return url;
  22811. }
  22812. function getNextAssetIndex(interstitial, assetListIndex) {
  22813. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  22814. var _interstitial$assetLi;
  22815. } /* no-op */
  22816. return assetListIndex;
  22817. }
  22818. function eventToString(interstitial) {
  22819. return `["${interstitial.identifier}" ${interstitial.cue.pre ? '<pre>' : interstitial.cue.post ? '<post>' : ''}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;
  22820. }
  22821. function eventAssetToString(asset) {
  22822. const start = asset.timelineStart;
  22823. const duration = asset.duration || 0;
  22824. return `["${asset.identifier}" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;
  22825. }
  22826. class HlsAssetPlayer {
  22827. constructor(HlsPlayerClass, userConfig, interstitial, assetItem) {
  22828. this.hls = void 0;
  22829. this.interstitial = void 0;
  22830. this.assetItem = void 0;
  22831. this.tracks = null;
  22832. this.hasDetails = false;
  22833. this.mediaAttached = null;
  22834. this._currentTime = void 0;
  22835. this._bufferedEosTime = void 0;
  22836. this.checkPlayout = () => {
  22837. if (this.reachedPlayout(this.currentTime)) {
  22838. this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  22839. }
  22840. };
  22841. const hls = this.hls = new HlsPlayerClass(userConfig);
  22842. this.interstitial = interstitial;
  22843. this.assetItem = assetItem;
  22844. let uri = assetItem.uri;
  22845. try {
  22846. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  22847. } catch (error) {
  22848. // Ignore error parsing ASSET_URI or adding _HLS_primary_id to it. The
  22849. // issue should surface as an INTERSTITIAL_ASSET_ERROR loading the asset.
  22850. }
  22851. hls.loadSource(uri);
  22852. const detailsLoaded = () => {
  22853. this.hasDetails = true;
  22854. };
  22855. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  22856. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  22857. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  22858. hls.on(Events.MEDIA_ATTACHING, (name, {
  22859. media
  22860. }) => {
  22861. this.removeMediaListeners();
  22862. this.mediaAttached = media;
  22863. const event = this.interstitial;
  22864. if (event.playoutLimit) {
  22865. media.addEventListener('timeupdate', this.checkPlayout);
  22866. if (this.appendInPlace) {
  22867. hls.on(Events.BUFFER_APPENDED, () => {
  22868. const bufferedEnd = this.bufferedEnd;
  22869. if (this.reachedPlayout(bufferedEnd)) {
  22870. this._bufferedEosTime = bufferedEnd;
  22871. hls.trigger(Events.BUFFERED_TO_END, undefined);
  22872. }
  22873. });
  22874. }
  22875. }
  22876. });
  22877. }
  22878. get appendInPlace() {
  22879. var _this$interstitial;
  22880. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  22881. }
  22882. bufferedInPlaceToEnd(media) {
  22883. var _this$hls;
  22884. if (!this.appendInPlace) {
  22885. return false;
  22886. }
  22887. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  22888. return true;
  22889. }
  22890. if (!media || !this._bufferedEosTime) {
  22891. return false;
  22892. }
  22893. const start = this.timelineOffset;
  22894. const bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  22895. const bufferedEnd = this.getAssetTime(bufferInfo.end);
  22896. return bufferedEnd >= this._bufferedEosTime - 0.02;
  22897. }
  22898. reachedPlayout(time) {
  22899. const interstitial = this.interstitial;
  22900. const playoutLimit = interstitial.playoutLimit;
  22901. return this.startOffset + time >= playoutLimit;
  22902. }
  22903. get destroyed() {
  22904. var _this$hls2;
  22905. return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);
  22906. }
  22907. get assetId() {
  22908. return this.assetItem.identifier;
  22909. }
  22910. get interstitialId() {
  22911. return this.assetItem.parentIdentifier;
  22912. }
  22913. get media() {
  22914. var _this$hls3;
  22915. return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;
  22916. }
  22917. get bufferedEnd() {
  22918. const media = this.media || this.mediaAttached;
  22919. if (!media) {
  22920. if (this._bufferedEosTime) {
  22921. return this._bufferedEosTime;
  22922. }
  22923. return this.currentTime;
  22924. }
  22925. const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 0.001);
  22926. return this.getAssetTime(bufferInfo.end);
  22927. }
  22928. get currentTime() {
  22929. const media = this.media || this.mediaAttached;
  22930. if (!media) {
  22931. return this._currentTime || 0;
  22932. }
  22933. return this.getAssetTime(media.currentTime);
  22934. }
  22935. get duration() {
  22936. const duration = this.assetItem.duration;
  22937. if (!duration) {
  22938. return 0;
  22939. }
  22940. return duration;
  22941. }
  22942. get remaining() {
  22943. const duration = this.duration;
  22944. if (!duration) {
  22945. return 0;
  22946. }
  22947. return Math.max(0, duration - this.currentTime);
  22948. }
  22949. get startOffset() {
  22950. return this.assetItem.startOffset;
  22951. }
  22952. get timelineOffset() {
  22953. var _this$hls4;
  22954. return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;
  22955. }
  22956. set timelineOffset(value) {
  22957. const timelineOffset = this.timelineOffset;
  22958. if (value !== timelineOffset) {
  22959. const diff = value - timelineOffset;
  22960. if (Math.abs(diff) > 1 / 90000) {
  22961. if (this.hasDetails) {
  22962. throw new Error(`Cannot set timelineOffset after playlists are loaded`);
  22963. }
  22964. this.hls.config.timelineOffset = value;
  22965. }
  22966. }
  22967. }
  22968. getAssetTime(time) {
  22969. const timelineOffset = this.timelineOffset;
  22970. const duration = this.duration;
  22971. return Math.min(Math.max(0, time - timelineOffset), duration);
  22972. }
  22973. removeMediaListeners() {
  22974. const media = this.mediaAttached;
  22975. if (media) {
  22976. this._currentTime = media.currentTime;
  22977. this.bufferSnapShot();
  22978. media.removeEventListener('timeupdate', this.checkPlayout);
  22979. }
  22980. }
  22981. bufferSnapShot() {
  22982. if (this.mediaAttached) {
  22983. var _this$hls5;
  22984. if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {
  22985. this._bufferedEosTime = this.bufferedEnd;
  22986. }
  22987. }
  22988. }
  22989. destroy() {
  22990. this.removeMediaListeners();
  22991. this.hls.destroy();
  22992. // @ts-ignore
  22993. this.hls = this.interstitial = null;
  22994. // @ts-ignore
  22995. this.tracks = this.mediaAttached = this.checkPlayout = null;
  22996. }
  22997. attachMedia(data) {
  22998. this.hls.attachMedia(data);
  22999. }
  23000. detachMedia() {
  23001. this.removeMediaListeners();
  23002. this.mediaAttached = null;
  23003. this.hls.detachMedia();
  23004. }
  23005. resumeBuffering() {
  23006. this.hls.resumeBuffering();
  23007. }
  23008. pauseBuffering() {
  23009. this.hls.pauseBuffering();
  23010. }
  23011. transferMedia() {
  23012. this.bufferSnapShot();
  23013. return this.hls.transferMedia();
  23014. }
  23015. resetDetails() {
  23016. const hls = this.hls;
  23017. if (this.hasDetails) {
  23018. hls.stopLoad();
  23019. const deleteDetails = obj => delete obj.details;
  23020. hls.levels.forEach(deleteDetails);
  23021. hls.allAudioTracks.forEach(deleteDetails);
  23022. hls.allSubtitleTracks.forEach(deleteDetails);
  23023. this.hasDetails = false;
  23024. }
  23025. }
  23026. on(event, listener, context) {
  23027. this.hls.on(event, listener);
  23028. }
  23029. once(event, listener, context) {
  23030. this.hls.once(event, listener);
  23031. }
  23032. off(event, listener, context) {
  23033. this.hls.off(event, listener);
  23034. }
  23035. toString() {
  23036. var _this$hls6;
  23037. return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${this.appendInPlace ? 'append-in-place' : ''}`;
  23038. }
  23039. }
  23040. const ABUTTING_THRESHOLD_SECONDS = 0.033;
  23041. class InterstitialsSchedule extends Logger {
  23042. constructor(onScheduleUpdate, logger) {
  23043. super('interstitials-sched', logger);
  23044. this.onScheduleUpdate = void 0;
  23045. this.eventMap = {};
  23046. this.events = null;
  23047. this.items = null;
  23048. this.durations = {
  23049. primary: 0,
  23050. playout: 0,
  23051. integrated: 0
  23052. };
  23053. this.onScheduleUpdate = onScheduleUpdate;
  23054. }
  23055. destroy() {
  23056. this.reset();
  23057. // @ts-ignore
  23058. this.onScheduleUpdate = null;
  23059. }
  23060. reset() {
  23061. this.eventMap = {};
  23062. this.setDurations(0, 0, 0);
  23063. if (this.events) {
  23064. this.events.forEach(interstitial => interstitial.reset());
  23065. }
  23066. this.events = this.items = null;
  23067. }
  23068. resetErrorsInRange(start, end) {
  23069. if (this.events) {
  23070. return this.events.reduce((count, interstitial) => {
  23071. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  23072. delete interstitial.error;
  23073. return count + 1;
  23074. }
  23075. return count;
  23076. }, 0);
  23077. }
  23078. return 0;
  23079. }
  23080. get duration() {
  23081. const items = this.items;
  23082. return items ? items[items.length - 1].end : 0;
  23083. }
  23084. get length() {
  23085. return this.items ? this.items.length : 0;
  23086. }
  23087. getEvent(identifier) {
  23088. return identifier ? this.eventMap[identifier] || null : null;
  23089. }
  23090. hasEvent(identifier) {
  23091. return identifier in this.eventMap;
  23092. }
  23093. findItemIndex(item, time) {
  23094. if (item.event) {
  23095. // Find Event Item
  23096. return this.findEventIndex(item.event.identifier);
  23097. }
  23098. // Find Primary Item
  23099. let index = -1;
  23100. if (item.nextEvent) {
  23101. index = this.findEventIndex(item.nextEvent.identifier) - 1;
  23102. } else if (item.previousEvent) {
  23103. index = this.findEventIndex(item.previousEvent.identifier) + 1;
  23104. }
  23105. const items = this.items;
  23106. if (items) {
  23107. if (!items[index]) {
  23108. if (time === undefined) {
  23109. time = item.start;
  23110. }
  23111. index = this.findItemIndexAtTime(time);
  23112. }
  23113. // Only return index of a Primary Item
  23114. while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
  23115. var _items$index;
  23116. // If index found is an interstitial it is not a valid result as it should have been matched up top
  23117. // decrement until result is negative (not found) or a primary segment
  23118. index--;
  23119. }
  23120. }
  23121. return index;
  23122. }
  23123. findItemIndexAtTime(timelinePos, timelineType) {
  23124. const items = this.items;
  23125. if (items) {
  23126. for (let i = 0; i < items.length; i++) {
  23127. let timeRange = items[i];
  23128. if (timelineType && timelineType !== 'primary') {
  23129. timeRange = timeRange[timelineType];
  23130. }
  23131. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  23132. return i;
  23133. }
  23134. }
  23135. }
  23136. return -1;
  23137. }
  23138. findJumpRestrictedIndex(startIndex, endIndex) {
  23139. const items = this.items;
  23140. if (items) {
  23141. for (let i = startIndex; i <= endIndex; i++) {
  23142. if (!items[i]) {
  23143. break;
  23144. }
  23145. const event = items[i].event;
  23146. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  23147. return i;
  23148. }
  23149. }
  23150. }
  23151. return -1;
  23152. }
  23153. findEventIndex(identifier) {
  23154. const items = this.items;
  23155. if (items) {
  23156. for (let i = items.length; i--;) {
  23157. var _items$i$event;
  23158. if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  23159. return i;
  23160. }
  23161. }
  23162. }
  23163. return -1;
  23164. }
  23165. findAssetIndex(event, timelinePos) {
  23166. const assetList = event.assetList;
  23167. const length = assetList.length;
  23168. if (length > 1) {
  23169. for (let i = 0; i < length; i++) {
  23170. const asset = assetList[i];
  23171. if (!asset.error) {
  23172. const timelineStart = asset.timelineStart;
  23173. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  23174. return i;
  23175. }
  23176. }
  23177. }
  23178. }
  23179. return 0;
  23180. }
  23181. get assetIdAtEnd() {
  23182. var _this$items, _this$items2;
  23183. const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  23184. if (interstitialAtEnd) {
  23185. const assetList = interstitialAtEnd.assetList;
  23186. const assetAtEnd = assetList[assetList.length - 1];
  23187. if (assetAtEnd) {
  23188. return assetAtEnd.identifier;
  23189. }
  23190. }
  23191. return null;
  23192. }
  23193. parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  23194. const details = mediaSelection.main.details;
  23195. const {
  23196. dateRanges
  23197. } = details;
  23198. const previousInterstitialEvents = this.events;
  23199. const interstitialEvents = this.parseDateRanges(dateRanges, {
  23200. url: details.url
  23201. }, enableAppendInPlace);
  23202. const ids = Object.keys(dateRanges);
  23203. const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter(event => !ids.includes(event.identifier)) : [];
  23204. if (interstitialEvents.length) {
  23205. // pre-rolls, post-rolls, and events with the same start time are played in playlist tag order
  23206. // all other events are ordered by start time
  23207. interstitialEvents.sort((a, b) => {
  23208. const aPre = a.cue.pre;
  23209. const aPost = a.cue.post;
  23210. const bPre = b.cue.pre;
  23211. const bPost = b.cue.post;
  23212. if (aPre && !bPre) {
  23213. return -1;
  23214. }
  23215. if (bPre && !aPre) {
  23216. return 1;
  23217. }
  23218. if (aPost && !bPost) {
  23219. return 1;
  23220. }
  23221. if (bPost && !aPost) {
  23222. return -1;
  23223. }
  23224. if (!aPre && !bPre && !aPost && !bPost) {
  23225. const startA = a.startTime;
  23226. const startB = b.startTime;
  23227. if (startA !== startB) {
  23228. return startA - startB;
  23229. }
  23230. }
  23231. return a.dateRange.tagOrder - b.dateRange.tagOrder;
  23232. });
  23233. }
  23234. this.events = interstitialEvents;
  23235. // Clear removed DateRanges from buffered list (kills playback of active Interstitials)
  23236. removedInterstitials.forEach(interstitial => {
  23237. this.removeEvent(interstitial);
  23238. });
  23239. this.updateSchedule(mediaSelection, removedInterstitials);
  23240. }
  23241. updateSchedule(mediaSelection, removedInterstitials = []) {
  23242. const events = this.events || [];
  23243. if (events.length || removedInterstitials.length || this.length < 2) {
  23244. const currentItems = this.items;
  23245. const updatedItems = this.parseSchedule(events, mediaSelection);
  23246. const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {
  23247. return Math.abs(item.playout.start - currentItems[i].playout.start) > 0.005 || Math.abs(item.playout.end - currentItems[i].playout.end) > 0.005;
  23248. });
  23249. if (updated) {
  23250. this.items = updatedItems;
  23251. // call interstitials-controller onScheduleUpdated()
  23252. this.onScheduleUpdate(removedInterstitials, currentItems);
  23253. }
  23254. }
  23255. }
  23256. parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  23257. const interstitialEvents = [];
  23258. const ids = Object.keys(dateRanges);
  23259. for (let i = 0; i < ids.length; i++) {
  23260. const id = ids[i];
  23261. const dateRange = dateRanges[id];
  23262. if (dateRange.isInterstitial) {
  23263. let interstitial = this.eventMap[id];
  23264. if (interstitial) {
  23265. // Update InterstitialEvent already parsed and mapped
  23266. // This retains already loaded duration and loaded asset list info
  23267. interstitial.setDateRange(dateRange);
  23268. } else {
  23269. interstitial = new InterstitialEvent(dateRange, baseData);
  23270. this.eventMap[id] = interstitial;
  23271. if (enableAppendInPlace === false) {
  23272. interstitial.appendInPlace = enableAppendInPlace;
  23273. }
  23274. }
  23275. interstitialEvents.push(interstitial);
  23276. }
  23277. }
  23278. return interstitialEvents;
  23279. }
  23280. parseSchedule(interstitialEvents, mediaSelection) {
  23281. const schedule = [];
  23282. const details = mediaSelection.main.details;
  23283. const primaryDuration = details.live ? Infinity : details.edge;
  23284. let playoutDuration = 0;
  23285. // Filter events that have errored from the schedule (Primary fallback)
  23286. interstitialEvents = interstitialEvents.filter(event => !event.error && !(event.cue.once && event.hasPlayed));
  23287. if (interstitialEvents.length) {
  23288. // Update Schedule
  23289. this.resolveOffsets(interstitialEvents, mediaSelection);
  23290. // Populate Schedule with Interstitial Event and Primary Segment Items
  23291. let primaryPosition = 0;
  23292. let integratedTime = 0;
  23293. interstitialEvents.forEach((interstitial, i) => {
  23294. const preroll = interstitial.cue.pre;
  23295. const postroll = interstitial.cue.post;
  23296. const previousEvent = interstitialEvents[i - 1] || null;
  23297. const appendInPlace = interstitial.appendInPlace;
  23298. const eventStart = postroll ? primaryDuration : interstitial.startOffset;
  23299. const interstitialDuration = interstitial.duration;
  23300. const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  23301. const resumptionOffset = interstitial.resumptionOffset;
  23302. const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  23303. const start = eventStart + interstitial.cumulativeDuration;
  23304. let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  23305. if (preroll || !postroll && eventStart <= 0) {
  23306. // preroll or in-progress midroll
  23307. const integratedStart = integratedTime;
  23308. integratedTime += timelineDuration;
  23309. interstitial.timelineStart = start;
  23310. const playoutStart = playoutDuration;
  23311. playoutDuration += interstitialDuration;
  23312. schedule.push({
  23313. event: interstitial,
  23314. start,
  23315. end,
  23316. playout: {
  23317. start: playoutStart,
  23318. end: playoutDuration
  23319. },
  23320. integrated: {
  23321. start: integratedStart,
  23322. end: integratedTime
  23323. }
  23324. });
  23325. } else if (eventStart <= primaryDuration) {
  23326. if (!inSameStartTimeSequence) {
  23327. const segmentDuration = eventStart - primaryPosition;
  23328. // Do not schedule a primary segment if interstitials are abutting by less than ABUTTING_THRESHOLD_SECONDS
  23329. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  23330. // primary segment
  23331. const timelineStart = primaryPosition;
  23332. const _integratedStart = integratedTime;
  23333. integratedTime += segmentDuration;
  23334. const _playoutStart = playoutDuration;
  23335. playoutDuration += segmentDuration;
  23336. const primarySegment = {
  23337. previousEvent: interstitialEvents[i - 1] || null,
  23338. nextEvent: interstitial,
  23339. start: timelineStart,
  23340. end: timelineStart + segmentDuration,
  23341. playout: {
  23342. start: _playoutStart,
  23343. end: playoutDuration
  23344. },
  23345. integrated: {
  23346. start: _integratedStart,
  23347. end: integratedTime
  23348. }
  23349. };
  23350. schedule.push(primarySegment);
  23351. } else if (segmentDuration > 0 && previousEvent) {
  23352. // Add previous event `resumeTime` (based on duration or resumeOffset) so that it ends aligned with this one
  23353. previousEvent.cumulativeDuration += segmentDuration;
  23354. schedule[schedule.length - 1].end = eventStart;
  23355. }
  23356. }
  23357. // midroll / postroll
  23358. if (postroll) {
  23359. end = start;
  23360. }
  23361. interstitial.timelineStart = start;
  23362. const integratedStart = integratedTime;
  23363. integratedTime += timelineDuration;
  23364. const playoutStart = playoutDuration;
  23365. playoutDuration += interstitialDuration;
  23366. schedule.push({
  23367. event: interstitial,
  23368. start,
  23369. end,
  23370. playout: {
  23371. start: playoutStart,
  23372. end: playoutDuration
  23373. },
  23374. integrated: {
  23375. start: integratedStart,
  23376. end: integratedTime
  23377. }
  23378. });
  23379. } else {
  23380. // Interstitial starts after end of primary VOD - not included in schedule
  23381. return;
  23382. }
  23383. const resumeTime = interstitial.resumeTime;
  23384. if (postroll || resumeTime > primaryDuration) {
  23385. primaryPosition = primaryDuration;
  23386. } else {
  23387. primaryPosition = resumeTime;
  23388. }
  23389. });
  23390. if (primaryPosition < primaryDuration) {
  23391. var _schedule;
  23392. // last primary segment
  23393. const timelineStart = primaryPosition;
  23394. const integratedStart = integratedTime;
  23395. const segmentDuration = primaryDuration - primaryPosition;
  23396. integratedTime += segmentDuration;
  23397. const playoutStart = playoutDuration;
  23398. playoutDuration += segmentDuration;
  23399. schedule.push({
  23400. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  23401. nextEvent: null,
  23402. start: primaryPosition,
  23403. end: timelineStart + segmentDuration,
  23404. playout: {
  23405. start: playoutStart,
  23406. end: playoutDuration
  23407. },
  23408. integrated: {
  23409. start: integratedStart,
  23410. end: integratedTime
  23411. }
  23412. });
  23413. }
  23414. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  23415. } else {
  23416. // no interstials - schedule is one primary segment
  23417. const start = 0;
  23418. schedule.push({
  23419. previousEvent: null,
  23420. nextEvent: null,
  23421. start,
  23422. end: primaryDuration,
  23423. playout: {
  23424. start,
  23425. end: primaryDuration
  23426. },
  23427. integrated: {
  23428. start,
  23429. end: primaryDuration
  23430. }
  23431. });
  23432. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  23433. }
  23434. return schedule;
  23435. }
  23436. setDurations(primary, playout, integrated) {
  23437. this.durations = {
  23438. primary,
  23439. playout,
  23440. integrated
  23441. };
  23442. }
  23443. resolveOffsets(interstitialEvents, mediaSelection) {
  23444. const details = mediaSelection.main.details;
  23445. const primaryDuration = details.live ? Infinity : details.edge;
  23446. // First resolve cumulative resumption offsets for Interstitials that start at the same DateTime
  23447. let cumulativeDuration = 0;
  23448. let lastScheduledStart = -1;
  23449. interstitialEvents.forEach((interstitial, i) => {
  23450. const preroll = interstitial.cue.pre;
  23451. const postroll = interstitial.cue.post;
  23452. const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  23453. this.updateAssetDurations(interstitial);
  23454. // X-RESUME-OFFSET values of interstitials scheduled at the same time are cumulative
  23455. const inSameStartTimeSequence = lastScheduledStart === eventStart;
  23456. if (inSameStartTimeSequence) {
  23457. interstitial.cumulativeDuration = cumulativeDuration;
  23458. } else {
  23459. cumulativeDuration = 0;
  23460. lastScheduledStart = eventStart;
  23461. }
  23462. if (!postroll && interstitial.snapOptions.in) {
  23463. // FIXME: Include audio playlist in snapping
  23464. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || undefined;
  23465. }
  23466. // Check if primary fragments align with resumption offset and disable appendInPlace if they do not
  23467. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  23468. const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  23469. if (!alignedSegmentStart) {
  23470. interstitial.appendInPlace = false;
  23471. }
  23472. }
  23473. if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
  23474. // abutting Interstitials must use the same MediaSource strategy, this applies to all whether or not they are back to back:
  23475. const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
  23476. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  23477. interstitialEvents[i + 1].appendInPlace = false;
  23478. if (interstitialEvents[i + 1].appendInPlace) {
  23479. this.warn(`Could not change append strategy for abutting event ${interstitial}`);
  23480. }
  23481. }
  23482. }
  23483. // Update cumulativeDuration for next abutting interstitial with the same start date
  23484. const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  23485. cumulativeDuration += resumeOffset;
  23486. });
  23487. }
  23488. primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  23489. const resumeTime = interstitial.resumeTime;
  23490. const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  23491. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  23492. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);
  23493. return false;
  23494. }
  23495. if (!mediaSelection) {
  23496. this.log(`"${interstitial.identifier}" resumption ${resumeTime} can not be aligned with media (none selected)`);
  23497. return false;
  23498. }
  23499. const playlists = Object.keys(mediaSelection);
  23500. return !playlists.some(playlistType => {
  23501. const details = mediaSelection[playlistType].details;
  23502. const playlistEnd = details.edge;
  23503. if (resumeTime >= playlistEnd) {
  23504. // Live playback - resumption segments are not yet available
  23505. this.log(`"${interstitial.identifier}" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);
  23506. // Assume alignment is possible (or reset can take place)
  23507. return false;
  23508. }
  23509. const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  23510. if (!startFragment) {
  23511. this.log(`"${interstitial.identifier}" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);
  23512. return true;
  23513. }
  23514. const allowance = playlistType === 'audio' ? 0.175 : 0;
  23515. const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  23516. if (!alignedWithSegment) {
  23517. this.log(`"${interstitial.identifier}" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);
  23518. return true;
  23519. }
  23520. return false;
  23521. });
  23522. }
  23523. updateAssetDurations(interstitial) {
  23524. if (!interstitial.assetListLoaded) {
  23525. return;
  23526. }
  23527. const eventStart = interstitial.timelineStart;
  23528. let sumDuration = 0;
  23529. let hasUnknownDuration = false;
  23530. let hasErrors = false;
  23531. interstitial.assetList.forEach((asset, i) => {
  23532. const timelineStart = eventStart + sumDuration;
  23533. asset.startOffset = sumDuration;
  23534. asset.timelineStart = timelineStart;
  23535. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  23536. hasErrors || (hasErrors = !!asset.error);
  23537. const duration = asset.error ? 0 : asset.duration || 0;
  23538. sumDuration += duration;
  23539. });
  23540. // Use the sum of known durations when it is greater than the stated duration
  23541. if (hasUnknownDuration && !hasErrors) {
  23542. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  23543. } else {
  23544. interstitial.duration = sumDuration;
  23545. }
  23546. }
  23547. removeEvent(interstitial) {
  23548. interstitial.reset();
  23549. delete this.eventMap[interstitial.identifier];
  23550. }
  23551. }
  23552. function segmentToString(segment) {
  23553. return `[${segment.event ? '"' + segment.event.identifier + '"' : 'primary'}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;
  23554. }
  23555. class AssetListLoader {
  23556. constructor(hls) {
  23557. this.hls = void 0;
  23558. this.hls = hls;
  23559. }
  23560. destroy() {
  23561. // @ts-ignore
  23562. this.hls = null;
  23563. }
  23564. loadAssetList(interstitial, hlsStartOffset) {
  23565. const assetListUrl = interstitial.assetListUrl;
  23566. let url;
  23567. try {
  23568. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  23569. } catch (error) {
  23570. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  23571. this.hls.trigger(Events.ERROR, errorData);
  23572. return;
  23573. }
  23574. if (hlsStartOffset && url.protocol !== 'data:') {
  23575. url.searchParams.set('_HLS_start_offset', '' + hlsStartOffset);
  23576. }
  23577. const config = this.hls.config;
  23578. const Loader = config.loader;
  23579. const loader = new Loader(config);
  23580. const context = {
  23581. responseType: 'json',
  23582. url: url.href
  23583. };
  23584. const loadPolicy = config.interstitialAssetListLoadPolicy.default;
  23585. const loaderConfig = {
  23586. loadPolicy,
  23587. timeout: loadPolicy.maxLoadTimeMs,
  23588. maxRetry: 0,
  23589. retryDelay: 0,
  23590. maxRetryDelay: 0
  23591. };
  23592. const callbacks = {
  23593. onSuccess: (response, stats, context, networkDetails) => {
  23594. const assetListResponse = response.data;
  23595. const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  23596. if (!Array.isArray(assets)) {
  23597. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context.url, stats, networkDetails);
  23598. this.hls.trigger(Events.ERROR, errorData);
  23599. return;
  23600. }
  23601. interstitial.assetListResponse = assetListResponse;
  23602. this.hls.trigger(Events.ASSET_LIST_LOADED, {
  23603. event: interstitial,
  23604. assetListResponse,
  23605. networkDetails
  23606. });
  23607. },
  23608. onError: (error, context, networkDetails, stats) => {
  23609. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error.code} ${error.text} (${context.url})`), context.url, stats, networkDetails);
  23610. this.hls.trigger(Events.ERROR, errorData);
  23611. },
  23612. onTimeout: (stats, context, networkDetails) => {
  23613. const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context.url})`), context.url, stats, networkDetails);
  23614. this.hls.trigger(Events.ERROR, errorData);
  23615. }
  23616. };
  23617. loader.load(context, loaderConfig, callbacks);
  23618. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  23619. event: interstitial
  23620. });
  23621. return loader;
  23622. }
  23623. assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  23624. interstitial.error = error;
  23625. return {
  23626. type: ErrorTypes.NETWORK_ERROR,
  23627. details,
  23628. fatal: false,
  23629. interstitial,
  23630. url,
  23631. error,
  23632. networkDetails,
  23633. stats
  23634. };
  23635. }
  23636. }
  23637. function playWithCatch(media) {
  23638. media == null ? void 0 : media.play().catch(() => {
  23639. /* no-op */
  23640. });
  23641. }
  23642. class InterstitialsController extends Logger {
  23643. constructor(hls, HlsPlayerClass) {
  23644. super('interstitials', hls.logger);
  23645. this.HlsPlayerClass = void 0;
  23646. this.hls = void 0;
  23647. this.assetListLoader = void 0;
  23648. // Last updated LevelDetails
  23649. this.mediaSelection = null;
  23650. this.altSelection = null;
  23651. // Media and MediaSource/SourceBuffers
  23652. this.media = null;
  23653. this.detachedData = null;
  23654. this.requiredTracks = null;
  23655. // Public Interface for Interstitial playback state and control
  23656. this.manager = null;
  23657. // Interstitial Asset Players
  23658. this.playerQueue = [];
  23659. // Timeline position tracking
  23660. this.bufferedPos = -1;
  23661. this.timelinePos = -1;
  23662. // Schedule
  23663. this.schedule = void 0;
  23664. // Schedule playback and buffering state
  23665. this.playingItem = null;
  23666. this.bufferingItem = null;
  23667. this.waitingItem = null;
  23668. this.endedItem = null;
  23669. this.playingAsset = null;
  23670. this.endedAsset = null;
  23671. this.bufferingAsset = null;
  23672. this.shouldPlay = false;
  23673. this.onPlay = () => {
  23674. this.shouldPlay = true;
  23675. };
  23676. this.onPause = () => {
  23677. this.shouldPlay = false;
  23678. };
  23679. this.onSeeking = () => {
  23680. const currentTime = this.currentTime;
  23681. if (currentTime === undefined || this.playbackDisabled) {
  23682. return;
  23683. }
  23684. const diff = currentTime - this.timelinePos;
  23685. const roundingError = Math.abs(diff) < 1 / 705600000; // one flick
  23686. if (roundingError) {
  23687. return;
  23688. }
  23689. const backwardSeek = diff <= -0.01;
  23690. this.timelinePos = currentTime;
  23691. this.bufferedPos = currentTime;
  23692. // Check if seeking out of an item
  23693. const playingItem = this.playingItem;
  23694. if (!playingItem) {
  23695. this.checkBuffer();
  23696. return;
  23697. }
  23698. if (backwardSeek) {
  23699. const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  23700. if (resetCount) {
  23701. this.updateSchedule();
  23702. }
  23703. }
  23704. this.checkBuffer();
  23705. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  23706. var _this$media;
  23707. const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);
  23708. if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {
  23709. this.shouldPlay = false;
  23710. }
  23711. if (!backwardSeek) {
  23712. // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction
  23713. const playingIndex = this.findItemIndex(playingItem);
  23714. if (scheduleIndex > playingIndex) {
  23715. const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  23716. if (jumpIndex > playingIndex) {
  23717. this.setSchedulePosition(jumpIndex);
  23718. return;
  23719. }
  23720. }
  23721. }
  23722. this.setSchedulePosition(scheduleIndex);
  23723. return;
  23724. }
  23725. // Check if seeking out of an asset (assumes same item following above check)
  23726. const playingAsset = this.playingAsset;
  23727. if (!playingAsset) {
  23728. // restart Interstitial at end
  23729. if (this.playingLastItem && this.isInterstitial(playingItem)) {
  23730. const restartAsset = playingItem.event.assetList[0];
  23731. if (restartAsset) {
  23732. this.endedItem = this.playingItem;
  23733. this.playingItem = null;
  23734. this.setScheduleToAssetAtTime(currentTime, restartAsset);
  23735. }
  23736. }
  23737. return;
  23738. }
  23739. const start = playingAsset.timelineStart;
  23740. const duration = playingAsset.duration || 0;
  23741. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  23742. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  23743. }
  23744. };
  23745. this.onTimeupdate = () => {
  23746. const currentTime = this.currentTime;
  23747. if (currentTime === undefined || this.playbackDisabled) {
  23748. return;
  23749. }
  23750. // Only allow timeupdate to advance primary position, seeking is used for jumping back
  23751. // this prevents primaryPos from being reset to 0 after re-attach
  23752. if (currentTime > this.timelinePos) {
  23753. this.timelinePos = currentTime;
  23754. if (currentTime > this.bufferedPos) {
  23755. this.checkBuffer();
  23756. }
  23757. } else {
  23758. return;
  23759. }
  23760. // Check if playback has entered the next item
  23761. const playingItem = this.playingItem;
  23762. if (!playingItem || this.playingLastItem) {
  23763. return;
  23764. }
  23765. if (currentTime >= playingItem.end) {
  23766. this.timelinePos = playingItem.end;
  23767. const playingIndex = this.findItemIndex(playingItem);
  23768. this.setSchedulePosition(playingIndex + 1);
  23769. }
  23770. // Check if playback has entered the next asset
  23771. const playingAsset = this.playingAsset;
  23772. if (!playingAsset) {
  23773. return;
  23774. }
  23775. const end = playingAsset.timelineStart + (playingAsset.duration || 0);
  23776. if (currentTime >= end) {
  23777. this.setScheduleToAssetAtTime(currentTime, playingAsset);
  23778. }
  23779. };
  23780. // Schedule update callback
  23781. this.onScheduleUpdate = (removedInterstitials, previousItems) => {
  23782. const schedule = this.schedule;
  23783. const playingItem = this.playingItem;
  23784. const interstitialEvents = schedule.events || [];
  23785. const scheduleItems = schedule.items || [];
  23786. const durations = schedule.durations;
  23787. const removedIds = removedInterstitials.map(interstitial => interstitial.identifier);
  23788. const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  23789. if (interstitialsUpdated || previousItems) {
  23790. this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}
  23791. Schedule: ${scheduleItems.map(seg => segmentToString(seg))} pos: ${this.timelinePos}`);
  23792. }
  23793. if (removedIds.length) {
  23794. this.log(`Removed events ${removedIds}`);
  23795. }
  23796. this.playerQueue.forEach(player => {
  23797. if (player.interstitial.appendInPlace) {
  23798. const timelineStart = player.assetItem.timelineStart;
  23799. const diff = player.timelineOffset - timelineStart;
  23800. if (diff) {
  23801. try {
  23802. player.timelineOffset = timelineStart;
  23803. } catch (e) {
  23804. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  23805. this.warn(`${e} ("${player.assetId}" ${player.timelineOffset}->${timelineStart})`);
  23806. }
  23807. }
  23808. }
  23809. }
  23810. });
  23811. // Update schedule item references
  23812. // Do not replace Interstitial playingItem without a match - used for INTERSTITIAL_ASSET_ENDED and INTERSTITIAL_ENDED
  23813. let trimInPlaceForPlayout = null;
  23814. if (playingItem) {
  23815. const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);
  23816. if (this.itemsMatch(playingItem, updatedPlayingItem)) {
  23817. this.playingItem = updatedPlayingItem;
  23818. this.waitingItem = this.endedItem = null;
  23819. trimInPlaceForPlayout = () => this.trimInPlace(updatedPlayingItem, playingItem);
  23820. }
  23821. } else {
  23822. // Clear waitingItem if it has been removed from the schedule
  23823. this.waitingItem = this.updateItem(this.waitingItem);
  23824. this.endedItem = this.updateItem(this.endedItem);
  23825. }
  23826. // Do not replace Interstitial bufferingItem without a match - used for transfering media element or source
  23827. const bufferingItem = this.bufferingItem;
  23828. if (bufferingItem) {
  23829. const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);
  23830. if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  23831. this.bufferingItem = updatedBufferingItem;
  23832. trimInPlaceForPlayout || (trimInPlaceForPlayout = () => this.trimInPlace(updatedBufferingItem, bufferingItem));
  23833. } else if (bufferingItem.event) {
  23834. // Interstitial removed from schedule (Live -> VOD or other scenario where Start Date is outside the range of VOD Playlist)
  23835. this.bufferingItem = this.playingItem;
  23836. this.clearInterstitial(bufferingItem.event, null);
  23837. }
  23838. }
  23839. removedInterstitials.forEach(interstitial => {
  23840. interstitial.assetList.forEach(asset => {
  23841. this.clearAssetPlayer(asset.identifier, null);
  23842. });
  23843. });
  23844. if (interstitialsUpdated || previousItems) {
  23845. this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  23846. events: interstitialEvents.slice(0),
  23847. schedule: scheduleItems.slice(0),
  23848. durations,
  23849. removedIds
  23850. });
  23851. if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  23852. this.warn(`Interstitial "${playingItem.event.identifier}" removed while playing`);
  23853. this.primaryFallback(playingItem.event);
  23854. return;
  23855. }
  23856. if (trimInPlaceForPlayout) {
  23857. trimInPlaceForPlayout();
  23858. }
  23859. // Check is buffered to new Interstitial event boundary
  23860. // (Live update publishes Interstitial with new segment)
  23861. this.checkBuffer();
  23862. }
  23863. };
  23864. this.hls = hls;
  23865. this.HlsPlayerClass = HlsPlayerClass;
  23866. this.assetListLoader = new AssetListLoader(hls);
  23867. this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);
  23868. this.registerListeners();
  23869. }
  23870. registerListeners() {
  23871. const hls = this.hls;
  23872. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  23873. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23874. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  23875. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23876. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  23877. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  23878. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  23879. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23880. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  23881. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  23882. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  23883. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  23884. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  23885. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  23886. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  23887. hls.on(Events.ERROR, this.onError, this);
  23888. hls.on(Events.DESTROYING, this.onDestroying, this);
  23889. }
  23890. unregisterListeners() {
  23891. const hls = this.hls;
  23892. if (!hls) {
  23893. return;
  23894. }
  23895. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  23896. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23897. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  23898. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23899. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  23900. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  23901. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  23902. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  23903. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  23904. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  23905. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  23906. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  23907. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  23908. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  23909. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  23910. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  23911. hls.off(Events.ERROR, this.onError, this);
  23912. hls.off(Events.DESTROYING, this.onDestroying, this);
  23913. }
  23914. startLoad() {
  23915. // TODO: startLoad - check for waitingItem and retry by resetting schedule
  23916. this.resumeBuffering();
  23917. }
  23918. stopLoad() {
  23919. // TODO: stopLoad - stop all scheule.events[].assetListLoader?.abort() then delete the loaders
  23920. this.pauseBuffering();
  23921. }
  23922. resumeBuffering() {
  23923. var _this$getBufferingPla;
  23924. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  23925. }
  23926. pauseBuffering() {
  23927. var _this$getBufferingPla2;
  23928. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  23929. }
  23930. destroy() {
  23931. this.unregisterListeners();
  23932. this.stopLoad();
  23933. if (this.assetListLoader) {
  23934. this.assetListLoader.destroy();
  23935. }
  23936. this.emptyPlayerQueue();
  23937. this.clearScheduleState();
  23938. if (this.schedule) {
  23939. this.schedule.destroy();
  23940. }
  23941. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  23942. // @ts-ignore
  23943. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  23944. // @ts-ignore
  23945. this.assetListLoader = null;
  23946. // @ts-ignore
  23947. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  23948. // @ts-ignore
  23949. this.onScheduleUpdate = null;
  23950. }
  23951. onDestroying() {
  23952. const media = this.primaryMedia || this.media;
  23953. if (media) {
  23954. this.removeMediaListeners(media);
  23955. }
  23956. }
  23957. removeMediaListeners(media) {
  23958. removeEventListener(media, 'play', this.onPlay);
  23959. removeEventListener(media, 'pause', this.onPause);
  23960. removeEventListener(media, 'seeking', this.onSeeking);
  23961. removeEventListener(media, 'timeupdate', this.onTimeupdate);
  23962. }
  23963. onMediaAttaching(event, data) {
  23964. const media = this.media = data.media;
  23965. addEventListener(media, 'seeking', this.onSeeking);
  23966. addEventListener(media, 'timeupdate', this.onTimeupdate);
  23967. addEventListener(media, 'play', this.onPlay);
  23968. addEventListener(media, 'pause', this.onPause);
  23969. }
  23970. onMediaAttached(event, data) {
  23971. const playingItem = this.effectivePlayingItem;
  23972. const detachedMedia = this.detachedData;
  23973. this.detachedData = null;
  23974. if (playingItem === null) {
  23975. this.checkStart();
  23976. } else if (!detachedMedia) {
  23977. // Resume schedule after detached externally
  23978. this.clearScheduleState();
  23979. const playingIndex = this.findItemIndex(playingItem);
  23980. this.setSchedulePosition(playingIndex);
  23981. }
  23982. }
  23983. clearScheduleState() {
  23984. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  23985. }
  23986. onMediaDetaching(event, data) {
  23987. const transferringMedia = !!data.transferMedia;
  23988. const media = this.media;
  23989. this.media = null;
  23990. if (transferringMedia) {
  23991. return;
  23992. }
  23993. if (media) {
  23994. this.removeMediaListeners(media);
  23995. }
  23996. // If detachMedia is called while in an Interstitial, detach the asset player as well and reset the schedule position
  23997. if (this.detachedData) {
  23998. const player = this.getBufferingPlayer();
  23999. if (player) {
  24000. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  24001. player.detachMedia();
  24002. }
  24003. this.shouldPlay = false;
  24004. }
  24005. }
  24006. get interstitialsManager() {
  24007. if (!this.manager) {
  24008. if (!this.hls) {
  24009. return null;
  24010. }
  24011. const c = this;
  24012. const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;
  24013. const getAssetPlayer = asset => asset ? c.getAssetPlayer(asset.identifier) : asset;
  24014. const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {
  24015. if (item) {
  24016. let time = item[timelineType].start;
  24017. const interstitial = item.event;
  24018. if (interstitial) {
  24019. if (timelineType === 'playout' || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  24020. const assetPlayer = getAssetPlayer(asset);
  24021. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  24022. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  24023. }
  24024. }
  24025. } else {
  24026. const value = controllerField === 'bufferedPos' ? getBufferedEnd() : c[controllerField];
  24027. time += value - item.start;
  24028. }
  24029. return time;
  24030. }
  24031. return 0;
  24032. };
  24033. const findMappedTime = (primaryTime, timelineType) => {
  24034. if (primaryTime !== 0 && timelineType !== 'primary' && c.schedule.length) {
  24035. var _c$schedule$items;
  24036. const index = c.schedule.findItemIndexAtTime(primaryTime);
  24037. const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
  24038. if (item) {
  24039. const diff = item[timelineType].start - item.start;
  24040. return primaryTime + diff;
  24041. }
  24042. }
  24043. return primaryTime;
  24044. };
  24045. const getBufferedEnd = () => {
  24046. const value = c.bufferedPos;
  24047. if (value === Number.MAX_VALUE) {
  24048. return getMappedDuration('primary');
  24049. }
  24050. return Math.max(value, 0);
  24051. };
  24052. const getMappedDuration = timelineType => {
  24053. var _c$primaryDetails;
  24054. if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
  24055. // return end of last event item or playlist
  24056. return c.primaryDetails.edge;
  24057. }
  24058. return c.schedule.durations[timelineType];
  24059. };
  24060. const seekTo = (time, timelineType) => {
  24061. var _item$event, _c$schedule$items2;
  24062. const item = c.effectivePlayingItem;
  24063. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  24064. return;
  24065. }
  24066. c.log(`seek to ${time} "${timelineType}"`);
  24067. const playingItem = c.effectivePlayingItem;
  24068. const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
  24069. const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  24070. const bufferingPlayer = c.getBufferingPlayer();
  24071. const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  24072. const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  24073. const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
  24074. if (playingItem && (appendInPlace || seekInItem)) {
  24075. // seek in asset player or primary media (appendInPlace)
  24076. const assetPlayer = getAssetPlayer(c.playingAsset);
  24077. const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
  24078. if (media) {
  24079. const currentTime = timelineType === 'primary' ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, 'timelinePos', 'currentTime');
  24080. const diff = time - currentTime;
  24081. const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  24082. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  24083. media.currentTime = seekToTime;
  24084. return;
  24085. }
  24086. }
  24087. }
  24088. // seek out of item or asset
  24089. if (targetItem) {
  24090. let seekToTime = time;
  24091. if (timelineType !== 'primary') {
  24092. const primarySegmentStart = targetItem[timelineType].start;
  24093. const diff = time - primarySegmentStart;
  24094. seekToTime = targetItem.start + diff;
  24095. }
  24096. const targetIsPrimary = !c.isInterstitial(targetItem);
  24097. if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  24098. const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  24099. if (media) {
  24100. media.currentTime = seekToTime;
  24101. }
  24102. } else if (playingItem) {
  24103. // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction
  24104. const playingIndex = c.findItemIndex(playingItem);
  24105. if (targetIndex > playingIndex) {
  24106. const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  24107. if (jumpIndex > playingIndex) {
  24108. c.setSchedulePosition(jumpIndex);
  24109. return;
  24110. }
  24111. }
  24112. let assetIndex = 0;
  24113. if (targetIsPrimary) {
  24114. c.timelinePos = seekToTime;
  24115. c.checkBuffer();
  24116. } else {
  24117. var _targetItem$event;
  24118. const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  24119. if (assetList) {
  24120. const eventTime = time - (targetItem[timelineType] || targetItem).start;
  24121. for (let i = assetList.length; i--;) {
  24122. const asset = assetList[i];
  24123. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  24124. assetIndex = i;
  24125. break;
  24126. }
  24127. }
  24128. }
  24129. }
  24130. c.setSchedulePosition(targetIndex, assetIndex);
  24131. }
  24132. }
  24133. };
  24134. const getActiveInterstitial = () => {
  24135. const playingItem = c.effectivePlayingItem;
  24136. if (c.isInterstitial(playingItem)) {
  24137. return playingItem;
  24138. }
  24139. const bufferingItem = effectiveBufferingItem();
  24140. if (c.isInterstitial(bufferingItem)) {
  24141. return bufferingItem;
  24142. }
  24143. return null;
  24144. };
  24145. const interstitialPlayer = {
  24146. get currentTime() {
  24147. const interstitialItem = getActiveInterstitial();
  24148. const playingItem = c.effectivePlayingItem;
  24149. if (playingItem && playingItem === interstitialItem) {
  24150. return getMappedTime(playingItem, 'playout', c.effectivePlayingAsset, 'timelinePos', 'currentTime') - playingItem.playout.start;
  24151. }
  24152. return 0;
  24153. },
  24154. set currentTime(time) {
  24155. const interstitialItem = getActiveInterstitial();
  24156. const playingItem = c.effectivePlayingItem;
  24157. if (playingItem && playingItem === interstitialItem) {
  24158. seekTo(time + playingItem.playout.start, 'playout');
  24159. }
  24160. },
  24161. get duration() {
  24162. const interstitialItem = getActiveInterstitial();
  24163. if (interstitialItem) {
  24164. return interstitialItem.playout.end - interstitialItem.playout.start;
  24165. }
  24166. return 0;
  24167. },
  24168. get assetPlayers() {
  24169. var _getActiveInterstitia;
  24170. const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  24171. if (assetList) {
  24172. return assetList.map(asset => c.getAssetPlayer(asset.identifier));
  24173. }
  24174. return [];
  24175. },
  24176. get playingIndex() {
  24177. var _getActiveInterstitia2;
  24178. const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  24179. if (interstitial && c.effectivePlayingAsset) {
  24180. return interstitial.findAssetIndex(c.effectivePlayingAsset);
  24181. }
  24182. return -1;
  24183. },
  24184. get scheduleItem() {
  24185. return getActiveInterstitial();
  24186. }
  24187. };
  24188. this.manager = {
  24189. get events() {
  24190. var _c$schedule, _c$schedule$events;
  24191. return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  24192. },
  24193. get schedule() {
  24194. var _c$schedule2, _c$schedule2$items;
  24195. return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  24196. },
  24197. get interstitialPlayer() {
  24198. if (getActiveInterstitial()) {
  24199. return interstitialPlayer;
  24200. }
  24201. return null;
  24202. },
  24203. get playerQueue() {
  24204. return c.playerQueue.slice(0);
  24205. },
  24206. get bufferingAsset() {
  24207. return c.bufferingAsset;
  24208. },
  24209. get bufferingItem() {
  24210. return effectiveBufferingItem();
  24211. },
  24212. get bufferingIndex() {
  24213. const item = effectiveBufferingItem();
  24214. return c.findItemIndex(item);
  24215. },
  24216. get playingAsset() {
  24217. return c.effectivePlayingAsset;
  24218. },
  24219. get playingItem() {
  24220. return c.effectivePlayingItem;
  24221. },
  24222. get playingIndex() {
  24223. const item = c.effectivePlayingItem;
  24224. return c.findItemIndex(item);
  24225. },
  24226. primary: {
  24227. get bufferedEnd() {
  24228. return getBufferedEnd();
  24229. },
  24230. get currentTime() {
  24231. const timelinePos = c.timelinePos;
  24232. return timelinePos > 0 ? timelinePos : 0;
  24233. },
  24234. set currentTime(time) {
  24235. seekTo(time, 'primary');
  24236. },
  24237. get duration() {
  24238. return getMappedDuration('primary');
  24239. },
  24240. get seekableStart() {
  24241. var _c$primaryDetails2;
  24242. return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  24243. }
  24244. },
  24245. integrated: {
  24246. get bufferedEnd() {
  24247. return getMappedTime(effectiveBufferingItem(), 'integrated', c.bufferingAsset, 'bufferedPos', 'bufferedEnd');
  24248. },
  24249. get currentTime() {
  24250. return getMappedTime(c.effectivePlayingItem, 'integrated', c.effectivePlayingAsset, 'timelinePos', 'currentTime');
  24251. },
  24252. set currentTime(time) {
  24253. seekTo(time, 'integrated');
  24254. },
  24255. get duration() {
  24256. return getMappedDuration('integrated');
  24257. },
  24258. get seekableStart() {
  24259. var _c$primaryDetails3;
  24260. return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, 'integrated');
  24261. }
  24262. },
  24263. skip: () => {
  24264. const item = c.effectivePlayingItem;
  24265. const event = item == null ? void 0 : item.event;
  24266. if (event && !event.restrictions.skip) {
  24267. const index = c.findItemIndex(item);
  24268. if (event.appendInPlace) {
  24269. const time = item.playout.start + item.event.duration;
  24270. seekTo(time + 0.001, 'playout');
  24271. } else {
  24272. c.advanceAfterAssetEnded(event, index, Infinity);
  24273. }
  24274. }
  24275. }
  24276. };
  24277. }
  24278. return this.manager;
  24279. }
  24280. // Schedule getters
  24281. get effectivePlayingItem() {
  24282. return this.waitingItem || this.playingItem || this.endedItem;
  24283. }
  24284. get effectivePlayingAsset() {
  24285. return this.playingAsset || this.endedAsset;
  24286. }
  24287. get playingLastItem() {
  24288. var _this$schedule;
  24289. const playingItem = this.playingItem;
  24290. const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  24291. if (!this.playbackStarted || !playingItem || !items) {
  24292. return false;
  24293. }
  24294. return this.findItemIndex(playingItem) === items.length - 1;
  24295. }
  24296. get playbackStarted() {
  24297. return this.effectivePlayingItem !== null;
  24298. }
  24299. // Media getters and event callbacks
  24300. get currentTime() {
  24301. var _this$bufferingItem, _this$bufferingItem$e, _media;
  24302. if (this.mediaSelection === null) {
  24303. // Do not advance before schedule is known
  24304. return undefined;
  24305. }
  24306. // Ignore currentTime when detached for Interstitial playback with source reset
  24307. const queuedForPlayback = this.waitingItem || this.playingItem;
  24308. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  24309. return undefined;
  24310. }
  24311. let media = this.media;
  24312. if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {
  24313. // Observe detached media currentTime when appending in place
  24314. media = this.primaryMedia;
  24315. }
  24316. const currentTime = (_media = media) == null ? void 0 : _media.currentTime;
  24317. if (currentTime === undefined || !isFiniteNumber(currentTime)) {
  24318. return undefined;
  24319. }
  24320. return currentTime;
  24321. }
  24322. get primaryMedia() {
  24323. var _this$detachedData;
  24324. return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;
  24325. }
  24326. isInterstitial(item) {
  24327. return !!(item != null && item.event);
  24328. }
  24329. retreiveMediaSource(assetId, toSegment) {
  24330. const player = this.getAssetPlayer(assetId);
  24331. if (player) {
  24332. this.transferMediaFromPlayer(player, toSegment);
  24333. }
  24334. }
  24335. transferMediaFromPlayer(player, toSegment) {
  24336. const appendInPlace = player.interstitial.appendInPlace;
  24337. const playerMedia = player.media;
  24338. if (appendInPlace && playerMedia === this.primaryMedia) {
  24339. this.bufferingAsset = null;
  24340. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  24341. // MediaSource cannot be transfered back to an Interstitial that requires a source reset
  24342. // no-op when toSegment is undefined
  24343. if (toSegment && playerMedia) {
  24344. this.detachedData = {
  24345. media: playerMedia
  24346. };
  24347. return;
  24348. }
  24349. }
  24350. const attachMediaSourceData = player.transferMedia();
  24351. this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);
  24352. this.detachedData = attachMediaSourceData;
  24353. } else if (toSegment && playerMedia) {
  24354. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  24355. }
  24356. }
  24357. transferMediaTo(player, media) {
  24358. var _this$detachedData2, _attachMediaSourceDat;
  24359. if (player.media === media) {
  24360. return;
  24361. }
  24362. let attachMediaSourceData = null;
  24363. const primaryPlayer = this.hls;
  24364. const isAssetPlayer = player !== primaryPlayer;
  24365. const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  24366. const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;
  24367. let logFromSource;
  24368. if (primaryPlayer.media) {
  24369. if (appendInPlace) {
  24370. attachMediaSourceData = primaryPlayer.transferMedia();
  24371. this.detachedData = attachMediaSourceData;
  24372. }
  24373. logFromSource = `Primary`;
  24374. } else if (detachedMediaSource) {
  24375. const bufferingPlayer = this.getBufferingPlayer();
  24376. if (bufferingPlayer) {
  24377. attachMediaSourceData = bufferingPlayer.transferMedia();
  24378. logFromSource = `${bufferingPlayer}`;
  24379. } else {
  24380. logFromSource = `detached MediaSource`;
  24381. }
  24382. } else {
  24383. logFromSource = `detached media`;
  24384. }
  24385. if (!attachMediaSourceData) {
  24386. if (detachedMediaSource) {
  24387. attachMediaSourceData = this.detachedData;
  24388. this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);
  24389. } else if (!this.detachedData || primaryPlayer.media === media) {
  24390. // Keep interstitial media transition consistent
  24391. const playerQueue = this.playerQueue;
  24392. if (playerQueue.length > 1) {
  24393. playerQueue.forEach(queuedPlayer => {
  24394. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  24395. const interstitial = queuedPlayer.interstitial;
  24396. this.clearInterstitial(queuedPlayer.interstitial, null);
  24397. interstitial.appendInPlace = false;
  24398. if (interstitial.appendInPlace) {
  24399. this.warn(`Could not change append strategy for queued assets ${interstitial}`);
  24400. }
  24401. }
  24402. });
  24403. }
  24404. this.hls.detachMedia();
  24405. this.detachedData = {
  24406. media
  24407. };
  24408. }
  24409. }
  24410. const transferring = attachMediaSourceData && 'mediaSource' in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== 'closed';
  24411. const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  24412. this.log(`${transferring ? 'transfering MediaSource' : 'attaching media'} to ${isAssetPlayer ? player : 'Primary'} from ${logFromSource}`);
  24413. if (dataToAttach === attachMediaSourceData) {
  24414. const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  24415. // Prevent asset players from marking EoS on transferred MediaSource
  24416. dataToAttach.overrides = {
  24417. duration: this.schedule.duration,
  24418. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  24419. cueRemoval: !isAssetPlayer
  24420. };
  24421. }
  24422. player.attachMedia(dataToAttach);
  24423. }
  24424. onInterstitialCueEnter() {
  24425. this.onTimeupdate();
  24426. }
  24427. // Scheduling methods
  24428. checkStart() {
  24429. const schedule = this.schedule;
  24430. const interstitialEvents = schedule.events;
  24431. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  24432. return;
  24433. }
  24434. // Check buffered to pre-roll
  24435. if (this.bufferedPos === -1) {
  24436. this.bufferedPos = 0;
  24437. }
  24438. // Start stepping through schedule when playback begins for the first time and we have a pre-roll
  24439. const timelinePos = this.timelinePos;
  24440. const effectivePlayingItem = this.effectivePlayingItem;
  24441. if (timelinePos === -1) {
  24442. const startPosition = this.hls.startPosition;
  24443. this.timelinePos = startPosition;
  24444. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  24445. const index = schedule.findEventIndex(interstitialEvents[0].identifier);
  24446. this.setSchedulePosition(index);
  24447. } else if (startPosition >= 0 || !this.primaryLive) {
  24448. const start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  24449. const index = schedule.findItemIndexAtTime(start);
  24450. this.setSchedulePosition(index);
  24451. }
  24452. } else if (effectivePlayingItem && !this.playingItem) {
  24453. const index = schedule.findItemIndex(effectivePlayingItem);
  24454. this.setSchedulePosition(index);
  24455. }
  24456. }
  24457. advanceAfterAssetEnded(interstitial, index, assetListIndex) {
  24458. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  24459. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  24460. // Advance to next asset list item
  24461. this.setSchedulePosition(index, nextAssetIndex);
  24462. } else {
  24463. // Advance to next schedule segment
  24464. // check if we've reached the end of the program
  24465. const scheduleItems = this.schedule.items;
  24466. if (scheduleItems) {
  24467. const nextIndex = index + 1;
  24468. const scheduleLength = scheduleItems.length;
  24469. if (nextIndex >= scheduleLength) {
  24470. this.setSchedulePosition(-1);
  24471. return;
  24472. }
  24473. const resumptionTime = interstitial.resumeTime;
  24474. if (this.timelinePos < resumptionTime) {
  24475. this.timelinePos = resumptionTime;
  24476. this.checkBuffer();
  24477. }
  24478. this.setSchedulePosition(nextIndex);
  24479. }
  24480. }
  24481. }
  24482. setScheduleToAssetAtTime(time, playingAsset) {
  24483. const schedule = this.schedule;
  24484. const parentIdentifier = playingAsset.parentIdentifier;
  24485. const interstitial = schedule.getEvent(parentIdentifier);
  24486. if (interstitial) {
  24487. const itemIndex = schedule.findEventIndex(parentIdentifier);
  24488. const assetListIndex = schedule.findAssetIndex(interstitial, time);
  24489. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  24490. }
  24491. }
  24492. setSchedulePosition(index, assetListIndex) {
  24493. const scheduleItems = this.schedule.items;
  24494. if (!scheduleItems || this.playbackDisabled) {
  24495. return;
  24496. }
  24497. this.log(`setSchedulePosition ${index}, ${assetListIndex}`);
  24498. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  24499. // Cleanup current item / asset
  24500. const currentItem = this.playingItem;
  24501. const playingLastItem = this.playingLastItem;
  24502. if (this.isInterstitial(currentItem)) {
  24503. var _interstitial$assetLi;
  24504. const interstitial = currentItem.event;
  24505. const playingAsset = this.playingAsset;
  24506. const assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  24507. const player = assetId ? this.getAssetPlayer(assetId) : null;
  24508. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== undefined && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  24509. var _this$detachedData3;
  24510. const playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  24511. this.log(`INTERSTITIAL_ASSET_ENDED ${playingAssetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);
  24512. this.endedAsset = playingAsset;
  24513. this.playingAsset = null;
  24514. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  24515. asset: playingAsset,
  24516. assetListIndex: playingAssetListIndex,
  24517. event: interstitial,
  24518. schedule: scheduleItems.slice(0),
  24519. scheduleIndex: index,
  24520. player
  24521. });
  24522. if (currentItem !== this.playingItem) {
  24523. // Schedule change occured on INTERSTITIAL_ASSET_ENDED
  24524. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  24525. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  24526. }
  24527. // Navigation occured on INTERSTITIAL_ASSET_ENDED
  24528. return;
  24529. }
  24530. this.retreiveMediaSource(assetId, scheduledItem);
  24531. if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  24532. player.detachMedia();
  24533. }
  24534. }
  24535. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  24536. this.endedItem = currentItem;
  24537. this.playingItem = null;
  24538. this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);
  24539. interstitial.hasPlayed = true;
  24540. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  24541. event: interstitial,
  24542. schedule: scheduleItems.slice(0),
  24543. scheduleIndex: index
  24544. });
  24545. // Exiting an Interstitial
  24546. if (interstitial.cue.once) {
  24547. // Remove interstitial with CUE attribute value of ONCE after it has played
  24548. this.updateSchedule();
  24549. const items = this.schedule.items;
  24550. if (scheduledItem && items) {
  24551. const updatedIndex = this.findItemIndex(scheduledItem);
  24552. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  24553. }
  24554. return;
  24555. }
  24556. }
  24557. }
  24558. this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  24559. }
  24560. advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  24561. const scheduledItem = index >= 0 ? scheduleItems[index] : null;
  24562. const media = this.primaryMedia;
  24563. // Cleanup out of range Interstitials
  24564. const playerQueue = this.playerQueue;
  24565. if (playerQueue.length) {
  24566. playerQueue.forEach(player => {
  24567. const interstitial = player.interstitial;
  24568. const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);
  24569. if (queuedIndex < index || queuedIndex > index + 1) {
  24570. this.clearInterstitial(interstitial, scheduledItem);
  24571. }
  24572. });
  24573. }
  24574. // Setup scheduled item
  24575. if (this.isInterstitial(scheduledItem)) {
  24576. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  24577. // Handle Interstitial
  24578. const interstitial = scheduledItem.event;
  24579. // find asset index
  24580. if (assetListIndex === undefined) {
  24581. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  24582. const assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  24583. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  24584. this.advanceAfterAssetEnded(interstitial, index, assetListIndex);
  24585. return;
  24586. }
  24587. assetListIndex = assetIndexCandidate;
  24588. }
  24589. // Ensure Interstitial is enqueued
  24590. const waitingItem = this.waitingItem;
  24591. if (!this.assetsBuffered(scheduledItem, media)) {
  24592. this.setBufferingItem(scheduledItem);
  24593. }
  24594. let player = this.preloadAssets(interstitial, assetListIndex);
  24595. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  24596. this.waitingItem = scheduledItem;
  24597. this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? 'append in place' : ''}`);
  24598. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  24599. event: interstitial,
  24600. schedule: scheduleItems.slice(0),
  24601. scheduleIndex: index
  24602. });
  24603. }
  24604. if (!interstitial.assetListLoaded) {
  24605. // Waiting at end of primary content segment
  24606. // Expect setSchedulePosition to be called again once ASSET-LIST is loaded
  24607. this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);
  24608. return;
  24609. }
  24610. if (interstitial.assetListLoader) {
  24611. interstitial.assetListLoader.destroy();
  24612. interstitial.assetListLoader = undefined;
  24613. }
  24614. if (!media) {
  24615. this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);
  24616. return;
  24617. }
  24618. // Update schedule and asset list position now that it can start
  24619. this.waitingItem = this.endedItem = null;
  24620. this.playingItem = scheduledItem;
  24621. // If asset-list is empty or missing asset index, advance to next item
  24622. const assetItem = interstitial.assetList[assetListIndex];
  24623. if (!assetItem) {
  24624. const nextItem = scheduleItems[index + 1];
  24625. const _media2 = this.media;
  24626. if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {
  24627. _media2.currentTime = this.timelinePos = nextItem.start;
  24628. }
  24629. this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
  24630. return;
  24631. }
  24632. // Start Interstitial Playback
  24633. if (!player) {
  24634. player = this.getAssetPlayer(assetItem.identifier);
  24635. }
  24636. if (player === null || player.destroyed) {
  24637. const assetListLength = interstitial.assetList.length;
  24638. this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);
  24639. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  24640. }
  24641. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  24642. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  24643. return;
  24644. }
  24645. }
  24646. this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
  24647. if (this.shouldPlay) {
  24648. playWithCatch(player.media);
  24649. }
  24650. } else if (scheduledItem !== null) {
  24651. this.resumePrimary(scheduledItem, index, currentItem);
  24652. if (this.shouldPlay) {
  24653. playWithCatch(this.hls.media);
  24654. }
  24655. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  24656. // Maintain playingItem state at end of schedule (setSchedulePosition(-1) called to end program)
  24657. // this allows onSeeking handler to update schedule position
  24658. this.endedItem = null;
  24659. this.playingItem = currentItem;
  24660. if (!currentItem.event.appendInPlace) {
  24661. // Media must be re-attached to resume primary schedule if not sharing source
  24662. this.attachPrimary(this.schedule.durations.primary, null);
  24663. }
  24664. }
  24665. }
  24666. get playbackDisabled() {
  24667. return this.hls.config.enableInterstitialPlayback === false;
  24668. }
  24669. get primaryDetails() {
  24670. var _this$mediaSelection, _this$mediaSelection$;
  24671. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  24672. }
  24673. get primaryLive() {
  24674. var _this$primaryDetails;
  24675. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  24676. }
  24677. resumePrimary(scheduledItem, index, fromItem) {
  24678. var _this$detachedData4;
  24679. this.playingItem = scheduledItem;
  24680. this.playingAsset = this.endedAsset = null;
  24681. this.waitingItem = this.endedItem = null;
  24682. this.bufferedToItem(scheduledItem);
  24683. this.log(`resuming ${segmentToString(scheduledItem)}`);
  24684. if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {
  24685. let timelinePos = this.timelinePos;
  24686. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  24687. timelinePos = this.getPrimaryResumption(scheduledItem, index);
  24688. this.timelinePos = timelinePos;
  24689. }
  24690. this.attachPrimary(timelinePos, scheduledItem);
  24691. }
  24692. if (!fromItem) {
  24693. return;
  24694. }
  24695. const scheduleItems = this.schedule.items;
  24696. if (!scheduleItems) {
  24697. return;
  24698. }
  24699. this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(scheduledItem)}`);
  24700. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  24701. schedule: scheduleItems.slice(0),
  24702. scheduleIndex: index
  24703. });
  24704. this.checkBuffer();
  24705. }
  24706. getPrimaryResumption(scheduledItem, index) {
  24707. const itemStart = scheduledItem.start;
  24708. if (this.primaryLive) {
  24709. const details = this.primaryDetails;
  24710. if (index === 0) {
  24711. return this.hls.startPosition;
  24712. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  24713. return this.hls.liveSyncPosition || -1;
  24714. }
  24715. }
  24716. return itemStart;
  24717. }
  24718. isAssetBuffered(asset) {
  24719. const player = this.getAssetPlayer(asset.identifier);
  24720. if (player != null && player.hls) {
  24721. return player.hls.bufferedToEnd;
  24722. }
  24723. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  24724. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  24725. }
  24726. attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  24727. if (item) {
  24728. this.setBufferingItem(item);
  24729. } else {
  24730. this.bufferingItem = this.playingItem;
  24731. }
  24732. this.bufferingAsset = null;
  24733. const media = this.primaryMedia;
  24734. if (!media) {
  24735. return;
  24736. }
  24737. const hls = this.hls;
  24738. if (hls.media) {
  24739. this.checkBuffer();
  24740. } else {
  24741. this.transferMediaTo(hls, media);
  24742. if (skipSeekToStartPosition) {
  24743. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  24744. }
  24745. }
  24746. if (!skipSeekToStartPosition) {
  24747. // Set primary position to resume time
  24748. this.timelinePos = timelinePos;
  24749. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  24750. }
  24751. }
  24752. startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  24753. var _hls$mainForwardBuffe;
  24754. const hls = this.hls;
  24755. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  24756. hls.startLoad(timelinePos, skipSeekToStartPosition);
  24757. } else if (!hls.bufferingEnabled) {
  24758. hls.resumeBuffering();
  24759. }
  24760. }
  24761. // HLS.js event callbacks
  24762. onManifestLoading() {
  24763. this.stopLoad();
  24764. this.schedule.reset();
  24765. this.emptyPlayerQueue();
  24766. this.clearScheduleState();
  24767. this.shouldPlay = false;
  24768. this.bufferedPos = this.timelinePos = -1;
  24769. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  24770. // BUFFER_CODECS listener added here for buffer-controller to handle it first where it adds tracks
  24771. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24772. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24773. }
  24774. onLevelUpdated(event, data) {
  24775. if (data.level === -1) {
  24776. // level was removed
  24777. return;
  24778. }
  24779. const main = this.hls.levels[data.level];
  24780. const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  24781. main
  24782. });
  24783. this.mediaSelection = currentSelection;
  24784. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  24785. if (!this.effectivePlayingItem && this.schedule.items) {
  24786. this.checkStart();
  24787. }
  24788. }
  24789. onAudioTrackUpdated(event, data) {
  24790. const audio = this.hls.audioTracks[data.id];
  24791. const previousSelection = this.mediaSelection;
  24792. if (!previousSelection) {
  24793. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  24794. audio
  24795. });
  24796. return;
  24797. }
  24798. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  24799. audio
  24800. });
  24801. this.mediaSelection = currentSelection;
  24802. }
  24803. onSubtitleTrackUpdated(event, data) {
  24804. const subtitles = this.hls.subtitleTracks[data.id];
  24805. const previousSelection = this.mediaSelection;
  24806. if (!previousSelection) {
  24807. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  24808. subtitles
  24809. });
  24810. return;
  24811. }
  24812. const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  24813. subtitles
  24814. });
  24815. this.mediaSelection = currentSelection;
  24816. }
  24817. onAudioTrackSwitching(event, data) {
  24818. const audioOption = getBasicSelectionOption(data);
  24819. this.playerQueue.forEach(player => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));
  24820. }
  24821. onSubtitleTrackSwitch(event, data) {
  24822. const subtitleOption = getBasicSelectionOption(data);
  24823. this.playerQueue.forEach(player => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));
  24824. }
  24825. onBufferCodecs(event, data) {
  24826. const requiredTracks = data.tracks;
  24827. if (requiredTracks) {
  24828. this.requiredTracks = requiredTracks;
  24829. }
  24830. }
  24831. onBufferAppended(event, data) {
  24832. this.checkBuffer();
  24833. }
  24834. onBufferFlushed(event, data) {
  24835. const playingItem = this.playingItem;
  24836. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  24837. const timelinePos = this.timelinePos;
  24838. this.bufferedPos = timelinePos;
  24839. this.checkBuffer();
  24840. }
  24841. }
  24842. onBufferedToEnd(event) {
  24843. // Buffered to post-roll
  24844. const interstitialEvents = this.schedule.events;
  24845. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  24846. for (let i = 0; i < interstitialEvents.length; i++) {
  24847. const interstitial = interstitialEvents[i];
  24848. if (interstitial.cue.post) {
  24849. var _this$schedule$items;
  24850. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  24851. const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  24852. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  24853. this.bufferedToItem(item, 0);
  24854. }
  24855. break;
  24856. }
  24857. }
  24858. this.bufferedPos = Number.MAX_VALUE;
  24859. }
  24860. }
  24861. onMediaEnded(event) {
  24862. const playingItem = this.playingItem;
  24863. if (!this.playingLastItem && playingItem) {
  24864. const playingIndex = this.findItemIndex(playingItem);
  24865. this.setSchedulePosition(playingIndex + 1);
  24866. } else {
  24867. this.shouldPlay = false;
  24868. }
  24869. }
  24870. updateItem(previousItem, time) {
  24871. // find item in this.schedule.items;
  24872. const items = this.schedule.items;
  24873. if (previousItem && items) {
  24874. const index = this.findItemIndex(previousItem, time);
  24875. return items[index] || null;
  24876. }
  24877. return null;
  24878. }
  24879. trimInPlace(updatedItem, itemBeforeUpdate) {
  24880. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  24881. updatedItem.event.assetList.forEach((asset, index) => {
  24882. if (updatedItem.event.isAssetPastPlayoutLimit(index)) {
  24883. this.clearAssetPlayer(asset.identifier, null);
  24884. }
  24885. });
  24886. const flushStart = updatedItem.end + 0.25;
  24887. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  24888. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  24889. this.attachPrimary(flushStart, null);
  24890. this.flushFrontBuffer(flushStart);
  24891. }
  24892. }
  24893. }
  24894. itemsMatch(a, b) {
  24895. return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  24896. }
  24897. eventItemsMatch(a, b) {
  24898. var _b$event;
  24899. return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  24900. }
  24901. findItemIndex(item, time) {
  24902. return item ? this.schedule.findItemIndex(item, time) : -1;
  24903. }
  24904. updateSchedule() {
  24905. const mediaSelection = this.mediaSelection;
  24906. if (!mediaSelection) {
  24907. return;
  24908. }
  24909. this.schedule.updateSchedule(mediaSelection, []);
  24910. }
  24911. // Schedule buffer control
  24912. checkBuffer(starved) {
  24913. const items = this.schedule.items;
  24914. if (!items) {
  24915. return;
  24916. }
  24917. // Find when combined forward buffer change reaches next schedule segment
  24918. const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  24919. if (starved) {
  24920. this.bufferedPos = this.timelinePos;
  24921. }
  24922. starved || (starved = bufferInfo.len < 1);
  24923. this.updateBufferedPos(bufferInfo.end, items, starved);
  24924. }
  24925. updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  24926. const schedule = this.schedule;
  24927. const bufferingItem = this.bufferingItem;
  24928. if (this.bufferedPos > bufferEnd) {
  24929. return;
  24930. }
  24931. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  24932. this.bufferedPos = bufferEnd;
  24933. return;
  24934. }
  24935. const playingItem = this.playingItem;
  24936. const playingIndex = this.findItemIndex(playingItem);
  24937. let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  24938. if (this.bufferedPos < bufferEnd) {
  24939. var _nextItemToBuffer$eve, _bufferingItem$event;
  24940. const bufferingIndex = this.findItemIndex(bufferingItem);
  24941. const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  24942. const nextItemToBuffer = items[nextToBufferIndex];
  24943. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  24944. bufferEndIndex = nextToBufferIndex;
  24945. }
  24946. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  24947. // do not advance buffering item past Interstitial that requires source reset
  24948. return;
  24949. }
  24950. this.bufferedPos = bufferEnd;
  24951. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  24952. this.bufferedToItem(nextItemToBuffer);
  24953. } else {
  24954. // allow more time than distance from edge for assets to load
  24955. const details = this.primaryDetails;
  24956. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  24957. this.preloadAssets(nextItemToBuffer.event, 0);
  24958. }
  24959. }
  24960. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  24961. if (bufferEndIndex === playingIndex) {
  24962. this.bufferedToItem(playingItem);
  24963. } else if (bufferEndIndex === playingIndex + 1) {
  24964. this.bufferedToItem(items[bufferEndIndex]);
  24965. }
  24966. }
  24967. }
  24968. assetsBuffered(item, media) {
  24969. const assetList = item.event.assetList;
  24970. if (assetList.length === 0) {
  24971. return false;
  24972. }
  24973. return !item.event.assetList.some(asset => {
  24974. const player = this.getAssetPlayer(asset.identifier);
  24975. return !(player != null && player.bufferedInPlaceToEnd(media));
  24976. });
  24977. }
  24978. setBufferingItem(item) {
  24979. const bufferingLast = this.bufferingItem;
  24980. const schedule = this.schedule;
  24981. if (!this.itemsMatch(item, bufferingLast)) {
  24982. const {
  24983. items,
  24984. events
  24985. } = schedule;
  24986. if (!items || !events) {
  24987. return bufferingLast;
  24988. }
  24989. const isInterstitial = this.isInterstitial(item);
  24990. const bufferingPlayer = this.getBufferingPlayer();
  24991. this.bufferingItem = item;
  24992. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  24993. const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  24994. this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ''));
  24995. if (!this.playbackDisabled) {
  24996. if (isInterstitial) {
  24997. // primary fragment loading will exit early in base-stream-controller while `bufferingItem` is set to an Interstitial block
  24998. item.event.assetList.forEach(asset => {
  24999. const player = this.getAssetPlayer(asset.identifier);
  25000. if (player) {
  25001. player.resumeBuffering();
  25002. }
  25003. });
  25004. } else {
  25005. this.hls.resumeBuffering();
  25006. this.playerQueue.forEach(player => player.pauseBuffering());
  25007. }
  25008. }
  25009. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  25010. events: events.slice(0),
  25011. schedule: items.slice(0),
  25012. bufferingIndex: this.findItemIndex(item),
  25013. playingIndex: this.findItemIndex(this.playingItem)
  25014. });
  25015. } else if (this.bufferingItem !== item) {
  25016. this.bufferingItem = item;
  25017. }
  25018. return bufferingLast;
  25019. }
  25020. bufferedToItem(item, assetListIndex = 0) {
  25021. const bufferingLast = this.setBufferingItem(item);
  25022. if (this.playbackDisabled) {
  25023. return;
  25024. }
  25025. if (this.isInterstitial(item)) {
  25026. // Ensure asset list is loaded
  25027. this.bufferedToEvent(item, assetListIndex);
  25028. } else if (bufferingLast !== null) {
  25029. // If primary player is detached, it is also stopped, restart loading at primary position
  25030. this.bufferingAsset = null;
  25031. const detachedData = this.detachedData;
  25032. if (detachedData) {
  25033. if (detachedData.mediaSource) {
  25034. const skipSeekToStartPosition = true;
  25035. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  25036. } else {
  25037. this.preloadPrimary(item);
  25038. }
  25039. } else {
  25040. // If not detached seek to resumption point
  25041. this.preloadPrimary(item);
  25042. }
  25043. }
  25044. }
  25045. preloadPrimary(item) {
  25046. const index = this.findItemIndex(item);
  25047. const timelinePos = this.getPrimaryResumption(item, index);
  25048. this.startLoadingPrimaryAt(timelinePos);
  25049. }
  25050. bufferedToEvent(item, assetListIndex) {
  25051. const interstitial = item.event;
  25052. const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  25053. const playOnce = interstitial.cue.once;
  25054. if (neverLoaded || !playOnce) {
  25055. // Buffered to Interstitial boundary
  25056. const player = this.preloadAssets(interstitial, assetListIndex);
  25057. if (player != null && player.interstitial.appendInPlace) {
  25058. // If we have a player and asset list info, start buffering
  25059. const assetItem = interstitial.assetList[assetListIndex];
  25060. const media = this.primaryMedia;
  25061. if (assetItem && media) {
  25062. this.bufferAssetPlayer(player, media);
  25063. }
  25064. }
  25065. }
  25066. }
  25067. preloadAssets(interstitial, assetListIndex) {
  25068. const uri = interstitial.assetUrl;
  25069. const assetListLength = interstitial.assetList.length;
  25070. const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  25071. const playOnce = interstitial.cue.once;
  25072. if (neverLoaded) {
  25073. const timelineStart = interstitial.timelineStart;
  25074. if (interstitial.appendInPlace) {
  25075. var _playingItem$nextEven;
  25076. const playingItem = this.playingItem;
  25077. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  25078. this.flushFrontBuffer(timelineStart + 0.25);
  25079. }
  25080. }
  25081. let hlsStartOffset;
  25082. let liveStartPosition = 0;
  25083. if (!this.playingItem && this.primaryLive) {
  25084. liveStartPosition = this.hls.startPosition;
  25085. if (liveStartPosition === -1) {
  25086. liveStartPosition = this.hls.liveSyncPosition || 0;
  25087. }
  25088. }
  25089. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  25090. const startOffset = liveStartPosition - timelineStart;
  25091. if (startOffset > 0) {
  25092. hlsStartOffset = Math.round(startOffset * 1000) / 1000;
  25093. }
  25094. }
  25095. this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ''}`);
  25096. if (uri) {
  25097. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  25098. }
  25099. const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  25100. if (assetListLoader) {
  25101. interstitial.assetListLoader = assetListLoader;
  25102. }
  25103. } else if (!playOnce && assetListLength) {
  25104. // Re-buffered to Interstitial boundary, re-create asset player(s)
  25105. for (let i = assetListIndex; i < assetListLength; i++) {
  25106. const asset = interstitial.assetList[i];
  25107. const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  25108. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  25109. this.createAssetPlayer(interstitial, asset, i);
  25110. }
  25111. }
  25112. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  25113. }
  25114. return null;
  25115. }
  25116. flushFrontBuffer(startOffset) {
  25117. // Force queued flushing of all buffers
  25118. const requiredTracks = this.requiredTracks;
  25119. if (!requiredTracks) {
  25120. return;
  25121. }
  25122. this.log(`Removing front buffer starting at ${startOffset}`);
  25123. const sourceBufferNames = Object.keys(requiredTracks);
  25124. sourceBufferNames.forEach(type => {
  25125. this.hls.trigger(Events.BUFFER_FLUSHING, {
  25126. startOffset,
  25127. endOffset: Infinity,
  25128. type
  25129. });
  25130. });
  25131. }
  25132. // Interstitial Asset Player control
  25133. getAssetPlayerQueueIndex(assetId) {
  25134. const playerQueue = this.playerQueue;
  25135. for (let i = 0; i < playerQueue.length; i++) {
  25136. if (assetId === playerQueue[i].assetId) {
  25137. return i;
  25138. }
  25139. }
  25140. return -1;
  25141. }
  25142. getAssetPlayer(assetId) {
  25143. const index = this.getAssetPlayerQueueIndex(assetId);
  25144. return this.playerQueue[index] || null;
  25145. }
  25146. getBufferingPlayer() {
  25147. const {
  25148. playerQueue,
  25149. primaryMedia
  25150. } = this;
  25151. if (primaryMedia) {
  25152. for (let i = 0; i < playerQueue.length; i++) {
  25153. if (playerQueue[i].media === primaryMedia) {
  25154. return playerQueue[i];
  25155. }
  25156. }
  25157. }
  25158. return null;
  25159. }
  25160. createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  25161. const assetItem = {
  25162. parentIdentifier: interstitial.identifier,
  25163. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  25164. duration,
  25165. startOffset,
  25166. timelineStart,
  25167. uri
  25168. };
  25169. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  25170. }
  25171. createAssetPlayer(interstitial, assetItem, assetListIndex) {
  25172. const primary = this.hls;
  25173. const userConfig = primary.userConfig;
  25174. let videoPreference = userConfig.videoPreference;
  25175. const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  25176. if (videoPreference || currentLevel) {
  25177. videoPreference = _extends({}, videoPreference);
  25178. if (currentLevel.videoCodec) {
  25179. videoPreference.videoCodec = currentLevel.videoCodec;
  25180. }
  25181. if (currentLevel.videoRange) {
  25182. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  25183. }
  25184. }
  25185. const selectedAudio = primary.audioTracks[primary.audioTrack];
  25186. const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  25187. let startPosition = 0;
  25188. if (this.primaryLive || interstitial.appendInPlace) {
  25189. const timePastStart = this.timelinePos - assetItem.timelineStart;
  25190. if (timePastStart > 1) {
  25191. const duration = assetItem.duration;
  25192. if (duration && timePastStart < duration) {
  25193. startPosition = timePastStart;
  25194. }
  25195. }
  25196. }
  25197. const assetId = assetItem.identifier;
  25198. const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  25199. autoStartLoad: true,
  25200. startFragPrefetch: true,
  25201. primarySessionId: primary.sessionId,
  25202. assetPlayerId: assetId,
  25203. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  25204. interstitialsController: undefined,
  25205. startPosition,
  25206. liveDurationInfinity: false,
  25207. testBandwidth: false,
  25208. videoPreference,
  25209. audioPreference: selectedAudio || userConfig.audioPreference,
  25210. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  25211. });
  25212. if (interstitial.appendInPlace) {
  25213. interstitial.appendInPlaceStarted = true;
  25214. if (assetItem.timelineStart) {
  25215. playerConfig.timelineOffset = assetItem.timelineStart;
  25216. }
  25217. }
  25218. const cmcd = playerConfig.cmcd;
  25219. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  25220. playerConfig.cmcd = _extends({}, cmcd, {
  25221. contentId: hash(assetItem.uri)
  25222. });
  25223. }
  25224. if (this.getAssetPlayer(assetId)) {
  25225. this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);
  25226. }
  25227. const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  25228. this.playerQueue.push(player);
  25229. interstitial.assetList[assetListIndex] = assetItem;
  25230. // Listen for LevelDetails and PTS change to update duration
  25231. const updateAssetPlayerDetails = details => {
  25232. if (details.live) {
  25233. const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);
  25234. const errorData = {
  25235. fatal: true,
  25236. type: ErrorTypes.OTHER_ERROR,
  25237. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25238. error
  25239. };
  25240. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  25241. return;
  25242. }
  25243. // Get time at end of last fragment
  25244. const duration = details.edge - details.fragmentStart;
  25245. const currentAssetDuration = assetItem.duration;
  25246. if (currentAssetDuration === null || duration > currentAssetDuration) {
  25247. this.log(`Interstitial asset "${assetId}" duration change ${currentAssetDuration} > ${duration}`);
  25248. assetItem.duration = duration;
  25249. // Update schedule with new event and asset duration
  25250. this.updateSchedule();
  25251. }
  25252. };
  25253. player.on(Events.LEVEL_UPDATED, (event, {
  25254. details
  25255. }) => updateAssetPlayerDetails(details));
  25256. player.on(Events.LEVEL_PTS_UPDATED, (event, {
  25257. details
  25258. }) => updateAssetPlayerDetails(details));
  25259. const onBufferCodecs = (event, data) => {
  25260. const inQueuPlayer = this.getAssetPlayer(assetId);
  25261. if (inQueuPlayer && data.tracks) {
  25262. inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);
  25263. inQueuPlayer.tracks = data.tracks;
  25264. const media = this.primaryMedia;
  25265. if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  25266. this.bufferAssetPlayer(inQueuPlayer, media);
  25267. }
  25268. }
  25269. };
  25270. player.on(Events.BUFFER_CODECS, onBufferCodecs);
  25271. const bufferedToEnd = () => {
  25272. var _this$schedule$items2;
  25273. const inQueuPlayer = this.getAssetPlayer(assetId);
  25274. this.log(`buffered to end of asset ${inQueuPlayer}`);
  25275. if (!inQueuPlayer) {
  25276. return;
  25277. }
  25278. // Preload at end of asset
  25279. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  25280. const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  25281. if (this.isInterstitial(item)) {
  25282. const assetListIndex = interstitial.findAssetIndex(assetItem);
  25283. const nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  25284. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  25285. this.bufferedToItem(item, nextAssetIndex);
  25286. } else {
  25287. var _this$schedule$items3;
  25288. const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];
  25289. if (nextItem) {
  25290. this.bufferedToItem(nextItem);
  25291. }
  25292. }
  25293. }
  25294. };
  25295. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  25296. const endedWithAssetIndex = assetIndex => {
  25297. return () => {
  25298. const inQueuPlayer = this.getAssetPlayer(assetId);
  25299. if (!inQueuPlayer) {
  25300. return;
  25301. }
  25302. this.shouldPlay = true;
  25303. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  25304. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  25305. };
  25306. };
  25307. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  25308. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  25309. player.on(Events.ERROR, (event, data) => {
  25310. const inQueuPlayer = this.getAssetPlayer(assetId);
  25311. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  25312. if (inQueuPlayer != null && inQueuPlayer.media) {
  25313. const assetCurrentTime = inQueuPlayer.currentTime;
  25314. const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  25315. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  25316. this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);
  25317. bufferedToEnd();
  25318. } else {
  25319. this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);
  25320. this.onTimeupdate();
  25321. this.checkBuffer(true);
  25322. }
  25323. }
  25324. return;
  25325. }
  25326. this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);
  25327. });
  25328. player.on(Events.DESTROYING, () => {
  25329. const inQueuPlayer = this.getAssetPlayer(assetId);
  25330. if (!inQueuPlayer) {
  25331. return;
  25332. }
  25333. const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);
  25334. const errorData = {
  25335. fatal: true,
  25336. type: ErrorTypes.OTHER_ERROR,
  25337. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25338. error
  25339. };
  25340. this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  25341. });
  25342. this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(assetItem)}`);
  25343. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  25344. asset: assetItem,
  25345. assetListIndex,
  25346. event: interstitial,
  25347. player
  25348. });
  25349. return player;
  25350. }
  25351. clearInterstitial(interstitial, toSegment) {
  25352. interstitial.assetList.forEach(asset => {
  25353. this.clearAssetPlayer(asset.identifier, toSegment);
  25354. });
  25355. // Remove asset list and resolved duration
  25356. interstitial.reset();
  25357. }
  25358. resetAssetPlayer(assetId) {
  25359. // Reset asset player so that it's timeline can be adjusted without reloading the MVP
  25360. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25361. if (playerIndex !== -1) {
  25362. this.log(`reset asset player "${assetId}" after error`);
  25363. const player = this.playerQueue[playerIndex];
  25364. this.transferMediaFromPlayer(player, null);
  25365. player.resetDetails();
  25366. }
  25367. }
  25368. clearAssetPlayer(assetId, toSegment) {
  25369. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25370. if (playerIndex !== -1) {
  25371. this.log(`clear asset player "${assetId}" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);
  25372. const player = this.playerQueue[playerIndex];
  25373. this.transferMediaFromPlayer(player, toSegment);
  25374. this.playerQueue.splice(playerIndex, 1);
  25375. player.destroy();
  25376. }
  25377. }
  25378. emptyPlayerQueue() {
  25379. let player;
  25380. while (player = this.playerQueue.pop()) {
  25381. player.destroy();
  25382. }
  25383. this.playerQueue = [];
  25384. }
  25385. startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  25386. const {
  25387. interstitial,
  25388. assetItem,
  25389. assetId
  25390. } = player;
  25391. const assetListLength = interstitial.assetList.length;
  25392. const playingAsset = this.playingAsset;
  25393. this.endedAsset = null;
  25394. this.playingAsset = assetItem;
  25395. if (!playingAsset || playingAsset.identifier !== assetId) {
  25396. if (playingAsset) {
  25397. // Exiting another Interstitial asset
  25398. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  25399. delete playingAsset.error;
  25400. }
  25401. this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${eventAssetToString(assetItem)}`);
  25402. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  25403. asset: assetItem,
  25404. assetListIndex,
  25405. event: interstitial,
  25406. schedule: scheduleItems.slice(0),
  25407. scheduleIndex,
  25408. player
  25409. });
  25410. }
  25411. // detach media and attach to interstitial player if it does not have another element attached
  25412. this.bufferAssetPlayer(player, media);
  25413. }
  25414. bufferAssetPlayer(player, media) {
  25415. var _this$schedule$items4, _this$detachedData5;
  25416. const {
  25417. interstitial,
  25418. assetItem
  25419. } = player;
  25420. const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  25421. const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];
  25422. if (!item) {
  25423. return;
  25424. }
  25425. this.setBufferingItem(item);
  25426. this.bufferingAsset = assetItem;
  25427. const bufferingPlayer = this.getBufferingPlayer();
  25428. if (bufferingPlayer === player) {
  25429. return;
  25430. }
  25431. const appendInPlaceNext = interstitial.appendInPlace;
  25432. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  25433. // Media is detached and not available to append in place
  25434. return;
  25435. }
  25436. const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;
  25437. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  25438. // Do not buffer another item if tracks are unknown or incompatible
  25439. if (!player.tracks) {
  25440. return;
  25441. }
  25442. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  25443. const error = new Error(`Asset ${eventAssetToString(assetItem)} SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);
  25444. const errorData = {
  25445. fatal: true,
  25446. type: ErrorTypes.OTHER_ERROR,
  25447. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25448. error
  25449. };
  25450. const assetListIndex = interstitial.findAssetIndex(assetItem);
  25451. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  25452. return;
  25453. }
  25454. }
  25455. this.transferMediaTo(player, media);
  25456. }
  25457. handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  25458. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  25459. return;
  25460. }
  25461. const assetItem = interstitial.assetList[assetListIndex];
  25462. this.warn(`INTERSTITIAL_ASSET_ERROR ${assetItem ? eventAssetToString(assetItem) : assetItem} ${data.error}`);
  25463. const assetId = assetItem == null ? void 0 : assetItem.identifier;
  25464. const playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25465. const player = this.playerQueue[playerIndex] || null;
  25466. const items = this.schedule.items;
  25467. const interstitialAssetError = _extends({}, data, {
  25468. fatal: false,
  25469. errorAction: createDoNothingErrorAction(true),
  25470. asset: assetItem,
  25471. assetListIndex,
  25472. event: interstitial,
  25473. schedule: items,
  25474. scheduleIndex,
  25475. player
  25476. });
  25477. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  25478. if (!data.fatal) {
  25479. return;
  25480. }
  25481. const playingAsset = this.playingAsset;
  25482. const error = new Error(errorMessage);
  25483. if (assetItem) {
  25484. this.clearAssetPlayer(assetId, null);
  25485. assetItem.error = error;
  25486. }
  25487. // If all assets in interstitial fail, mark the interstitial with an error
  25488. if (!interstitial.assetList.some(asset => !asset.error)) {
  25489. interstitial.error = error;
  25490. } else {
  25491. // Reset level details and reload/parse media playlists to align with updated schedule
  25492. for (let i = assetListIndex; i < interstitial.assetList.length; i++) {
  25493. this.resetAssetPlayer(interstitial.assetList[i].identifier);
  25494. }
  25495. this.updateSchedule();
  25496. }
  25497. if (interstitial.error) {
  25498. this.primaryFallback(interstitial);
  25499. } else if (playingAsset && playingAsset.identifier === assetId) {
  25500. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  25501. }
  25502. }
  25503. primaryFallback(interstitial) {
  25504. // Fallback to Primary by on current or future events by updating schedule to skip errored interstitials/assets
  25505. const flushStart = interstitial.timelineStart;
  25506. const playingItem = this.effectivePlayingItem;
  25507. // Update schedule now that interstitial/assets are flagged with `error` for fallback
  25508. this.updateSchedule();
  25509. if (playingItem) {
  25510. this.log(`Fallback to primary from event "${interstitial.identifier}" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : '<none>'} error: ${interstitial.error}`);
  25511. let timelinePos = this.timelinePos;
  25512. if (timelinePos === -1) {
  25513. timelinePos = this.hls.startPosition;
  25514. }
  25515. const newPlayingItem = this.updateItem(playingItem, timelinePos);
  25516. if (this.itemsMatch(playingItem, newPlayingItem)) {
  25517. this.clearInterstitial(interstitial, null);
  25518. }
  25519. if (interstitial.appendInPlace) {
  25520. this.attachPrimary(flushStart, null);
  25521. this.flushFrontBuffer(flushStart);
  25522. }
  25523. const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  25524. this.setSchedulePosition(scheduleIndex);
  25525. } else {
  25526. this.checkStart();
  25527. }
  25528. }
  25529. // Asset List loading
  25530. onAssetListLoaded(event, data) {
  25531. var _this$bufferingItem2;
  25532. const interstitial = data.event;
  25533. const interstitialId = interstitial.identifier;
  25534. const assets = data.assetListResponse.ASSETS;
  25535. if (!this.schedule.hasEvent(interstitialId)) {
  25536. // Interstitial with id was removed
  25537. return;
  25538. }
  25539. const eventStart = interstitial.timelineStart;
  25540. const previousDuration = interstitial.duration;
  25541. let sumDuration = 0;
  25542. assets.forEach((asset, assetListIndex) => {
  25543. const duration = parseFloat(asset.DURATION);
  25544. this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  25545. sumDuration += duration;
  25546. });
  25547. interstitial.duration = sumDuration;
  25548. this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);
  25549. const waitingItem = this.waitingItem;
  25550. const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  25551. // Update schedule now that asset.DURATION(s) are parsed
  25552. this.updateSchedule();
  25553. const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;
  25554. // If buffer reached Interstitial, start buffering first asset
  25555. if (waitingForItem) {
  25556. var _this$schedule$items5;
  25557. // Advance schedule when waiting for asset list data to play
  25558. const scheduleIndex = this.schedule.findEventIndex(interstitialId);
  25559. const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];
  25560. if (item) {
  25561. if (!this.playingItem && this.timelinePos > item.end) {
  25562. // Abandon if new duration is reduced enough to land playback in primary start
  25563. const index = this.schedule.findItemIndexAtTime(this.timelinePos);
  25564. if (index !== scheduleIndex) {
  25565. interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);
  25566. this.primaryFallback(interstitial);
  25567. return;
  25568. }
  25569. }
  25570. this.setBufferingItem(item);
  25571. }
  25572. this.setSchedulePosition(scheduleIndex);
  25573. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  25574. // If buffering (but not playback) has reached this item transfer media-source
  25575. const assetItem = interstitial.assetList[0];
  25576. const player = this.getAssetPlayer(assetItem.identifier);
  25577. const media = this.primaryMedia;
  25578. if (assetItem && player && media) {
  25579. this.bufferAssetPlayer(player, media);
  25580. }
  25581. }
  25582. }
  25583. onError(event, data) {
  25584. switch (data.details) {
  25585. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  25586. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  25587. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:
  25588. {
  25589. const interstitial = data.interstitial;
  25590. if (interstitial) {
  25591. this.primaryFallback(interstitial);
  25592. }
  25593. break;
  25594. }
  25595. case ErrorDetails.BUFFER_STALLED_ERROR:
  25596. {
  25597. this.onTimeupdate();
  25598. this.checkBuffer(true);
  25599. break;
  25600. }
  25601. }
  25602. }
  25603. }
  25604. const TICK_INTERVAL$2 = 500; // how often to tick in ms
  25605. class SubtitleStreamController extends BaseStreamController {
  25606. constructor(hls, fragmentTracker, keyLoader) {
  25607. super(hls, fragmentTracker, keyLoader, 'subtitle-stream-controller', PlaylistLevelType.SUBTITLE);
  25608. this.currentTrackId = -1;
  25609. this.tracksBuffered = [];
  25610. this.mainDetails = null;
  25611. this.registerListeners();
  25612. }
  25613. onHandlerDestroying() {
  25614. this.unregisterListeners();
  25615. super.onHandlerDestroying();
  25616. this.mainDetails = null;
  25617. }
  25618. registerListeners() {
  25619. super.registerListeners();
  25620. const {
  25621. hls
  25622. } = this;
  25623. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25624. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25625. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  25626. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25627. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  25628. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25629. }
  25630. unregisterListeners() {
  25631. super.unregisterListeners();
  25632. const {
  25633. hls
  25634. } = this;
  25635. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25636. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25637. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  25638. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25639. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  25640. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25641. }
  25642. startLoad(startPosition, skipSeekToStartPosition) {
  25643. this.stopLoad();
  25644. this.state = State.IDLE;
  25645. this.setInterval(TICK_INTERVAL$2);
  25646. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  25647. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  25648. this.tick();
  25649. }
  25650. onManifestLoading() {
  25651. super.onManifestLoading();
  25652. this.mainDetails = null;
  25653. }
  25654. onMediaDetaching(event, data) {
  25655. this.tracksBuffered = [];
  25656. super.onMediaDetaching(event, data);
  25657. }
  25658. onLevelLoaded(event, data) {
  25659. this.mainDetails = data.details;
  25660. }
  25661. onSubtitleFragProcessed(event, data) {
  25662. const {
  25663. frag,
  25664. success
  25665. } = data;
  25666. if (!this.fragContextChanged(frag)) {
  25667. if (isMediaFragment(frag)) {
  25668. this.fragPrevious = frag;
  25669. }
  25670. this.state = State.IDLE;
  25671. }
  25672. if (!success) {
  25673. return;
  25674. }
  25675. const buffered = this.tracksBuffered[this.currentTrackId];
  25676. if (!buffered) {
  25677. return;
  25678. }
  25679. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  25680. // so we can re-use the logic used to detect how much has been buffered
  25681. let timeRange;
  25682. const fragStart = frag.start;
  25683. for (let i = 0; i < buffered.length; i++) {
  25684. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  25685. timeRange = buffered[i];
  25686. break;
  25687. }
  25688. }
  25689. const fragEnd = frag.start + frag.duration;
  25690. if (timeRange) {
  25691. timeRange.end = fragEnd;
  25692. } else {
  25693. timeRange = {
  25694. start: fragStart,
  25695. end: fragEnd
  25696. };
  25697. buffered.push(timeRange);
  25698. }
  25699. this.fragmentTracker.fragBuffered(frag);
  25700. this.fragBufferedComplete(frag, null);
  25701. if (this.media) {
  25702. this.tick();
  25703. }
  25704. }
  25705. onBufferFlushing(event, data) {
  25706. const {
  25707. startOffset,
  25708. endOffset
  25709. } = data;
  25710. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  25711. const endOffsetSubtitles = endOffset - 1;
  25712. if (endOffsetSubtitles <= 0) {
  25713. return;
  25714. }
  25715. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  25716. this.tracksBuffered.forEach(buffered => {
  25717. for (let i = 0; i < buffered.length;) {
  25718. if (buffered[i].end <= endOffsetSubtitles) {
  25719. buffered.shift();
  25720. continue;
  25721. } else if (buffered[i].start < endOffsetSubtitles) {
  25722. buffered[i].start = endOffsetSubtitles;
  25723. } else {
  25724. break;
  25725. }
  25726. i++;
  25727. }
  25728. });
  25729. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  25730. }
  25731. }
  25732. // If something goes wrong, proceed to next frag, if we were processing one.
  25733. onError(event, data) {
  25734. const frag = data.frag;
  25735. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  25736. if (data.details === ErrorDetails.FRAG_GAP) {
  25737. this.fragmentTracker.fragBuffered(frag, true);
  25738. }
  25739. if (this.fragCurrent) {
  25740. this.fragCurrent.abortRequests();
  25741. }
  25742. if (this.state !== State.STOPPED) {
  25743. this.state = State.IDLE;
  25744. }
  25745. }
  25746. }
  25747. // Got all new subtitle levels.
  25748. onSubtitleTracksUpdated(event, {
  25749. subtitleTracks
  25750. }) {
  25751. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  25752. this.levels = subtitleTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  25753. return;
  25754. }
  25755. this.tracksBuffered = [];
  25756. this.levels = subtitleTracks.map(mediaPlaylist => {
  25757. const level = new Level(mediaPlaylist);
  25758. this.tracksBuffered[level.id] = [];
  25759. return level;
  25760. });
  25761. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  25762. this.fragPrevious = null;
  25763. this.mediaBuffer = null;
  25764. }
  25765. onSubtitleTrackSwitch(event, data) {
  25766. var _this$levels;
  25767. this.currentTrackId = data.id;
  25768. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  25769. this.clearInterval();
  25770. return;
  25771. }
  25772. // Check if track has the necessary details to load fragments
  25773. const currentTrack = this.levels[this.currentTrackId];
  25774. if (currentTrack != null && currentTrack.details) {
  25775. this.mediaBuffer = this.mediaBufferTimeRanges;
  25776. } else {
  25777. this.mediaBuffer = null;
  25778. }
  25779. if (currentTrack && this.state !== State.STOPPED) {
  25780. this.setInterval(TICK_INTERVAL$2);
  25781. }
  25782. }
  25783. // Got a new set of subtitle fragments.
  25784. onSubtitleTrackLoaded(event, data) {
  25785. var _track$details;
  25786. const {
  25787. currentTrackId,
  25788. levels
  25789. } = this;
  25790. const {
  25791. details: newDetails,
  25792. id: trackId
  25793. } = data;
  25794. if (!levels) {
  25795. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  25796. return;
  25797. }
  25798. const track = levels[trackId];
  25799. if (trackId >= levels.length || !track) {
  25800. return;
  25801. }
  25802. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  25803. this.mediaBuffer = this.mediaBufferTimeRanges;
  25804. let sliding = 0;
  25805. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  25806. if (newDetails.deltaUpdateFailed) {
  25807. return;
  25808. }
  25809. const mainDetails = this.mainDetails;
  25810. if (!mainDetails) {
  25811. this.startFragRequested = false;
  25812. return;
  25813. }
  25814. const mainSlidingStartFragment = mainDetails.fragments[0];
  25815. if (!track.details) {
  25816. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  25817. alignMediaPlaylistByPDT(newDetails, mainDetails);
  25818. sliding = newDetails.fragmentStart;
  25819. } else if (mainSlidingStartFragment) {
  25820. // line up live playlist with main so that fragments in range are loaded
  25821. sliding = mainSlidingStartFragment.start;
  25822. addSliding(newDetails, sliding);
  25823. }
  25824. } else {
  25825. var _this$levelLastLoaded;
  25826. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  25827. if (sliding === 0 && mainSlidingStartFragment) {
  25828. // realign with main when there is no overlap with last refresh
  25829. sliding = mainSlidingStartFragment.start;
  25830. addSliding(newDetails, sliding);
  25831. }
  25832. }
  25833. // compute start position if we are aligned with the main playlist
  25834. if (mainDetails && !this.startFragRequested) {
  25835. this.setStartPosition(mainDetails, sliding);
  25836. }
  25837. }
  25838. track.details = newDetails;
  25839. this.levelLastLoaded = track;
  25840. if (trackId !== currentTrackId) {
  25841. return;
  25842. }
  25843. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  25844. details: newDetails,
  25845. id: trackId,
  25846. groupId: data.groupId
  25847. });
  25848. // trigger handler right now
  25849. this.tick();
  25850. // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
  25851. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  25852. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  25853. if (!foundFrag) {
  25854. this.warn('Subtitle playlist not aligned with playback');
  25855. track.details = undefined;
  25856. }
  25857. }
  25858. }
  25859. _handleFragmentLoadComplete(fragLoadedData) {
  25860. const {
  25861. frag,
  25862. payload
  25863. } = fragLoadedData;
  25864. const decryptData = frag.decryptdata;
  25865. const hls = this.hls;
  25866. if (this.fragContextChanged(frag)) {
  25867. return;
  25868. }
  25869. // check to see if the payload needs to be decrypted
  25870. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  25871. const startTime = performance.now();
  25872. // decrypt the subtitles
  25873. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(err => {
  25874. hls.trigger(Events.ERROR, {
  25875. type: ErrorTypes.MEDIA_ERROR,
  25876. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  25877. fatal: false,
  25878. error: err,
  25879. reason: err.message,
  25880. frag
  25881. });
  25882. throw err;
  25883. }).then(decryptedData => {
  25884. const endTime = performance.now();
  25885. hls.trigger(Events.FRAG_DECRYPTED, {
  25886. frag,
  25887. payload: decryptedData,
  25888. stats: {
  25889. tstart: startTime,
  25890. tdecrypt: endTime
  25891. }
  25892. });
  25893. }).catch(err => {
  25894. this.warn(`${err.name}: ${err.message}`);
  25895. this.state = State.IDLE;
  25896. });
  25897. }
  25898. }
  25899. doTick() {
  25900. if (!this.media) {
  25901. this.state = State.IDLE;
  25902. return;
  25903. }
  25904. if (this.state === State.IDLE) {
  25905. const {
  25906. currentTrackId,
  25907. levels
  25908. } = this;
  25909. const track = levels == null ? void 0 : levels[currentTrackId];
  25910. if (!track || !levels.length || !track.details) {
  25911. return;
  25912. }
  25913. if (this.waitForLive(track)) {
  25914. return;
  25915. }
  25916. const {
  25917. config
  25918. } = this;
  25919. const currentTime = this.getLoadPosition();
  25920. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  25921. const {
  25922. end: targetBufferTime,
  25923. len: bufferLen
  25924. } = bufferedInfo;
  25925. const trackDetails = track.details;
  25926. const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  25927. if (bufferLen > maxBufLen) {
  25928. return;
  25929. }
  25930. const fragments = trackDetails.fragments;
  25931. const fragLen = fragments.length;
  25932. const end = trackDetails.edge;
  25933. let foundFrag = null;
  25934. const fragPrevious = this.fragPrevious;
  25935. if (targetBufferTime < end) {
  25936. const tolerance = config.maxFragLookUpTolerance;
  25937. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  25938. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  25939. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  25940. foundFrag = fragments[0];
  25941. }
  25942. } else {
  25943. foundFrag = fragments[fragLen - 1];
  25944. }
  25945. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  25946. if (!foundFrag) {
  25947. return;
  25948. }
  25949. // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment
  25950. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  25951. const prevFrag = fragments[curSNIdx - 1];
  25952. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  25953. foundFrag = prevFrag;
  25954. }
  25955. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  25956. // only load if fragment is not loaded
  25957. const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  25958. if (fragToLoad) {
  25959. this.loadFragment(fragToLoad, track, targetBufferTime);
  25960. }
  25961. }
  25962. }
  25963. }
  25964. loadFragment(frag, level, targetBufferTime) {
  25965. if (!isMediaFragment(frag)) {
  25966. this._loadInitSegment(frag, level);
  25967. } else {
  25968. super.loadFragment(frag, level, targetBufferTime);
  25969. }
  25970. }
  25971. get mediaBufferTimeRanges() {
  25972. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  25973. }
  25974. }
  25975. class BufferableInstance {
  25976. constructor(timeranges) {
  25977. this.buffered = void 0;
  25978. const getRange = (name, index, length) => {
  25979. index = index >>> 0;
  25980. if (index > length - 1) {
  25981. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  25982. }
  25983. return timeranges[index][name];
  25984. };
  25985. this.buffered = {
  25986. get length() {
  25987. return timeranges.length;
  25988. },
  25989. end(index) {
  25990. return getRange('end', index, timeranges.length);
  25991. },
  25992. start(index) {
  25993. return getRange('start', index, timeranges.length);
  25994. }
  25995. };
  25996. }
  25997. }
  25998. /**
  25999. *
  26000. * This code was ported from the dash.js project at:
  26001. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  26002. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  26003. *
  26004. * The original copyright appears below:
  26005. *
  26006. * The copyright in this software is being made available under the BSD License,
  26007. * included below. This software may be subject to other third party and contributor
  26008. * rights, including patent rights, and no such rights are granted under this license.
  26009. *
  26010. * Copyright (c) 2015-2016, DASH Industry Forum.
  26011. * All rights reserved.
  26012. *
  26013. * Redistribution and use in source and binary forms, with or without modification,
  26014. * are permitted provided that the following conditions are met:
  26015. * 1. Redistributions of source code must retain the above copyright notice, this
  26016. * list of conditions and the following disclaimer.
  26017. * * Redistributions in binary form must reproduce the above copyright notice,
  26018. * this list of conditions and the following disclaimer in the documentation and/or
  26019. * other materials provided with the distribution.
  26020. * 2. Neither the name of Dash Industry Forum nor the names of its
  26021. * contributors may be used to endorse or promote products derived from this software
  26022. * without specific prior written permission.
  26023. *
  26024. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  26025. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  26026. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  26027. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  26028. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  26029. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26030. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  26031. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26032. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26033. * POSSIBILITY OF SUCH DAMAGE.
  26034. */
  26035. /**
  26036. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  26037. */
  26038. const specialCea608CharsCodes = {
  26039. 0x2a: 0xe1,
  26040. // lowercase a, acute accent
  26041. 0x5c: 0xe9,
  26042. // lowercase e, acute accent
  26043. 0x5e: 0xed,
  26044. // lowercase i, acute accent
  26045. 0x5f: 0xf3,
  26046. // lowercase o, acute accent
  26047. 0x60: 0xfa,
  26048. // lowercase u, acute accent
  26049. 0x7b: 0xe7,
  26050. // lowercase c with cedilla
  26051. 0x7c: 0xf7,
  26052. // division symbol
  26053. 0x7d: 0xd1,
  26054. // uppercase N tilde
  26055. 0x7e: 0xf1,
  26056. // lowercase n tilde
  26057. 0x7f: 0x2588,
  26058. // Full block
  26059. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  26060. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  26061. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  26062. 0x80: 0xae,
  26063. // Registered symbol (R)
  26064. 0x81: 0xb0,
  26065. // degree sign
  26066. 0x82: 0xbd,
  26067. // 1/2 symbol
  26068. 0x83: 0xbf,
  26069. // Inverted (open) question mark
  26070. 0x84: 0x2122,
  26071. // Trademark symbol (TM)
  26072. 0x85: 0xa2,
  26073. // Cents symbol
  26074. 0x86: 0xa3,
  26075. // Pounds sterling
  26076. 0x87: 0x266a,
  26077. // Music 8'th note
  26078. 0x88: 0xe0,
  26079. // lowercase a, grave accent
  26080. 0x89: 0x20,
  26081. // transparent space (regular)
  26082. 0x8a: 0xe8,
  26083. // lowercase e, grave accent
  26084. 0x8b: 0xe2,
  26085. // lowercase a, circumflex accent
  26086. 0x8c: 0xea,
  26087. // lowercase e, circumflex accent
  26088. 0x8d: 0xee,
  26089. // lowercase i, circumflex accent
  26090. 0x8e: 0xf4,
  26091. // lowercase o, circumflex accent
  26092. 0x8f: 0xfb,
  26093. // lowercase u, circumflex accent
  26094. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  26095. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  26096. 0x90: 0xc1,
  26097. // capital letter A with acute
  26098. 0x91: 0xc9,
  26099. // capital letter E with acute
  26100. 0x92: 0xd3,
  26101. // capital letter O with acute
  26102. 0x93: 0xda,
  26103. // capital letter U with acute
  26104. 0x94: 0xdc,
  26105. // capital letter U with diaresis
  26106. 0x95: 0xfc,
  26107. // lowercase letter U with diaeresis
  26108. 0x96: 0x2018,
  26109. // opening single quote
  26110. 0x97: 0xa1,
  26111. // inverted exclamation mark
  26112. 0x98: 0x2a,
  26113. // asterisk
  26114. 0x99: 0x2019,
  26115. // closing single quote
  26116. 0x9a: 0x2501,
  26117. // box drawings heavy horizontal
  26118. 0x9b: 0xa9,
  26119. // copyright sign
  26120. 0x9c: 0x2120,
  26121. // Service mark
  26122. 0x9d: 0x2022,
  26123. // (round) bullet
  26124. 0x9e: 0x201c,
  26125. // Left double quotation mark
  26126. 0x9f: 0x201d,
  26127. // Right double quotation mark
  26128. 0xa0: 0xc0,
  26129. // uppercase A, grave accent
  26130. 0xa1: 0xc2,
  26131. // uppercase A, circumflex
  26132. 0xa2: 0xc7,
  26133. // uppercase C with cedilla
  26134. 0xa3: 0xc8,
  26135. // uppercase E, grave accent
  26136. 0xa4: 0xca,
  26137. // uppercase E, circumflex
  26138. 0xa5: 0xcb,
  26139. // capital letter E with diaresis
  26140. 0xa6: 0xeb,
  26141. // lowercase letter e with diaresis
  26142. 0xa7: 0xce,
  26143. // uppercase I, circumflex
  26144. 0xa8: 0xcf,
  26145. // uppercase I, with diaresis
  26146. 0xa9: 0xef,
  26147. // lowercase i, with diaresis
  26148. 0xaa: 0xd4,
  26149. // uppercase O, circumflex
  26150. 0xab: 0xd9,
  26151. // uppercase U, grave accent
  26152. 0xac: 0xf9,
  26153. // lowercase u, grave accent
  26154. 0xad: 0xdb,
  26155. // uppercase U, circumflex
  26156. 0xae: 0xab,
  26157. // left-pointing double angle quotation mark
  26158. 0xaf: 0xbb,
  26159. // right-pointing double angle quotation mark
  26160. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  26161. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  26162. 0xb0: 0xc3,
  26163. // Uppercase A, tilde
  26164. 0xb1: 0xe3,
  26165. // Lowercase a, tilde
  26166. 0xb2: 0xcd,
  26167. // Uppercase I, acute accent
  26168. 0xb3: 0xcc,
  26169. // Uppercase I, grave accent
  26170. 0xb4: 0xec,
  26171. // Lowercase i, grave accent
  26172. 0xb5: 0xd2,
  26173. // Uppercase O, grave accent
  26174. 0xb6: 0xf2,
  26175. // Lowercase o, grave accent
  26176. 0xb7: 0xd5,
  26177. // Uppercase O, tilde
  26178. 0xb8: 0xf5,
  26179. // Lowercase o, tilde
  26180. 0xb9: 0x7b,
  26181. // Open curly brace
  26182. 0xba: 0x7d,
  26183. // Closing curly brace
  26184. 0xbb: 0x5c,
  26185. // Backslash
  26186. 0xbc: 0x5e,
  26187. // Caret
  26188. 0xbd: 0x5f,
  26189. // Underscore
  26190. 0xbe: 0x7c,
  26191. // Pipe (vertical line)
  26192. 0xbf: 0x223c,
  26193. // Tilde operator
  26194. 0xc0: 0xc4,
  26195. // Uppercase A, umlaut
  26196. 0xc1: 0xe4,
  26197. // Lowercase A, umlaut
  26198. 0xc2: 0xd6,
  26199. // Uppercase O, umlaut
  26200. 0xc3: 0xf6,
  26201. // Lowercase o, umlaut
  26202. 0xc4: 0xdf,
  26203. // Esszett (sharp S)
  26204. 0xc5: 0xa5,
  26205. // Yen symbol
  26206. 0xc6: 0xa4,
  26207. // Generic currency sign
  26208. 0xc7: 0x2503,
  26209. // Box drawings heavy vertical
  26210. 0xc8: 0xc5,
  26211. // Uppercase A, ring
  26212. 0xc9: 0xe5,
  26213. // Lowercase A, ring
  26214. 0xca: 0xd8,
  26215. // Uppercase O, stroke
  26216. 0xcb: 0xf8,
  26217. // Lowercase o, strok
  26218. 0xcc: 0x250f,
  26219. // Box drawings heavy down and right
  26220. 0xcd: 0x2513,
  26221. // Box drawings heavy down and left
  26222. 0xce: 0x2517,
  26223. // Box drawings heavy up and right
  26224. 0xcf: 0x251b // Box drawings heavy up and left
  26225. };
  26226. /**
  26227. * Utils
  26228. */
  26229. const getCharForByte = byte => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  26230. const NR_ROWS = 15;
  26231. const NR_COLS = 100;
  26232. // Tables to look up row from PAC data
  26233. const rowsLowCh1 = {
  26234. 0x11: 1,
  26235. 0x12: 3,
  26236. 0x15: 5,
  26237. 0x16: 7,
  26238. 0x17: 9,
  26239. 0x10: 11,
  26240. 0x13: 12,
  26241. 0x14: 14
  26242. };
  26243. const rowsHighCh1 = {
  26244. 0x11: 2,
  26245. 0x12: 4,
  26246. 0x15: 6,
  26247. 0x16: 8,
  26248. 0x17: 10,
  26249. 0x13: 13,
  26250. 0x14: 15
  26251. };
  26252. const rowsLowCh2 = {
  26253. 0x19: 1,
  26254. 0x1a: 3,
  26255. 0x1d: 5,
  26256. 0x1e: 7,
  26257. 0x1f: 9,
  26258. 0x18: 11,
  26259. 0x1b: 12,
  26260. 0x1c: 14
  26261. };
  26262. const rowsHighCh2 = {
  26263. 0x19: 2,
  26264. 0x1a: 4,
  26265. 0x1d: 6,
  26266. 0x1e: 8,
  26267. 0x1f: 10,
  26268. 0x1b: 13,
  26269. 0x1c: 15
  26270. };
  26271. const backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  26272. class CaptionsLogger {
  26273. constructor() {
  26274. this.time = null;
  26275. this.verboseLevel = 0;
  26276. }
  26277. log(severity, msg) {
  26278. if (this.verboseLevel >= severity) {
  26279. const m = typeof msg === 'function' ? msg() : msg;
  26280. logger.log(`${this.time} [${severity}] ${m}`);
  26281. }
  26282. }
  26283. }
  26284. const numArrayToHexArray = function numArrayToHexArray(numArray) {
  26285. const hexArray = [];
  26286. for (let j = 0; j < numArray.length; j++) {
  26287. hexArray.push(numArray[j].toString(16));
  26288. }
  26289. return hexArray;
  26290. };
  26291. class PenState {
  26292. constructor() {
  26293. this.foreground = 'white';
  26294. this.underline = false;
  26295. this.italics = false;
  26296. this.background = 'black';
  26297. this.flash = false;
  26298. }
  26299. reset() {
  26300. this.foreground = 'white';
  26301. this.underline = false;
  26302. this.italics = false;
  26303. this.background = 'black';
  26304. this.flash = false;
  26305. }
  26306. setStyles(styles) {
  26307. const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  26308. for (let i = 0; i < attribs.length; i++) {
  26309. const style = attribs[i];
  26310. if (styles.hasOwnProperty(style)) {
  26311. this[style] = styles[style];
  26312. }
  26313. }
  26314. }
  26315. isDefault() {
  26316. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  26317. }
  26318. equals(other) {
  26319. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  26320. }
  26321. copy(newPenState) {
  26322. this.foreground = newPenState.foreground;
  26323. this.underline = newPenState.underline;
  26324. this.italics = newPenState.italics;
  26325. this.background = newPenState.background;
  26326. this.flash = newPenState.flash;
  26327. }
  26328. toString() {
  26329. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  26330. }
  26331. }
  26332. /**
  26333. * Unicode character with styling and background.
  26334. * @constructor
  26335. */
  26336. class StyledUnicodeChar {
  26337. constructor() {
  26338. this.uchar = ' ';
  26339. this.penState = new PenState();
  26340. }
  26341. reset() {
  26342. this.uchar = ' ';
  26343. this.penState.reset();
  26344. }
  26345. setChar(uchar, newPenState) {
  26346. this.uchar = uchar;
  26347. this.penState.copy(newPenState);
  26348. }
  26349. setPenState(newPenState) {
  26350. this.penState.copy(newPenState);
  26351. }
  26352. equals(other) {
  26353. return this.uchar === other.uchar && this.penState.equals(other.penState);
  26354. }
  26355. copy(newChar) {
  26356. this.uchar = newChar.uchar;
  26357. this.penState.copy(newChar.penState);
  26358. }
  26359. isEmpty() {
  26360. return this.uchar === ' ' && this.penState.isDefault();
  26361. }
  26362. }
  26363. /**
  26364. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  26365. * @constructor
  26366. */
  26367. class Row {
  26368. constructor(logger) {
  26369. this.chars = [];
  26370. this.pos = 0;
  26371. this.currPenState = new PenState();
  26372. this.cueStartTime = null;
  26373. this.logger = void 0;
  26374. for (let i = 0; i < NR_COLS; i++) {
  26375. this.chars.push(new StyledUnicodeChar());
  26376. }
  26377. this.logger = logger;
  26378. }
  26379. equals(other) {
  26380. for (let i = 0; i < NR_COLS; i++) {
  26381. if (!this.chars[i].equals(other.chars[i])) {
  26382. return false;
  26383. }
  26384. }
  26385. return true;
  26386. }
  26387. copy(other) {
  26388. for (let i = 0; i < NR_COLS; i++) {
  26389. this.chars[i].copy(other.chars[i]);
  26390. }
  26391. }
  26392. isEmpty() {
  26393. let empty = true;
  26394. for (let i = 0; i < NR_COLS; i++) {
  26395. if (!this.chars[i].isEmpty()) {
  26396. empty = false;
  26397. break;
  26398. }
  26399. }
  26400. return empty;
  26401. }
  26402. /**
  26403. * Set the cursor to a valid column.
  26404. */
  26405. setCursor(absPos) {
  26406. if (this.pos !== absPos) {
  26407. this.pos = absPos;
  26408. }
  26409. if (this.pos < 0) {
  26410. this.logger.log(3, 'Negative cursor position ' + this.pos);
  26411. this.pos = 0;
  26412. } else if (this.pos > NR_COLS) {
  26413. this.logger.log(3, 'Too large cursor position ' + this.pos);
  26414. this.pos = NR_COLS;
  26415. }
  26416. }
  26417. /**
  26418. * Move the cursor relative to current position.
  26419. */
  26420. moveCursor(relPos) {
  26421. const newPos = this.pos + relPos;
  26422. if (relPos > 1) {
  26423. for (let i = this.pos + 1; i < newPos + 1; i++) {
  26424. this.chars[i].setPenState(this.currPenState);
  26425. }
  26426. }
  26427. this.setCursor(newPos);
  26428. }
  26429. /**
  26430. * Backspace, move one step back and clear character.
  26431. */
  26432. backSpace() {
  26433. this.moveCursor(-1);
  26434. this.chars[this.pos].setChar(' ', this.currPenState);
  26435. }
  26436. insertChar(byte) {
  26437. if (byte >= 0x90) {
  26438. // Extended char
  26439. this.backSpace();
  26440. }
  26441. const char = getCharForByte(byte);
  26442. if (this.pos >= NR_COLS) {
  26443. this.logger.log(0, () => 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  26444. return;
  26445. }
  26446. this.chars[this.pos].setChar(char, this.currPenState);
  26447. this.moveCursor(1);
  26448. }
  26449. clearFromPos(startPos) {
  26450. let i;
  26451. for (i = startPos; i < NR_COLS; i++) {
  26452. this.chars[i].reset();
  26453. }
  26454. }
  26455. clear() {
  26456. this.clearFromPos(0);
  26457. this.pos = 0;
  26458. this.currPenState.reset();
  26459. }
  26460. clearToEndOfRow() {
  26461. this.clearFromPos(this.pos);
  26462. }
  26463. getTextString() {
  26464. const chars = [];
  26465. let empty = true;
  26466. for (let i = 0; i < NR_COLS; i++) {
  26467. const char = this.chars[i].uchar;
  26468. if (char !== ' ') {
  26469. empty = false;
  26470. }
  26471. chars.push(char);
  26472. }
  26473. if (empty) {
  26474. return '';
  26475. } else {
  26476. return chars.join('');
  26477. }
  26478. }
  26479. setPenStyles(styles) {
  26480. this.currPenState.setStyles(styles);
  26481. const currChar = this.chars[this.pos];
  26482. currChar.setPenState(this.currPenState);
  26483. }
  26484. }
  26485. /**
  26486. * Keep a CEA-608 screen of 32x15 styled characters
  26487. * @constructor
  26488. */
  26489. class CaptionScreen {
  26490. constructor(logger) {
  26491. this.rows = [];
  26492. this.currRow = NR_ROWS - 1;
  26493. this.nrRollUpRows = null;
  26494. this.lastOutputScreen = null;
  26495. this.logger = void 0;
  26496. for (let i = 0; i < NR_ROWS; i++) {
  26497. this.rows.push(new Row(logger));
  26498. }
  26499. this.logger = logger;
  26500. }
  26501. reset() {
  26502. for (let i = 0; i < NR_ROWS; i++) {
  26503. this.rows[i].clear();
  26504. }
  26505. this.currRow = NR_ROWS - 1;
  26506. }
  26507. equals(other) {
  26508. let equal = true;
  26509. for (let i = 0; i < NR_ROWS; i++) {
  26510. if (!this.rows[i].equals(other.rows[i])) {
  26511. equal = false;
  26512. break;
  26513. }
  26514. }
  26515. return equal;
  26516. }
  26517. copy(other) {
  26518. for (let i = 0; i < NR_ROWS; i++) {
  26519. this.rows[i].copy(other.rows[i]);
  26520. }
  26521. }
  26522. isEmpty() {
  26523. let empty = true;
  26524. for (let i = 0; i < NR_ROWS; i++) {
  26525. if (!this.rows[i].isEmpty()) {
  26526. empty = false;
  26527. break;
  26528. }
  26529. }
  26530. return empty;
  26531. }
  26532. backSpace() {
  26533. const row = this.rows[this.currRow];
  26534. row.backSpace();
  26535. }
  26536. clearToEndOfRow() {
  26537. const row = this.rows[this.currRow];
  26538. row.clearToEndOfRow();
  26539. }
  26540. /**
  26541. * Insert a character (without styling) in the current row.
  26542. */
  26543. insertChar(char) {
  26544. const row = this.rows[this.currRow];
  26545. row.insertChar(char);
  26546. }
  26547. setPen(styles) {
  26548. const row = this.rows[this.currRow];
  26549. row.setPenStyles(styles);
  26550. }
  26551. moveCursor(relPos) {
  26552. const row = this.rows[this.currRow];
  26553. row.moveCursor(relPos);
  26554. }
  26555. setCursor(absPos) {
  26556. this.logger.log(2, 'setCursor: ' + absPos);
  26557. const row = this.rows[this.currRow];
  26558. row.setCursor(absPos);
  26559. }
  26560. setPAC(pacData) {
  26561. this.logger.log(2, () => 'pacData = ' + stringify(pacData));
  26562. let newRow = pacData.row - 1;
  26563. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  26564. newRow = this.nrRollUpRows - 1;
  26565. }
  26566. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  26567. if (this.nrRollUpRows && this.currRow !== newRow) {
  26568. // clear all rows first
  26569. for (let i = 0; i < NR_ROWS; i++) {
  26570. this.rows[i].clear();
  26571. }
  26572. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  26573. // topRowIndex - the start of rows to copy (inclusive index)
  26574. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  26575. // We only copy if the last position was already shown.
  26576. // We use the cueStartTime value to check this.
  26577. const lastOutputScreen = this.lastOutputScreen;
  26578. if (lastOutputScreen) {
  26579. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  26580. const time = this.logger.time;
  26581. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  26582. for (let i = 0; i < this.nrRollUpRows; i++) {
  26583. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  26584. }
  26585. }
  26586. }
  26587. }
  26588. this.currRow = newRow;
  26589. const row = this.rows[this.currRow];
  26590. if (pacData.indent !== null) {
  26591. const indent = pacData.indent;
  26592. const prevPos = Math.max(indent - 1, 0);
  26593. row.setCursor(pacData.indent);
  26594. pacData.color = row.chars[prevPos].penState.foreground;
  26595. }
  26596. const styles = {
  26597. foreground: pacData.color,
  26598. underline: pacData.underline,
  26599. italics: pacData.italics,
  26600. background: 'black',
  26601. flash: false
  26602. };
  26603. this.setPen(styles);
  26604. }
  26605. /**
  26606. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  26607. */
  26608. setBkgData(bkgData) {
  26609. this.logger.log(2, () => 'bkgData = ' + stringify(bkgData));
  26610. this.backSpace();
  26611. this.setPen(bkgData);
  26612. this.insertChar(0x20); // Space
  26613. }
  26614. setRollUpRows(nrRows) {
  26615. this.nrRollUpRows = nrRows;
  26616. }
  26617. rollUp() {
  26618. if (this.nrRollUpRows === null) {
  26619. this.logger.log(3, 'roll_up but nrRollUpRows not set yet');
  26620. return; // Not properly setup
  26621. }
  26622. this.logger.log(1, () => this.getDisplayText());
  26623. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  26624. const topRow = this.rows.splice(topRowIndex, 1)[0];
  26625. topRow.clear();
  26626. this.rows.splice(this.currRow, 0, topRow);
  26627. this.logger.log(2, 'Rolling up');
  26628. // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
  26629. }
  26630. /**
  26631. * Get all non-empty rows with as unicode text.
  26632. */
  26633. getDisplayText(asOneRow) {
  26634. asOneRow = asOneRow || false;
  26635. const displayText = [];
  26636. let text = '';
  26637. let rowNr = -1;
  26638. for (let i = 0; i < NR_ROWS; i++) {
  26639. const rowText = this.rows[i].getTextString();
  26640. if (rowText) {
  26641. rowNr = i + 1;
  26642. if (asOneRow) {
  26643. displayText.push('Row ' + rowNr + ": '" + rowText + "'");
  26644. } else {
  26645. displayText.push(rowText.trim());
  26646. }
  26647. }
  26648. }
  26649. if (displayText.length > 0) {
  26650. if (asOneRow) {
  26651. text = '[' + displayText.join(' | ') + ']';
  26652. } else {
  26653. text = displayText.join('\n');
  26654. }
  26655. }
  26656. return text;
  26657. }
  26658. getTextAndFormat() {
  26659. return this.rows;
  26660. }
  26661. }
  26662. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  26663. class Cea608Channel {
  26664. constructor(channelNumber, outputFilter, logger) {
  26665. this.chNr = void 0;
  26666. this.outputFilter = void 0;
  26667. this.mode = void 0;
  26668. this.verbose = void 0;
  26669. this.displayedMemory = void 0;
  26670. this.nonDisplayedMemory = void 0;
  26671. this.lastOutputScreen = void 0;
  26672. this.currRollUpRow = void 0;
  26673. this.writeScreen = void 0;
  26674. this.cueStartTime = void 0;
  26675. this.logger = void 0;
  26676. this.chNr = channelNumber;
  26677. this.outputFilter = outputFilter;
  26678. this.mode = null;
  26679. this.verbose = 0;
  26680. this.displayedMemory = new CaptionScreen(logger);
  26681. this.nonDisplayedMemory = new CaptionScreen(logger);
  26682. this.lastOutputScreen = new CaptionScreen(logger);
  26683. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  26684. this.writeScreen = this.displayedMemory;
  26685. this.mode = null;
  26686. this.cueStartTime = null; // Keeps track of where a cue started.
  26687. this.logger = logger;
  26688. }
  26689. reset() {
  26690. this.mode = null;
  26691. this.displayedMemory.reset();
  26692. this.nonDisplayedMemory.reset();
  26693. this.lastOutputScreen.reset();
  26694. this.outputFilter.reset();
  26695. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  26696. this.writeScreen = this.displayedMemory;
  26697. this.mode = null;
  26698. this.cueStartTime = null;
  26699. }
  26700. getHandler() {
  26701. return this.outputFilter;
  26702. }
  26703. setHandler(newHandler) {
  26704. this.outputFilter = newHandler;
  26705. }
  26706. setPAC(pacData) {
  26707. this.writeScreen.setPAC(pacData);
  26708. }
  26709. setBkgData(bkgData) {
  26710. this.writeScreen.setBkgData(bkgData);
  26711. }
  26712. setMode(newMode) {
  26713. if (newMode === this.mode) {
  26714. return;
  26715. }
  26716. this.mode = newMode;
  26717. this.logger.log(2, () => 'MODE=' + newMode);
  26718. if (this.mode === 'MODE_POP-ON') {
  26719. this.writeScreen = this.nonDisplayedMemory;
  26720. } else {
  26721. this.writeScreen = this.displayedMemory;
  26722. this.writeScreen.reset();
  26723. }
  26724. if (this.mode !== 'MODE_ROLL-UP') {
  26725. this.displayedMemory.nrRollUpRows = null;
  26726. this.nonDisplayedMemory.nrRollUpRows = null;
  26727. }
  26728. this.mode = newMode;
  26729. }
  26730. insertChars(chars) {
  26731. for (let i = 0; i < chars.length; i++) {
  26732. this.writeScreen.insertChar(chars[i]);
  26733. }
  26734. const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  26735. this.logger.log(2, () => screen + ': ' + this.writeScreen.getDisplayText(true));
  26736. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  26737. this.logger.log(1, () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  26738. this.outputDataUpdate();
  26739. }
  26740. }
  26741. ccRCL() {
  26742. // Resume Caption Loading (switch mode to Pop On)
  26743. this.logger.log(2, 'RCL - Resume Caption Loading');
  26744. this.setMode('MODE_POP-ON');
  26745. }
  26746. ccBS() {
  26747. // BackSpace
  26748. this.logger.log(2, 'BS - BackSpace');
  26749. if (this.mode === 'MODE_TEXT') {
  26750. return;
  26751. }
  26752. this.writeScreen.backSpace();
  26753. if (this.writeScreen === this.displayedMemory) {
  26754. this.outputDataUpdate();
  26755. }
  26756. }
  26757. ccAOF() {
  26758. // Reserved (formerly Alarm Off)
  26759. }
  26760. ccAON() {
  26761. // Reserved (formerly Alarm On)
  26762. }
  26763. ccDER() {
  26764. // Delete to End of Row
  26765. this.logger.log(2, 'DER- Delete to End of Row');
  26766. this.writeScreen.clearToEndOfRow();
  26767. this.outputDataUpdate();
  26768. }
  26769. ccRU(nrRows) {
  26770. // Roll-Up Captions-2,3,or 4 Rows
  26771. this.logger.log(2, 'RU(' + nrRows + ') - Roll Up');
  26772. this.writeScreen = this.displayedMemory;
  26773. this.setMode('MODE_ROLL-UP');
  26774. this.writeScreen.setRollUpRows(nrRows);
  26775. }
  26776. ccFON() {
  26777. // Flash On
  26778. this.logger.log(2, 'FON - Flash On');
  26779. this.writeScreen.setPen({
  26780. flash: true
  26781. });
  26782. }
  26783. ccRDC() {
  26784. // Resume Direct Captioning (switch mode to PaintOn)
  26785. this.logger.log(2, 'RDC - Resume Direct Captioning');
  26786. this.setMode('MODE_PAINT-ON');
  26787. }
  26788. ccTR() {
  26789. // Text Restart in text mode (not supported, however)
  26790. this.logger.log(2, 'TR');
  26791. this.setMode('MODE_TEXT');
  26792. }
  26793. ccRTD() {
  26794. // Resume Text Display in Text mode (not supported, however)
  26795. this.logger.log(2, 'RTD');
  26796. this.setMode('MODE_TEXT');
  26797. }
  26798. ccEDM() {
  26799. // Erase Displayed Memory
  26800. this.logger.log(2, 'EDM - Erase Displayed Memory');
  26801. this.displayedMemory.reset();
  26802. this.outputDataUpdate(true);
  26803. }
  26804. ccCR() {
  26805. // Carriage Return
  26806. this.logger.log(2, 'CR - Carriage Return');
  26807. this.writeScreen.rollUp();
  26808. this.outputDataUpdate(true);
  26809. }
  26810. ccENM() {
  26811. // Erase Non-Displayed Memory
  26812. this.logger.log(2, 'ENM - Erase Non-displayed Memory');
  26813. this.nonDisplayedMemory.reset();
  26814. }
  26815. ccEOC() {
  26816. // End of Caption (Flip Memories)
  26817. this.logger.log(2, 'EOC - End Of Caption');
  26818. if (this.mode === 'MODE_POP-ON') {
  26819. const tmp = this.displayedMemory;
  26820. this.displayedMemory = this.nonDisplayedMemory;
  26821. this.nonDisplayedMemory = tmp;
  26822. this.writeScreen = this.nonDisplayedMemory;
  26823. this.logger.log(1, () => 'DISP: ' + this.displayedMemory.getDisplayText());
  26824. }
  26825. this.outputDataUpdate(true);
  26826. }
  26827. ccTO(nrCols) {
  26828. // Tab Offset 1,2, or 3 columns
  26829. this.logger.log(2, 'TO(' + nrCols + ') - Tab Offset');
  26830. this.writeScreen.moveCursor(nrCols);
  26831. }
  26832. ccMIDROW(secondByte) {
  26833. // Parse MIDROW command
  26834. const styles = {
  26835. flash: false
  26836. };
  26837. styles.underline = secondByte % 2 === 1;
  26838. styles.italics = secondByte >= 0x2e;
  26839. if (!styles.italics) {
  26840. const colorIndex = Math.floor(secondByte / 2) - 0x10;
  26841. const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  26842. styles.foreground = colors[colorIndex];
  26843. } else {
  26844. styles.foreground = 'white';
  26845. }
  26846. this.logger.log(2, 'MIDROW: ' + stringify(styles));
  26847. this.writeScreen.setPen(styles);
  26848. }
  26849. outputDataUpdate(dispatch = false) {
  26850. const time = this.logger.time;
  26851. if (time === null) {
  26852. return;
  26853. }
  26854. if (this.outputFilter) {
  26855. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  26856. // Start of a new cue
  26857. this.cueStartTime = time;
  26858. } else {
  26859. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  26860. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  26861. if (dispatch && this.outputFilter.dispatchCue) {
  26862. this.outputFilter.dispatchCue();
  26863. }
  26864. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  26865. }
  26866. }
  26867. this.lastOutputScreen.copy(this.displayedMemory);
  26868. }
  26869. }
  26870. cueSplitAtTime(t) {
  26871. if (this.outputFilter) {
  26872. if (!this.displayedMemory.isEmpty()) {
  26873. if (this.outputFilter.newCue) {
  26874. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  26875. }
  26876. this.cueStartTime = t;
  26877. }
  26878. }
  26879. }
  26880. }
  26881. // Will be 1 or 2 when parsing captions
  26882. class Cea608Parser {
  26883. constructor(field, out1, out2) {
  26884. this.channels = void 0;
  26885. this.currentChannel = 0;
  26886. this.cmdHistory = createCmdHistory();
  26887. this.logger = void 0;
  26888. const logger = this.logger = new CaptionsLogger();
  26889. this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
  26890. }
  26891. getHandler(channel) {
  26892. return this.channels[channel].getHandler();
  26893. }
  26894. setHandler(channel, newHandler) {
  26895. this.channels[channel].setHandler(newHandler);
  26896. }
  26897. /**
  26898. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  26899. */
  26900. addData(time, byteList) {
  26901. this.logger.time = time;
  26902. for (let i = 0; i < byteList.length; i += 2) {
  26903. const a = byteList[i] & 0x7f;
  26904. const b = byteList[i + 1] & 0x7f;
  26905. let cmdFound = false;
  26906. let charsFound = null;
  26907. if (a === 0 && b === 0) {
  26908. continue;
  26909. } else {
  26910. this.logger.log(3, () => '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  26911. }
  26912. const cmdHistory = this.cmdHistory;
  26913. const isControlCode = a >= 0x10 && a <= 0x1f;
  26914. if (isControlCode) {
  26915. // Skip redundant control codes
  26916. if (hasCmdRepeated(a, b, cmdHistory)) {
  26917. setLastCmd(null, null, cmdHistory);
  26918. this.logger.log(3, () => 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  26919. continue;
  26920. }
  26921. setLastCmd(a, b, this.cmdHistory);
  26922. cmdFound = this.parseCmd(a, b);
  26923. if (!cmdFound) {
  26924. cmdFound = this.parseMidrow(a, b);
  26925. }
  26926. if (!cmdFound) {
  26927. cmdFound = this.parsePAC(a, b);
  26928. }
  26929. if (!cmdFound) {
  26930. cmdFound = this.parseBackgroundAttributes(a, b);
  26931. }
  26932. } else {
  26933. setLastCmd(null, null, cmdHistory);
  26934. }
  26935. if (!cmdFound) {
  26936. charsFound = this.parseChars(a, b);
  26937. if (charsFound) {
  26938. const currChNr = this.currentChannel;
  26939. if (currChNr && currChNr > 0) {
  26940. const channel = this.channels[currChNr];
  26941. channel.insertChars(charsFound);
  26942. } else {
  26943. this.logger.log(2, 'No channel found yet. TEXT-MODE?');
  26944. }
  26945. }
  26946. }
  26947. if (!cmdFound && !charsFound) {
  26948. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  26949. }
  26950. }
  26951. }
  26952. /**
  26953. * Parse Command.
  26954. * @returns True if a command was found
  26955. */
  26956. parseCmd(a, b) {
  26957. const cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
  26958. const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
  26959. if (!(cond1 || cond2)) {
  26960. return false;
  26961. }
  26962. const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
  26963. const channel = this.channels[chNr];
  26964. if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
  26965. if (b === 0x20) {
  26966. channel.ccRCL();
  26967. } else if (b === 0x21) {
  26968. channel.ccBS();
  26969. } else if (b === 0x22) {
  26970. channel.ccAOF();
  26971. } else if (b === 0x23) {
  26972. channel.ccAON();
  26973. } else if (b === 0x24) {
  26974. channel.ccDER();
  26975. } else if (b === 0x25) {
  26976. channel.ccRU(2);
  26977. } else if (b === 0x26) {
  26978. channel.ccRU(3);
  26979. } else if (b === 0x27) {
  26980. channel.ccRU(4);
  26981. } else if (b === 0x28) {
  26982. channel.ccFON();
  26983. } else if (b === 0x29) {
  26984. channel.ccRDC();
  26985. } else if (b === 0x2a) {
  26986. channel.ccTR();
  26987. } else if (b === 0x2b) {
  26988. channel.ccRTD();
  26989. } else if (b === 0x2c) {
  26990. channel.ccEDM();
  26991. } else if (b === 0x2d) {
  26992. channel.ccCR();
  26993. } else if (b === 0x2e) {
  26994. channel.ccENM();
  26995. } else if (b === 0x2f) {
  26996. channel.ccEOC();
  26997. }
  26998. } else {
  26999. // a == 0x17 || a == 0x1F
  27000. channel.ccTO(b - 0x20);
  27001. }
  27002. this.currentChannel = chNr;
  27003. return true;
  27004. }
  27005. /**
  27006. * Parse midrow styling command
  27007. */
  27008. parseMidrow(a, b) {
  27009. let chNr = 0;
  27010. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  27011. if (a === 0x11) {
  27012. chNr = 1;
  27013. } else {
  27014. chNr = 2;
  27015. }
  27016. if (chNr !== this.currentChannel) {
  27017. this.logger.log(0, 'Mismatch channel in midrow parsing');
  27018. return false;
  27019. }
  27020. const channel = this.channels[chNr];
  27021. if (!channel) {
  27022. return false;
  27023. }
  27024. channel.ccMIDROW(b);
  27025. this.logger.log(3, () => 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  27026. return true;
  27027. }
  27028. return false;
  27029. }
  27030. /**
  27031. * Parse Preable Access Codes (Table 53).
  27032. * @returns {Boolean} Tells if PAC found
  27033. */
  27034. parsePAC(a, b) {
  27035. let row;
  27036. const case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
  27037. const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
  27038. if (!(case1 || case2)) {
  27039. return false;
  27040. }
  27041. const chNr = a <= 0x17 ? 1 : 2;
  27042. if (b >= 0x40 && b <= 0x5f) {
  27043. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  27044. } else {
  27045. // 0x60 <= b <= 0x7F
  27046. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  27047. }
  27048. const channel = this.channels[chNr];
  27049. if (!channel) {
  27050. return false;
  27051. }
  27052. channel.setPAC(this.interpretPAC(row, b));
  27053. this.currentChannel = chNr;
  27054. return true;
  27055. }
  27056. /**
  27057. * Interpret the second byte of the pac, and return the information.
  27058. * @returns pacData with style parameters
  27059. */
  27060. interpretPAC(row, byte) {
  27061. let pacIndex;
  27062. const pacData = {
  27063. color: null,
  27064. italics: false,
  27065. indent: null,
  27066. underline: false,
  27067. row: row
  27068. };
  27069. if (byte > 0x5f) {
  27070. pacIndex = byte - 0x60;
  27071. } else {
  27072. pacIndex = byte - 0x40;
  27073. }
  27074. pacData.underline = (pacIndex & 1) === 1;
  27075. if (pacIndex <= 0xd) {
  27076. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  27077. } else if (pacIndex <= 0xf) {
  27078. pacData.italics = true;
  27079. pacData.color = 'white';
  27080. } else {
  27081. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  27082. }
  27083. return pacData; // Note that row has zero offset. The spec uses 1.
  27084. }
  27085. /**
  27086. * Parse characters.
  27087. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  27088. */
  27089. parseChars(a, b) {
  27090. let channelNr;
  27091. let charCodes = null;
  27092. let charCode1 = null;
  27093. if (a >= 0x19) {
  27094. channelNr = 2;
  27095. charCode1 = a - 8;
  27096. } else {
  27097. channelNr = 1;
  27098. charCode1 = a;
  27099. }
  27100. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  27101. // Special character
  27102. let oneCode;
  27103. if (charCode1 === 0x11) {
  27104. oneCode = b + 0x50;
  27105. } else if (charCode1 === 0x12) {
  27106. oneCode = b + 0x70;
  27107. } else {
  27108. oneCode = b + 0x90;
  27109. }
  27110. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  27111. charCodes = [oneCode];
  27112. } else if (a >= 0x20 && a <= 0x7f) {
  27113. charCodes = b === 0 ? [a] : [a, b];
  27114. }
  27115. if (charCodes) {
  27116. this.logger.log(3, () => 'Char codes = ' + numArrayToHexArray(charCodes).join(','));
  27117. }
  27118. return charCodes;
  27119. }
  27120. /**
  27121. * Parse extended background attributes as well as new foreground color black.
  27122. * @returns True if background attributes are found
  27123. */
  27124. parseBackgroundAttributes(a, b) {
  27125. const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  27126. const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  27127. if (!(case1 || case2)) {
  27128. return false;
  27129. }
  27130. let index;
  27131. const bkgData = {};
  27132. if (a === 0x10 || a === 0x18) {
  27133. index = Math.floor((b - 0x20) / 2);
  27134. bkgData.background = backgroundColors[index];
  27135. if (b % 2 === 1) {
  27136. bkgData.background = bkgData.background + '_semi';
  27137. }
  27138. } else if (b === 0x2d) {
  27139. bkgData.background = 'transparent';
  27140. } else {
  27141. bkgData.foreground = 'black';
  27142. if (b === 0x2f) {
  27143. bkgData.underline = true;
  27144. }
  27145. }
  27146. const chNr = a <= 0x17 ? 1 : 2;
  27147. const channel = this.channels[chNr];
  27148. channel.setBkgData(bkgData);
  27149. return true;
  27150. }
  27151. /**
  27152. * Reset state of parser and its channels.
  27153. */
  27154. reset() {
  27155. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  27156. const channel = this.channels[i];
  27157. if (channel) {
  27158. channel.reset();
  27159. }
  27160. }
  27161. setLastCmd(null, null, this.cmdHistory);
  27162. }
  27163. /**
  27164. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  27165. */
  27166. cueSplitAtTime(t) {
  27167. for (let i = 0; i < this.channels.length; i++) {
  27168. const channel = this.channels[i];
  27169. if (channel) {
  27170. channel.cueSplitAtTime(t);
  27171. }
  27172. }
  27173. }
  27174. }
  27175. function setLastCmd(a, b, cmdHistory) {
  27176. cmdHistory.a = a;
  27177. cmdHistory.b = b;
  27178. }
  27179. function hasCmdRepeated(a, b, cmdHistory) {
  27180. return cmdHistory.a === a && cmdHistory.b === b;
  27181. }
  27182. function createCmdHistory() {
  27183. return {
  27184. a: null,
  27185. b: null
  27186. };
  27187. }
  27188. /**
  27189. * Copyright 2013 vtt.js Contributors
  27190. *
  27191. * Licensed under the Apache License, Version 2.0 (the 'License');
  27192. * you may not use this file except in compliance with the License.
  27193. * You may obtain a copy of the License at
  27194. *
  27195. * http://www.apache.org/licenses/LICENSE-2.0
  27196. *
  27197. * Unless required by applicable law or agreed to in writing, software
  27198. * distributed under the License is distributed on an 'AS IS' BASIS,
  27199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27200. * See the License for the specific language governing permissions and
  27201. * limitations under the License.
  27202. */
  27203. var VTTCue = (function () {
  27204. if (optionalSelf != null && optionalSelf.VTTCue) {
  27205. return self.VTTCue;
  27206. }
  27207. const AllowedDirections = ['', 'lr', 'rl'];
  27208. const AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
  27209. function isAllowedValue(allowed, value) {
  27210. if (typeof value !== 'string') {
  27211. return false;
  27212. }
  27213. // necessary for assuring the generic conforms to the Array interface
  27214. if (!Array.isArray(allowed)) {
  27215. return false;
  27216. }
  27217. // reset the type so that the next narrowing works well
  27218. const lcValue = value.toLowerCase();
  27219. // use the allow list to narrow the type to a specific subset of strings
  27220. if (~allowed.indexOf(lcValue)) {
  27221. return lcValue;
  27222. }
  27223. return false;
  27224. }
  27225. function findDirectionSetting(value) {
  27226. return isAllowedValue(AllowedDirections, value);
  27227. }
  27228. function findAlignSetting(value) {
  27229. return isAllowedValue(AllowedAlignments, value);
  27230. }
  27231. function extend(obj, ...rest) {
  27232. let i = 1;
  27233. for (; i < arguments.length; i++) {
  27234. const cobj = arguments[i];
  27235. for (const p in cobj) {
  27236. obj[p] = cobj[p];
  27237. }
  27238. }
  27239. return obj;
  27240. }
  27241. function VTTCue(startTime, endTime, text) {
  27242. const cue = this;
  27243. const baseObj = {
  27244. enumerable: true
  27245. };
  27246. /**
  27247. * Shim implementation specific properties. These properties are not in
  27248. * the spec.
  27249. */
  27250. // Lets us know when the VTTCue's data has changed in such a way that we need
  27251. // to recompute its display state. This lets us compute its display state
  27252. // lazily.
  27253. cue.hasBeenReset = false;
  27254. /**
  27255. * VTTCue and TextTrackCue properties
  27256. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  27257. */
  27258. let _id = '';
  27259. let _pauseOnExit = false;
  27260. let _startTime = startTime;
  27261. let _endTime = endTime;
  27262. let _text = text;
  27263. let _region = null;
  27264. let _vertical = '';
  27265. let _snapToLines = true;
  27266. let _line = 'auto';
  27267. let _lineAlign = 'start';
  27268. let _position = 50;
  27269. let _positionAlign = 'middle';
  27270. let _size = 50;
  27271. let _align = 'middle';
  27272. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  27273. get: function () {
  27274. return _id;
  27275. },
  27276. set: function (value) {
  27277. _id = '' + value;
  27278. }
  27279. }));
  27280. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  27281. get: function () {
  27282. return _pauseOnExit;
  27283. },
  27284. set: function (value) {
  27285. _pauseOnExit = !!value;
  27286. }
  27287. }));
  27288. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  27289. get: function () {
  27290. return _startTime;
  27291. },
  27292. set: function (value) {
  27293. if (typeof value !== 'number') {
  27294. throw new TypeError('Start time must be set to a number.');
  27295. }
  27296. _startTime = value;
  27297. this.hasBeenReset = true;
  27298. }
  27299. }));
  27300. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  27301. get: function () {
  27302. return _endTime;
  27303. },
  27304. set: function (value) {
  27305. if (typeof value !== 'number') {
  27306. throw new TypeError('End time must be set to a number.');
  27307. }
  27308. _endTime = value;
  27309. this.hasBeenReset = true;
  27310. }
  27311. }));
  27312. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  27313. get: function () {
  27314. return _text;
  27315. },
  27316. set: function (value) {
  27317. _text = '' + value;
  27318. this.hasBeenReset = true;
  27319. }
  27320. }));
  27321. // todo: implement VTTRegion polyfill?
  27322. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  27323. get: function () {
  27324. return _region;
  27325. },
  27326. set: function (value) {
  27327. _region = value;
  27328. this.hasBeenReset = true;
  27329. }
  27330. }));
  27331. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  27332. get: function () {
  27333. return _vertical;
  27334. },
  27335. set: function (value) {
  27336. const setting = findDirectionSetting(value);
  27337. // Have to check for false because the setting an be an empty string.
  27338. if (setting === false) {
  27339. throw new SyntaxError('An invalid or illegal string was specified.');
  27340. }
  27341. _vertical = setting;
  27342. this.hasBeenReset = true;
  27343. }
  27344. }));
  27345. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  27346. get: function () {
  27347. return _snapToLines;
  27348. },
  27349. set: function (value) {
  27350. _snapToLines = !!value;
  27351. this.hasBeenReset = true;
  27352. }
  27353. }));
  27354. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  27355. get: function () {
  27356. return _line;
  27357. },
  27358. set: function (value) {
  27359. if (typeof value !== 'number' && value !== 'auto') {
  27360. throw new SyntaxError('An invalid number or illegal string was specified.');
  27361. }
  27362. _line = value;
  27363. this.hasBeenReset = true;
  27364. }
  27365. }));
  27366. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  27367. get: function () {
  27368. return _lineAlign;
  27369. },
  27370. set: function (value) {
  27371. const setting = findAlignSetting(value);
  27372. if (!setting) {
  27373. throw new SyntaxError('An invalid or illegal string was specified.');
  27374. }
  27375. _lineAlign = setting;
  27376. this.hasBeenReset = true;
  27377. }
  27378. }));
  27379. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  27380. get: function () {
  27381. return _position;
  27382. },
  27383. set: function (value) {
  27384. if (value < 0 || value > 100) {
  27385. throw new Error('Position must be between 0 and 100.');
  27386. }
  27387. _position = value;
  27388. this.hasBeenReset = true;
  27389. }
  27390. }));
  27391. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  27392. get: function () {
  27393. return _positionAlign;
  27394. },
  27395. set: function (value) {
  27396. const setting = findAlignSetting(value);
  27397. if (!setting) {
  27398. throw new SyntaxError('An invalid or illegal string was specified.');
  27399. }
  27400. _positionAlign = setting;
  27401. this.hasBeenReset = true;
  27402. }
  27403. }));
  27404. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  27405. get: function () {
  27406. return _size;
  27407. },
  27408. set: function (value) {
  27409. if (value < 0 || value > 100) {
  27410. throw new Error('Size must be between 0 and 100.');
  27411. }
  27412. _size = value;
  27413. this.hasBeenReset = true;
  27414. }
  27415. }));
  27416. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  27417. get: function () {
  27418. return _align;
  27419. },
  27420. set: function (value) {
  27421. const setting = findAlignSetting(value);
  27422. if (!setting) {
  27423. throw new SyntaxError('An invalid or illegal string was specified.');
  27424. }
  27425. _align = setting;
  27426. this.hasBeenReset = true;
  27427. }
  27428. }));
  27429. /**
  27430. * Other <track> spec defined properties
  27431. */
  27432. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  27433. cue.displayState = undefined;
  27434. }
  27435. /**
  27436. * VTTCue methods
  27437. */
  27438. VTTCue.prototype.getCueAsHTML = function () {
  27439. // Assume WebVTT.convertCueToDOMTree is on the global.
  27440. const WebVTT = self.WebVTT;
  27441. return WebVTT.convertCueToDOMTree(self, this.text);
  27442. };
  27443. // this is a polyfill hack
  27444. return VTTCue;
  27445. })();
  27446. /*
  27447. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
  27448. */
  27449. class StringDecoder {
  27450. decode(data, options) {
  27451. if (!data) {
  27452. return '';
  27453. }
  27454. if (typeof data !== 'string') {
  27455. throw new Error('Error - expected string data.');
  27456. }
  27457. return decodeURIComponent(encodeURIComponent(data));
  27458. }
  27459. }
  27460. // Try to parse input as a time stamp.
  27461. function parseTimeStamp(input) {
  27462. function computeSeconds(h, m, s, f) {
  27463. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
  27464. }
  27465. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  27466. if (!m) {
  27467. return null;
  27468. }
  27469. if (parseFloat(m[2]) > 59) {
  27470. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  27471. // First position is hours as it's over 59.
  27472. return computeSeconds(m[2], m[3], 0, m[4]);
  27473. }
  27474. // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
  27475. return computeSeconds(m[1], m[2], m[3], m[4]);
  27476. }
  27477. // A settings object holds key/value pairs and will ignore anything but the first
  27478. // assignment to a specific key.
  27479. class Settings {
  27480. constructor() {
  27481. this.values = Object.create(null);
  27482. }
  27483. // Only accept the first assignment to any key.
  27484. set(k, v) {
  27485. if (!this.get(k) && v !== '') {
  27486. this.values[k] = v;
  27487. }
  27488. }
  27489. // Return the value for a key, or a default value.
  27490. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  27491. // a number of possible default values as properties where 'defaultKey' is
  27492. // the key of the property that will be chosen; otherwise it's assumed to be
  27493. // a single value.
  27494. get(k, dflt, defaultKey) {
  27495. if (defaultKey) {
  27496. return this.has(k) ? this.values[k] : dflt[defaultKey];
  27497. }
  27498. return this.has(k) ? this.values[k] : dflt;
  27499. }
  27500. // Check whether we have a value for a key.
  27501. has(k) {
  27502. return k in this.values;
  27503. }
  27504. // Accept a setting if its one of the given alternatives.
  27505. alt(k, v, a) {
  27506. for (let n = 0; n < a.length; ++n) {
  27507. if (v === a[n]) {
  27508. this.set(k, v);
  27509. break;
  27510. }
  27511. }
  27512. }
  27513. // Accept a setting if its a valid (signed) integer.
  27514. integer(k, v) {
  27515. if (/^-?\d+$/.test(v)) {
  27516. // integer
  27517. this.set(k, parseInt(v, 10));
  27518. }
  27519. }
  27520. // Accept a setting if its a valid percentage.
  27521. percent(k, v) {
  27522. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  27523. const percent = parseFloat(v);
  27524. if (percent >= 0 && percent <= 100) {
  27525. this.set(k, percent);
  27526. return true;
  27527. }
  27528. }
  27529. return false;
  27530. }
  27531. }
  27532. // Helper function to parse input into groups separated by 'groupDelim', and
  27533. // interpret each group as a key/value pair separated by 'keyValueDelim'.
  27534. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  27535. const groups = groupDelim ? input.split(groupDelim) : [input];
  27536. for (const i in groups) {
  27537. if (typeof groups[i] !== 'string') {
  27538. continue;
  27539. }
  27540. const kv = groups[i].split(keyValueDelim);
  27541. if (kv.length !== 2) {
  27542. continue;
  27543. }
  27544. const k = kv[0];
  27545. const v = kv[1];
  27546. callback(k, v);
  27547. }
  27548. }
  27549. const defaults = new VTTCue(0, 0, '');
  27550. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  27551. // Safari doesn't yet support this change, but FF and Chrome do.
  27552. const center = defaults.align === 'middle' ? 'middle' : 'center';
  27553. function parseCue(input, cue, regionList) {
  27554. // Remember the original input if we need to throw an error.
  27555. const oInput = input;
  27556. // 4.1 WebVTT timestamp
  27557. function consumeTimeStamp() {
  27558. const ts = parseTimeStamp(input);
  27559. if (ts === null) {
  27560. throw new Error('Malformed timestamp: ' + oInput);
  27561. }
  27562. // Remove time stamp from input.
  27563. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  27564. return ts;
  27565. }
  27566. // 4.4.2 WebVTT cue settings
  27567. function consumeCueSettings(input, cue) {
  27568. const settings = new Settings();
  27569. parseOptions(input, function (k, v) {
  27570. let vals;
  27571. switch (k) {
  27572. case 'region':
  27573. // Find the last region we parsed with the same region id.
  27574. for (let i = regionList.length - 1; i >= 0; i--) {
  27575. if (regionList[i].id === v) {
  27576. settings.set(k, regionList[i].region);
  27577. break;
  27578. }
  27579. }
  27580. break;
  27581. case 'vertical':
  27582. settings.alt(k, v, ['rl', 'lr']);
  27583. break;
  27584. case 'line':
  27585. vals = v.split(',');
  27586. settings.integer(k, vals[0]);
  27587. if (settings.percent(k, vals[0])) {
  27588. settings.set('snapToLines', false);
  27589. }
  27590. settings.alt(k, vals[0], ['auto']);
  27591. if (vals.length === 2) {
  27592. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  27593. }
  27594. break;
  27595. case 'position':
  27596. vals = v.split(',');
  27597. settings.percent(k, vals[0]);
  27598. if (vals.length === 2) {
  27599. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  27600. }
  27601. break;
  27602. case 'size':
  27603. settings.percent(k, v);
  27604. break;
  27605. case 'align':
  27606. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  27607. break;
  27608. }
  27609. }, /:/, /\s/);
  27610. // Apply default values for any missing fields.
  27611. cue.region = settings.get('region', null);
  27612. cue.vertical = settings.get('vertical', '');
  27613. let line = settings.get('line', 'auto');
  27614. if (line === 'auto' && defaults.line === -1) {
  27615. // set numeric line number for Safari
  27616. line = -1;
  27617. }
  27618. cue.line = line;
  27619. cue.lineAlign = settings.get('lineAlign', 'start');
  27620. cue.snapToLines = settings.get('snapToLines', true);
  27621. cue.size = settings.get('size', 100);
  27622. cue.align = settings.get('align', center);
  27623. let position = settings.get('position', 'auto');
  27624. if (position === 'auto' && defaults.position === 50) {
  27625. // set numeric position for Safari
  27626. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  27627. }
  27628. cue.position = position;
  27629. }
  27630. function skipWhitespace() {
  27631. input = input.replace(/^\s+/, '');
  27632. }
  27633. // 4.1 WebVTT cue timings.
  27634. skipWhitespace();
  27635. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  27636. skipWhitespace();
  27637. if (input.slice(0, 3) !== '-->') {
  27638. // (3) next characters must match '-->'
  27639. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  27640. }
  27641. input = input.slice(3);
  27642. skipWhitespace();
  27643. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  27644. // 4.1 WebVTT cue settings list.
  27645. skipWhitespace();
  27646. consumeCueSettings(input, cue);
  27647. }
  27648. function fixLineBreaks(input) {
  27649. return input.replace(/<br(?: \/)?>/gi, '\n');
  27650. }
  27651. class VTTParser {
  27652. constructor() {
  27653. this.state = 'INITIAL';
  27654. this.buffer = '';
  27655. this.decoder = new StringDecoder();
  27656. this.regionList = [];
  27657. this.cue = null;
  27658. this.oncue = void 0;
  27659. this.onparsingerror = void 0;
  27660. this.onflush = void 0;
  27661. }
  27662. parse(data) {
  27663. const _this = this;
  27664. // If there is no data then we won't decode it, but will just try to parse
  27665. // whatever is in buffer already. This may occur in circumstances, for
  27666. // example when flush() is called.
  27667. if (data) {
  27668. // Try to decode the data that we received.
  27669. _this.buffer += _this.decoder.decode(data, {
  27670. stream: true
  27671. });
  27672. }
  27673. function collectNextLine() {
  27674. let buffer = _this.buffer;
  27675. let pos = 0;
  27676. buffer = fixLineBreaks(buffer);
  27677. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  27678. ++pos;
  27679. }
  27680. const line = buffer.slice(0, pos);
  27681. // Advance the buffer early in case we fail below.
  27682. if (buffer[pos] === '\r') {
  27683. ++pos;
  27684. }
  27685. if (buffer[pos] === '\n') {
  27686. ++pos;
  27687. }
  27688. _this.buffer = buffer.slice(pos);
  27689. return line;
  27690. }
  27691. // 3.2 WebVTT metadata header syntax
  27692. function parseHeader(input) {
  27693. parseOptions(input, function (k, v) {
  27694. // switch (k) {
  27695. // case 'region':
  27696. // 3.3 WebVTT region metadata header syntax
  27697. // console.log('parse region', v);
  27698. // parseRegion(v);
  27699. // break;
  27700. // }
  27701. }, /:/);
  27702. }
  27703. // 5.1 WebVTT file parsing.
  27704. try {
  27705. let line = '';
  27706. if (_this.state === 'INITIAL') {
  27707. // We can't start parsing until we have the first line.
  27708. if (!/\r\n|\n/.test(_this.buffer)) {
  27709. return this;
  27710. }
  27711. line = collectNextLine();
  27712. // strip of UTF-8 BOM if any
  27713. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  27714. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  27715. if (!(m != null && m[0])) {
  27716. throw new Error('Malformed WebVTT signature.');
  27717. }
  27718. _this.state = 'HEADER';
  27719. }
  27720. let alreadyCollectedLine = false;
  27721. while (_this.buffer) {
  27722. // We can't parse a line until we have the full line.
  27723. if (!/\r\n|\n/.test(_this.buffer)) {
  27724. return this;
  27725. }
  27726. if (!alreadyCollectedLine) {
  27727. line = collectNextLine();
  27728. } else {
  27729. alreadyCollectedLine = false;
  27730. }
  27731. switch (_this.state) {
  27732. case 'HEADER':
  27733. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  27734. if (/:/.test(line)) {
  27735. parseHeader(line);
  27736. } else if (!line) {
  27737. // An empty line terminates the header and starts the body (cues).
  27738. _this.state = 'ID';
  27739. }
  27740. continue;
  27741. case 'NOTE':
  27742. // Ignore NOTE blocks.
  27743. if (!line) {
  27744. _this.state = 'ID';
  27745. }
  27746. continue;
  27747. case 'ID':
  27748. // Check for the start of NOTE blocks.
  27749. if (/^NOTE($|[ \t])/.test(line)) {
  27750. _this.state = 'NOTE';
  27751. break;
  27752. }
  27753. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  27754. if (!line) {
  27755. continue;
  27756. }
  27757. _this.cue = new VTTCue(0, 0, '');
  27758. _this.state = 'CUE';
  27759. // 30-39 - Check if self line contains an optional identifier or timing data.
  27760. if (line.indexOf('-->') === -1) {
  27761. _this.cue.id = line;
  27762. continue;
  27763. }
  27764. // Process line as start of a cue.
  27765. /* falls through */
  27766. case 'CUE':
  27767. // 40 - Collect cue timings and settings.
  27768. if (!_this.cue) {
  27769. _this.state = 'BADCUE';
  27770. continue;
  27771. }
  27772. try {
  27773. parseCue(line, _this.cue, _this.regionList);
  27774. } catch (e) {
  27775. // In case of an error ignore rest of the cue.
  27776. _this.cue = null;
  27777. _this.state = 'BADCUE';
  27778. continue;
  27779. }
  27780. _this.state = 'CUETEXT';
  27781. continue;
  27782. case 'CUETEXT':
  27783. {
  27784. const hasSubstring = line.indexOf('-->') !== -1;
  27785. // 34 - If we have an empty line then report the cue.
  27786. // 35 - If we have the special substring '-->' then report the cue,
  27787. // but do not collect the line as we need to process the current
  27788. // one as a new cue.
  27789. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  27790. // We are done parsing self cue.
  27791. if (_this.oncue && _this.cue) {
  27792. _this.oncue(_this.cue);
  27793. }
  27794. _this.cue = null;
  27795. _this.state = 'ID';
  27796. continue;
  27797. }
  27798. if (_this.cue === null) {
  27799. continue;
  27800. }
  27801. if (_this.cue.text) {
  27802. _this.cue.text += '\n';
  27803. }
  27804. _this.cue.text += line;
  27805. }
  27806. continue;
  27807. case 'BADCUE':
  27808. // 54-62 - Collect and discard the remaining cue.
  27809. if (!line) {
  27810. _this.state = 'ID';
  27811. }
  27812. }
  27813. }
  27814. } catch (e) {
  27815. // If we are currently parsing a cue, report what we have.
  27816. if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
  27817. _this.oncue(_this.cue);
  27818. }
  27819. _this.cue = null;
  27820. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  27821. // another exception occurred so enter BADCUE state.
  27822. _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  27823. }
  27824. return this;
  27825. }
  27826. flush() {
  27827. const _this = this;
  27828. try {
  27829. // Finish decoding the stream.
  27830. // _this.buffer += _this.decoder.decode();
  27831. // Synthesize the end of the current cue or region.
  27832. if (_this.cue || _this.state === 'HEADER') {
  27833. _this.buffer += '\n\n';
  27834. _this.parse();
  27835. }
  27836. // If we've flushed, parsed, and we're still on the INITIAL state then
  27837. // that means we don't have enough of the stream to parse the first
  27838. // line.
  27839. if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
  27840. throw new Error('Malformed WebVTT signature.');
  27841. }
  27842. } catch (e) {
  27843. if (_this.onparsingerror) {
  27844. _this.onparsingerror(e);
  27845. }
  27846. }
  27847. if (_this.onflush) {
  27848. _this.onflush();
  27849. }
  27850. return this;
  27851. }
  27852. }
  27853. const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  27854. // String.prototype.startsWith is not supported in IE11
  27855. const startsWith = function startsWith(inputString, searchString, position = 0) {
  27856. return inputString.slice(position, position + searchString.length) === searchString;
  27857. };
  27858. const cueString2millis = function cueString2millis(timeString) {
  27859. let ts = parseInt(timeString.slice(-3));
  27860. const secs = parseInt(timeString.slice(-6, -4));
  27861. const mins = parseInt(timeString.slice(-9, -7));
  27862. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(':'))) : 0;
  27863. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  27864. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  27865. }
  27866. ts += 1000 * secs;
  27867. ts += 60 * 1000 * mins;
  27868. ts += 60 * 60 * 1000 * hours;
  27869. return ts;
  27870. };
  27871. // Create a unique hash id for a cue based on start/end times and text.
  27872. // This helps timeline-controller to avoid showing repeated captions.
  27873. function generateCueId(startTime, endTime, text) {
  27874. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  27875. }
  27876. const calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  27877. let currCC = vttCCs[cc];
  27878. let prevCC = vttCCs[currCC.prevCC];
  27879. // This is the first discontinuity or cues have been processed since the last discontinuity
  27880. // Offset = current discontinuity time
  27881. if (!prevCC || !prevCC.new && currCC.new) {
  27882. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  27883. currCC.new = false;
  27884. return;
  27885. }
  27886. // There have been discontinuities since cues were last parsed.
  27887. // Offset = time elapsed
  27888. while ((_prevCC = prevCC) != null && _prevCC.new) {
  27889. var _prevCC;
  27890. vttCCs.ccOffset += currCC.start - prevCC.start;
  27891. currCC.new = false;
  27892. currCC = prevCC;
  27893. prevCC = vttCCs[currCC.prevCC];
  27894. }
  27895. vttCCs.presentationOffset = presentationTime;
  27896. };
  27897. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  27898. const parser = new VTTParser();
  27899. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  27900. // Uint8Array.prototype.reduce is not implemented in IE11
  27901. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
  27902. const cues = [];
  27903. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  27904. let cueTime = '00:00.000';
  27905. let timestampMapMPEGTS = 0;
  27906. let timestampMapLOCAL = 0;
  27907. let parsingError;
  27908. let inHeader = true;
  27909. parser.oncue = function (cue) {
  27910. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  27911. const currCC = vttCCs[cc];
  27912. let cueOffset = vttCCs.ccOffset;
  27913. // Calculate subtitle PTS offset
  27914. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;
  27915. // Update offsets for new discontinuities
  27916. if (currCC != null && currCC.new) {
  27917. if (timestampMapLOCAL !== undefined) {
  27918. // When local time is provided, offset = discontinuity start time - local time
  27919. cueOffset = vttCCs.ccOffset = currCC.start;
  27920. } else {
  27921. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  27922. }
  27923. }
  27924. if (webVttMpegTsMapOffset) {
  27925. if (!initPTS) {
  27926. parsingError = new Error('Missing initPTS for VTT MPEGTS');
  27927. return;
  27928. }
  27929. // If we have MPEGTS, offset = presentation time + discontinuity offset
  27930. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  27931. }
  27932. const duration = cue.endTime - cue.startTime;
  27933. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
  27934. cue.startTime = Math.max(startTime, 0);
  27935. cue.endTime = Math.max(startTime + duration, 0);
  27936. //trim trailing webvtt block whitespaces
  27937. const text = cue.text.trim();
  27938. // Fix encoding of special characters
  27939. cue.text = decodeURIComponent(encodeURIComponent(text));
  27940. // If the cue was not assigned an id from the VTT file (line above the content), create one.
  27941. if (!cue.id) {
  27942. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  27943. }
  27944. if (cue.endTime > 0) {
  27945. cues.push(cue);
  27946. }
  27947. };
  27948. parser.onparsingerror = function (error) {
  27949. parsingError = error;
  27950. };
  27951. parser.onflush = function () {
  27952. if (parsingError) {
  27953. errorCallBack(parsingError);
  27954. return;
  27955. }
  27956. callBack(cues);
  27957. };
  27958. // Go through contents line by line.
  27959. vttLines.forEach(line => {
  27960. if (inHeader) {
  27961. // Look for X-TIMESTAMP-MAP in header.
  27962. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  27963. // Once found, no more are allowed anyway, so stop searching.
  27964. inHeader = false;
  27965. // Extract LOCAL and MPEGTS.
  27966. line.slice(16).split(',').forEach(timestamp => {
  27967. if (startsWith(timestamp, 'LOCAL:')) {
  27968. cueTime = timestamp.slice(6);
  27969. } else if (startsWith(timestamp, 'MPEGTS:')) {
  27970. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  27971. }
  27972. });
  27973. try {
  27974. // Convert cue time to seconds
  27975. timestampMapLOCAL = cueString2millis(cueTime) / 1000;
  27976. } catch (error) {
  27977. parsingError = error;
  27978. }
  27979. // Return without parsing X-TIMESTAMP-MAP line.
  27980. return;
  27981. } else if (line === '') {
  27982. inHeader = false;
  27983. }
  27984. }
  27985. // Parse line by default.
  27986. parser.parse(line + '\n');
  27987. });
  27988. parser.flush();
  27989. }
  27990. const IMSC1_CODEC = 'stpp.ttml.im1t';
  27991. // Time format: h:m:s:frames(.subframes)
  27992. const HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  27993. // Time format: hours, minutes, seconds, milliseconds, frames, ticks
  27994. const TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  27995. const textAlignToLineAlign = {
  27996. left: 'start',
  27997. center: 'center',
  27998. right: 'end',
  27999. start: 'start',
  28000. end: 'end'
  28001. };
  28002. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  28003. const results = findBox(new Uint8Array(payload), ['mdat']);
  28004. if (results.length === 0) {
  28005. errorCallBack(new Error('Could not parse IMSC1 mdat'));
  28006. return;
  28007. }
  28008. const ttmlList = results.map(mdat => utf8ArrayToStr(mdat));
  28009. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  28010. try {
  28011. ttmlList.forEach(ttml => callBack(parseTTML(ttml, syncTime)));
  28012. } catch (error) {
  28013. errorCallBack(error);
  28014. }
  28015. }
  28016. function parseTTML(ttml, syncTime) {
  28017. const parser = new DOMParser();
  28018. const xmlDoc = parser.parseFromString(ttml, 'text/xml');
  28019. const tt = xmlDoc.getElementsByTagName('tt')[0];
  28020. if (!tt) {
  28021. throw new Error('Invalid ttml');
  28022. }
  28023. const defaultRateInfo = {
  28024. frameRate: 30,
  28025. subFrameRate: 1,
  28026. frameRateMultiplier: 0,
  28027. tickRate: 0
  28028. };
  28029. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  28030. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  28031. return result;
  28032. }, {});
  28033. const trim = tt.getAttribute('xml:space') !== 'preserve';
  28034. const styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
  28035. const regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
  28036. const cueElements = getElementCollection(tt, 'body', '[begin]');
  28037. return [].map.call(cueElements, cueElement => {
  28038. const cueText = getTextContent(cueElement, trim);
  28039. if (!cueText || !cueElement.hasAttribute('begin')) {
  28040. return null;
  28041. }
  28042. const startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
  28043. const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
  28044. let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
  28045. if (startTime === null) {
  28046. throw timestampParsingError(cueElement);
  28047. }
  28048. if (endTime === null) {
  28049. if (duration === null) {
  28050. throw timestampParsingError(cueElement);
  28051. }
  28052. endTime = startTime + duration;
  28053. }
  28054. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  28055. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  28056. const region = regionElements[cueElement.getAttribute('region')];
  28057. const style = styleElements[cueElement.getAttribute('style')];
  28058. // Apply styles to cue
  28059. const styles = getTtmlStyles(region, style, styleElements);
  28060. const {
  28061. textAlign
  28062. } = styles;
  28063. if (textAlign) {
  28064. // cue.positionAlign not settable in FF~2016
  28065. const lineAlign = textAlignToLineAlign[textAlign];
  28066. if (lineAlign) {
  28067. cue.lineAlign = lineAlign;
  28068. }
  28069. cue.align = textAlign;
  28070. }
  28071. _extends(cue, styles);
  28072. return cue;
  28073. }).filter(cue => cue !== null);
  28074. }
  28075. function getElementCollection(fromElement, parentName, childName) {
  28076. const parent = fromElement.getElementsByTagName(parentName)[0];
  28077. if (parent) {
  28078. return [].slice.call(parent.querySelectorAll(childName));
  28079. }
  28080. return [];
  28081. }
  28082. function collectionToDictionary(elementsWithId) {
  28083. return elementsWithId.reduce((dict, element) => {
  28084. const id = element.getAttribute('xml:id');
  28085. if (id) {
  28086. dict[id] = element;
  28087. }
  28088. return dict;
  28089. }, {});
  28090. }
  28091. function getTextContent(element, trim) {
  28092. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  28093. var _node$childNodes;
  28094. if (node.nodeName === 'br' && i) {
  28095. return str + '\n';
  28096. }
  28097. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  28098. return getTextContent(node, trim);
  28099. } else if (trim) {
  28100. return str + node.textContent.trim().replace(/\s+/g, ' ');
  28101. }
  28102. return str + node.textContent;
  28103. }, '');
  28104. }
  28105. function getTtmlStyles(region, style, styleElements) {
  28106. const ttsNs = 'http://www.w3.org/ns/ttml#styling';
  28107. let regionStyle = null;
  28108. const styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily'
  28109. // 'fontWeight',
  28110. // 'lineHeight',
  28111. // 'wrapOption',
  28112. // 'fontStyle',
  28113. // 'direction',
  28114. // 'writingMode'
  28115. ];
  28116. const regionStyleName = region != null && region.hasAttribute('style') ? region.getAttribute('style') : null;
  28117. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  28118. regionStyle = styleElements[regionStyleName];
  28119. }
  28120. return styleAttributes.reduce((styles, name) => {
  28121. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  28122. if (value) {
  28123. styles[name] = value;
  28124. }
  28125. return styles;
  28126. }, {});
  28127. }
  28128. function getAttributeNS(element, ns, name) {
  28129. if (!element) {
  28130. return null;
  28131. }
  28132. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  28133. }
  28134. function timestampParsingError(node) {
  28135. return new Error(`Could not parse ttml timestamp ${node}`);
  28136. }
  28137. function parseTtmlTime(timeAttributeValue, rateInfo) {
  28138. if (!timeAttributeValue) {
  28139. return null;
  28140. }
  28141. let seconds = parseTimeStamp(timeAttributeValue);
  28142. if (seconds === null) {
  28143. if (HMSF_REGEX.test(timeAttributeValue)) {
  28144. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  28145. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  28146. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  28147. }
  28148. }
  28149. return seconds;
  28150. }
  28151. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  28152. const m = HMSF_REGEX.exec(timeAttributeValue);
  28153. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  28154. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  28155. }
  28156. function parseTimeUnits(timeAttributeValue, rateInfo) {
  28157. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  28158. const value = Number(m[1]);
  28159. const unit = m[2];
  28160. switch (unit) {
  28161. case 'h':
  28162. return value * 3600;
  28163. case 'm':
  28164. return value * 60;
  28165. case 'ms':
  28166. return value * 1000;
  28167. case 'f':
  28168. return value / rateInfo.frameRate;
  28169. case 't':
  28170. return value / rateInfo.tickRate;
  28171. }
  28172. return value;
  28173. }
  28174. class OutputFilter {
  28175. constructor(timelineController, trackName) {
  28176. this.timelineController = void 0;
  28177. this.cueRanges = [];
  28178. this.trackName = void 0;
  28179. this.startTime = null;
  28180. this.endTime = null;
  28181. this.screen = null;
  28182. this.timelineController = timelineController;
  28183. this.trackName = trackName;
  28184. }
  28185. dispatchCue() {
  28186. if (this.startTime === null) {
  28187. return;
  28188. }
  28189. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  28190. this.startTime = null;
  28191. }
  28192. newCue(startTime, endTime, screen) {
  28193. if (this.startTime === null || this.startTime > startTime) {
  28194. this.startTime = startTime;
  28195. }
  28196. this.endTime = endTime;
  28197. this.screen = screen;
  28198. this.timelineController.createCaptionsTrack(this.trackName);
  28199. }
  28200. reset() {
  28201. this.cueRanges = [];
  28202. this.startTime = null;
  28203. }
  28204. }
  28205. class TimelineController {
  28206. constructor(hls) {
  28207. this.hls = void 0;
  28208. this.media = null;
  28209. this.config = void 0;
  28210. this.enabled = true;
  28211. this.Cues = void 0;
  28212. this.textTracks = [];
  28213. this.tracks = [];
  28214. this.initPTS = [];
  28215. this.unparsedVttFrags = [];
  28216. this.captionsTracks = {};
  28217. this.nonNativeCaptionsTracks = {};
  28218. this.cea608Parser1 = void 0;
  28219. this.cea608Parser2 = void 0;
  28220. this.lastCc = -1;
  28221. // Last video (CEA-608) fragment CC
  28222. this.lastSn = -1;
  28223. // Last video (CEA-608) fragment MSN
  28224. this.lastPartIndex = -1;
  28225. // Last video (CEA-608) fragment Part Index
  28226. this.prevCC = -1;
  28227. // Last subtitle fragment CC
  28228. this.vttCCs = newVTTCCs();
  28229. this.captionsProperties = void 0;
  28230. this.hls = hls;
  28231. this.config = hls.config;
  28232. this.Cues = hls.config.cueHandler;
  28233. this.captionsProperties = {
  28234. textTrack1: {
  28235. label: this.config.captionsTextTrack1Label,
  28236. languageCode: this.config.captionsTextTrack1LanguageCode
  28237. },
  28238. textTrack2: {
  28239. label: this.config.captionsTextTrack2Label,
  28240. languageCode: this.config.captionsTextTrack2LanguageCode
  28241. },
  28242. textTrack3: {
  28243. label: this.config.captionsTextTrack3Label,
  28244. languageCode: this.config.captionsTextTrack3LanguageCode
  28245. },
  28246. textTrack4: {
  28247. label: this.config.captionsTextTrack4Label,
  28248. languageCode: this.config.captionsTextTrack4LanguageCode
  28249. }
  28250. };
  28251. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28252. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28253. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28254. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  28255. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  28256. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  28257. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  28258. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  28259. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  28260. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  28261. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  28262. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28263. }
  28264. destroy() {
  28265. const {
  28266. hls
  28267. } = this;
  28268. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  28269. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  28270. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  28271. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  28272. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  28273. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  28274. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  28275. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  28276. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  28277. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  28278. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  28279. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  28280. // @ts-ignore
  28281. this.hls = this.config = this.media = null;
  28282. this.cea608Parser1 = this.cea608Parser2 = undefined;
  28283. }
  28284. initCea608Parsers() {
  28285. const channel1 = new OutputFilter(this, 'textTrack1');
  28286. const channel2 = new OutputFilter(this, 'textTrack2');
  28287. const channel3 = new OutputFilter(this, 'textTrack3');
  28288. const channel4 = new OutputFilter(this, 'textTrack4');
  28289. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  28290. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  28291. }
  28292. addCues(trackName, startTime, endTime, screen, cueRanges) {
  28293. // skip cues which overlap more than 50% with previously parsed time ranges
  28294. let merged = false;
  28295. for (let i = cueRanges.length; i--;) {
  28296. const cueRange = cueRanges[i];
  28297. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  28298. if (overlap >= 0) {
  28299. cueRange[0] = Math.min(cueRange[0], startTime);
  28300. cueRange[1] = Math.max(cueRange[1], endTime);
  28301. merged = true;
  28302. if (overlap / (endTime - startTime) > 0.5) {
  28303. return;
  28304. }
  28305. }
  28306. }
  28307. if (!merged) {
  28308. cueRanges.push([startTime, endTime]);
  28309. }
  28310. if (this.config.renderTextTracksNatively) {
  28311. const track = this.captionsTracks[trackName];
  28312. this.Cues.newCue(track, startTime, endTime, screen);
  28313. } else {
  28314. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  28315. this.hls.trigger(Events.CUES_PARSED, {
  28316. type: 'captions',
  28317. cues,
  28318. track: trackName
  28319. });
  28320. }
  28321. }
  28322. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  28323. onInitPtsFound(event, {
  28324. frag,
  28325. id,
  28326. initPTS,
  28327. timescale
  28328. }) {
  28329. const {
  28330. unparsedVttFrags
  28331. } = this;
  28332. if (id === PlaylistLevelType.MAIN) {
  28333. this.initPTS[frag.cc] = {
  28334. baseTime: initPTS,
  28335. timescale
  28336. };
  28337. }
  28338. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  28339. // Parse any unparsed fragments upon receiving the initial PTS.
  28340. if (unparsedVttFrags.length) {
  28341. this.unparsedVttFrags = [];
  28342. unparsedVttFrags.forEach(data => {
  28343. if (this.initPTS[data.frag.cc]) {
  28344. this.onFragLoaded(Events.FRAG_LOADED, data);
  28345. } else {
  28346. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28347. success: false,
  28348. frag: data.frag,
  28349. error: new Error('Subtitle discontinuity domain does not match main')
  28350. });
  28351. }
  28352. });
  28353. }
  28354. }
  28355. getExistingTrack(label, language) {
  28356. const {
  28357. media
  28358. } = this;
  28359. if (media) {
  28360. for (let i = 0; i < media.textTracks.length; i++) {
  28361. const textTrack = media.textTracks[i];
  28362. if (canReuseVttTextTrack(textTrack, {
  28363. name: label,
  28364. lang: language,
  28365. characteristics: 'transcribes-spoken-dialog,describes-music-and-sound'})) {
  28366. return textTrack;
  28367. }
  28368. }
  28369. }
  28370. return null;
  28371. }
  28372. createCaptionsTrack(trackName) {
  28373. if (this.config.renderTextTracksNatively) {
  28374. this.createNativeTrack(trackName);
  28375. } else {
  28376. this.createNonNativeTrack(trackName);
  28377. }
  28378. }
  28379. createNativeTrack(trackName) {
  28380. if (this.captionsTracks[trackName]) {
  28381. return;
  28382. }
  28383. const {
  28384. captionsProperties,
  28385. captionsTracks,
  28386. media
  28387. } = this;
  28388. const {
  28389. label,
  28390. languageCode
  28391. } = captionsProperties[trackName];
  28392. // Enable reuse of existing text track.
  28393. const existingTrack = this.getExistingTrack(label, languageCode);
  28394. if (!existingTrack) {
  28395. const textTrack = this.createTextTrack('captions', label, languageCode);
  28396. if (textTrack) {
  28397. // Set a special property on the track so we know it's managed by Hls.js
  28398. textTrack[trackName] = true;
  28399. captionsTracks[trackName] = textTrack;
  28400. }
  28401. } else {
  28402. captionsTracks[trackName] = existingTrack;
  28403. clearCurrentCues(captionsTracks[trackName]);
  28404. sendAddTrackEvent(captionsTracks[trackName], media);
  28405. }
  28406. }
  28407. createNonNativeTrack(trackName) {
  28408. if (this.nonNativeCaptionsTracks[trackName]) {
  28409. return;
  28410. }
  28411. // Create a list of a single track for the provider to consume
  28412. const trackProperties = this.captionsProperties[trackName];
  28413. if (!trackProperties) {
  28414. return;
  28415. }
  28416. const label = trackProperties.label;
  28417. const track = {
  28418. _id: trackName,
  28419. label,
  28420. kind: 'captions',
  28421. default: trackProperties.media ? !!trackProperties.media.default : false,
  28422. closedCaptions: trackProperties.media
  28423. };
  28424. this.nonNativeCaptionsTracks[trackName] = track;
  28425. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  28426. tracks: [track]
  28427. });
  28428. }
  28429. createTextTrack(kind, label, lang) {
  28430. const media = this.media;
  28431. if (!media) {
  28432. return;
  28433. }
  28434. return media.addTextTrack(kind, label, lang);
  28435. }
  28436. onMediaAttaching(event, data) {
  28437. this.media = data.media;
  28438. if (!data.mediaSource) {
  28439. this._cleanTracks();
  28440. }
  28441. }
  28442. onMediaDetaching(event, data) {
  28443. const transferringMedia = !!data.transferMedia;
  28444. this.media = null;
  28445. if (transferringMedia) {
  28446. return;
  28447. }
  28448. const {
  28449. captionsTracks
  28450. } = this;
  28451. Object.keys(captionsTracks).forEach(trackName => {
  28452. clearCurrentCues(captionsTracks[trackName]);
  28453. delete captionsTracks[trackName];
  28454. });
  28455. this.nonNativeCaptionsTracks = {};
  28456. }
  28457. onManifestLoading() {
  28458. // Detect discontinuity in video fragment (CEA-608) parsing
  28459. this.lastCc = -1;
  28460. this.lastSn = -1;
  28461. this.lastPartIndex = -1;
  28462. // Detect discontinuity in subtitle manifests
  28463. this.prevCC = -1;
  28464. this.vttCCs = newVTTCCs();
  28465. // Reset tracks
  28466. this._cleanTracks();
  28467. this.tracks = [];
  28468. this.captionsTracks = {};
  28469. this.nonNativeCaptionsTracks = {};
  28470. this.textTracks = [];
  28471. this.unparsedVttFrags = [];
  28472. this.initPTS = [];
  28473. if (this.cea608Parser1 && this.cea608Parser2) {
  28474. this.cea608Parser1.reset();
  28475. this.cea608Parser2.reset();
  28476. }
  28477. }
  28478. _cleanTracks() {
  28479. // clear outdated subtitles
  28480. const {
  28481. media
  28482. } = this;
  28483. if (!media) {
  28484. return;
  28485. }
  28486. const textTracks = media.textTracks;
  28487. if (textTracks) {
  28488. for (let i = 0; i < textTracks.length; i++) {
  28489. clearCurrentCues(textTracks[i]);
  28490. }
  28491. }
  28492. }
  28493. onSubtitleTracksUpdated(event, data) {
  28494. const tracks = data.subtitleTracks || [];
  28495. const hasIMSC1 = tracks.some(track => track.textCodec === IMSC1_CODEC);
  28496. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  28497. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  28498. if (listIsIdentical) {
  28499. this.tracks = tracks;
  28500. return;
  28501. }
  28502. this.textTracks = [];
  28503. this.tracks = tracks;
  28504. if (this.config.renderTextTracksNatively) {
  28505. const media = this.media;
  28506. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  28507. this.tracks.forEach((track, index) => {
  28508. // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks
  28509. let textTrack;
  28510. if (inUseTracks) {
  28511. let inUseTrack = null;
  28512. for (let i = 0; i < inUseTracks.length; i++) {
  28513. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  28514. inUseTrack = inUseTracks[i];
  28515. inUseTracks[i] = null;
  28516. break;
  28517. }
  28518. }
  28519. if (inUseTrack) {
  28520. textTrack = inUseTrack;
  28521. }
  28522. }
  28523. if (textTrack) {
  28524. clearCurrentCues(textTrack);
  28525. } else {
  28526. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  28527. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  28528. if (textTrack) {
  28529. textTrack.mode = 'disabled';
  28530. }
  28531. }
  28532. if (textTrack) {
  28533. this.textTracks.push(textTrack);
  28534. }
  28535. });
  28536. // Warn when video element has captions or subtitle TextTracks carried over from another source
  28537. if (inUseTracks != null && inUseTracks.length) {
  28538. const unusedTextTracks = inUseTracks.filter(t => t !== null).map(t => t.label);
  28539. if (unusedTextTracks.length) {
  28540. this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(', ')}. Replace media element for each source to clear TextTracks and captions menu.`);
  28541. }
  28542. }
  28543. } else if (this.tracks.length) {
  28544. // Create a list of tracks for the provider to consume
  28545. const tracksList = this.tracks.map(track => {
  28546. return {
  28547. label: track.name,
  28548. kind: track.type.toLowerCase(),
  28549. default: track.default,
  28550. subtitleTrack: track
  28551. };
  28552. });
  28553. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  28554. tracks: tracksList
  28555. });
  28556. }
  28557. }
  28558. }
  28559. onManifestLoaded(event, data) {
  28560. if (this.config.enableCEA708Captions && data.captions) {
  28561. data.captions.forEach(captionsTrack => {
  28562. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  28563. if (!instreamIdMatch) {
  28564. return;
  28565. }
  28566. const trackName = `textTrack${instreamIdMatch[1]}`;
  28567. const trackProperties = this.captionsProperties[trackName];
  28568. if (!trackProperties) {
  28569. return;
  28570. }
  28571. trackProperties.label = captionsTrack.name;
  28572. if (captionsTrack.lang) {
  28573. // optional attribute
  28574. trackProperties.languageCode = captionsTrack.lang;
  28575. }
  28576. trackProperties.media = captionsTrack;
  28577. });
  28578. }
  28579. }
  28580. closedCaptionsForLevel(frag) {
  28581. const level = this.hls.levels[frag.level];
  28582. return level == null ? void 0 : level.attrs['CLOSED-CAPTIONS'];
  28583. }
  28584. onFragLoading(event, data) {
  28585. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  28586. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  28587. var _data$part$index, _data$part;
  28588. const {
  28589. cea608Parser1,
  28590. cea608Parser2,
  28591. lastSn
  28592. } = this;
  28593. const {
  28594. cc,
  28595. sn
  28596. } = data.frag;
  28597. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  28598. if (cea608Parser1 && cea608Parser2) {
  28599. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  28600. cea608Parser1.reset();
  28601. cea608Parser2.reset();
  28602. }
  28603. }
  28604. this.lastCc = cc;
  28605. this.lastSn = sn;
  28606. this.lastPartIndex = partIndex;
  28607. }
  28608. }
  28609. onFragLoaded(event, data) {
  28610. const {
  28611. frag,
  28612. payload
  28613. } = data;
  28614. if (frag.type === PlaylistLevelType.SUBTITLE) {
  28615. // If fragment is subtitle type, parse as WebVTT.
  28616. if (payload.byteLength) {
  28617. const decryptData = frag.decryptdata;
  28618. // fragment after decryption has a stats object
  28619. const decrypted = 'stats' in data;
  28620. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  28621. if (decryptData == null || !decryptData.encrypted || decrypted) {
  28622. const trackPlaylistMedia = this.tracks[frag.level];
  28623. const vttCCs = this.vttCCs;
  28624. if (!vttCCs[frag.cc]) {
  28625. vttCCs[frag.cc] = {
  28626. start: frag.start,
  28627. prevCC: this.prevCC,
  28628. new: true
  28629. };
  28630. this.prevCC = frag.cc;
  28631. }
  28632. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  28633. this._parseIMSC1(frag, payload);
  28634. } else {
  28635. this._parseVTTs(data);
  28636. }
  28637. }
  28638. } else {
  28639. // In case there is no payload, finish unsuccessfully.
  28640. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28641. success: false,
  28642. frag,
  28643. error: new Error('Empty subtitle payload')
  28644. });
  28645. }
  28646. }
  28647. }
  28648. _parseIMSC1(frag, payload) {
  28649. const hls = this.hls;
  28650. parseIMSC1(payload, this.initPTS[frag.cc], cues => {
  28651. this._appendCues(cues, frag.level);
  28652. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28653. success: true,
  28654. frag: frag
  28655. });
  28656. }, error => {
  28657. hls.logger.log(`Failed to parse IMSC1: ${error}`);
  28658. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28659. success: false,
  28660. frag: frag,
  28661. error
  28662. });
  28663. });
  28664. }
  28665. _parseVTTs(data) {
  28666. var _frag$initSegment;
  28667. const {
  28668. frag,
  28669. payload
  28670. } = data;
  28671. // We need an initial synchronisation PTS. Store fragments as long as none has arrived
  28672. const {
  28673. initPTS,
  28674. unparsedVttFrags
  28675. } = this;
  28676. const maxAvCC = initPTS.length - 1;
  28677. if (!initPTS[frag.cc] && maxAvCC === -1) {
  28678. unparsedVttFrags.push(data);
  28679. return;
  28680. }
  28681. const hls = this.hls;
  28682. // Parse the WebVTT file contents.
  28683. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  28684. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, cues => {
  28685. this._appendCues(cues, frag.level);
  28686. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28687. success: true,
  28688. frag: frag
  28689. });
  28690. }, error => {
  28691. const missingInitPTS = error.message === 'Missing initPTS for VTT MPEGTS';
  28692. if (missingInitPTS) {
  28693. unparsedVttFrags.push(data);
  28694. } else {
  28695. this._fallbackToIMSC1(frag, payload);
  28696. }
  28697. // Something went wrong while parsing. Trigger event with success false.
  28698. hls.logger.log(`Failed to parse VTT cue: ${error}`);
  28699. if (missingInitPTS && maxAvCC > frag.cc) {
  28700. return;
  28701. }
  28702. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  28703. success: false,
  28704. frag: frag,
  28705. error
  28706. });
  28707. });
  28708. }
  28709. _fallbackToIMSC1(frag, payload) {
  28710. // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
  28711. const trackPlaylistMedia = this.tracks[frag.level];
  28712. if (!trackPlaylistMedia.textCodec) {
  28713. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  28714. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  28715. this._parseIMSC1(frag, payload);
  28716. }, () => {
  28717. trackPlaylistMedia.textCodec = 'wvtt';
  28718. });
  28719. }
  28720. }
  28721. _appendCues(cues, fragLevel) {
  28722. const hls = this.hls;
  28723. if (this.config.renderTextTracksNatively) {
  28724. const textTrack = this.textTracks[fragLevel];
  28725. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  28726. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  28727. // and trying to access getCueById method of cues will throw an exception
  28728. // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
  28729. if (!textTrack || textTrack.mode === 'disabled') {
  28730. return;
  28731. }
  28732. cues.forEach(cue => addCueToTrack(textTrack, cue));
  28733. } else {
  28734. const currentTrack = this.tracks[fragLevel];
  28735. if (!currentTrack) {
  28736. return;
  28737. }
  28738. const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
  28739. hls.trigger(Events.CUES_PARSED, {
  28740. type: 'subtitles',
  28741. cues,
  28742. track
  28743. });
  28744. }
  28745. }
  28746. onFragDecrypted(event, data) {
  28747. const {
  28748. frag
  28749. } = data;
  28750. if (frag.type === PlaylistLevelType.SUBTITLE) {
  28751. this.onFragLoaded(Events.FRAG_LOADED, data);
  28752. }
  28753. }
  28754. onSubtitleTracksCleared() {
  28755. this.tracks = [];
  28756. this.captionsTracks = {};
  28757. }
  28758. onFragParsingUserdata(event, data) {
  28759. if (!this.enabled || !this.config.enableCEA708Captions) {
  28760. return;
  28761. }
  28762. const {
  28763. frag,
  28764. samples
  28765. } = data;
  28766. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === 'NONE') {
  28767. return;
  28768. }
  28769. // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  28770. // It will create the proper timestamps based on the PTS value
  28771. for (let i = 0; i < samples.length; i++) {
  28772. const ccBytes = samples[i].bytes;
  28773. if (ccBytes) {
  28774. if (!this.cea608Parser1) {
  28775. this.initCea608Parsers();
  28776. }
  28777. const ccdatas = this.extractCea608Data(ccBytes);
  28778. this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  28779. this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  28780. }
  28781. }
  28782. }
  28783. onBufferFlushing(event, {
  28784. startOffset,
  28785. endOffset,
  28786. endOffsetSubtitles,
  28787. type
  28788. }) {
  28789. const {
  28790. media
  28791. } = this;
  28792. if (!media || media.currentTime < endOffset) {
  28793. return;
  28794. }
  28795. // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
  28796. // Forward cues are never removed because we can loose streamed 608 content from recent fragments
  28797. if (!type || type === 'video') {
  28798. const {
  28799. captionsTracks
  28800. } = this;
  28801. Object.keys(captionsTracks).forEach(trackName => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  28802. }
  28803. if (this.config.renderTextTracksNatively) {
  28804. // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
  28805. if (startOffset === 0 && endOffsetSubtitles !== undefined) {
  28806. const {
  28807. textTracks
  28808. } = this;
  28809. Object.keys(textTracks).forEach(trackName => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  28810. }
  28811. }
  28812. }
  28813. extractCea608Data(byteArray) {
  28814. const actualCCBytes = [[], []];
  28815. const count = byteArray[0] & 0x1f;
  28816. let position = 2;
  28817. for (let j = 0; j < count; j++) {
  28818. const tmpByte = byteArray[position++];
  28819. const ccbyte1 = 0x7f & byteArray[position++];
  28820. const ccbyte2 = 0x7f & byteArray[position++];
  28821. if (ccbyte1 === 0 && ccbyte2 === 0) {
  28822. continue;
  28823. }
  28824. const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels
  28825. if (ccValid) {
  28826. const ccType = 0x03 & tmpByte;
  28827. if (0x00 /* CEA608 field1*/ === ccType || 0x01 /* CEA608 field2*/ === ccType) {
  28828. // Exclude CEA708 CC data.
  28829. actualCCBytes[ccType].push(ccbyte1);
  28830. actualCCBytes[ccType].push(ccbyte2);
  28831. }
  28832. }
  28833. }
  28834. return actualCCBytes;
  28835. }
  28836. }
  28837. function captionsOrSubtitlesFromCharacteristics(track) {
  28838. if (track.characteristics) {
  28839. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  28840. return 'captions';
  28841. }
  28842. }
  28843. return 'subtitles';
  28844. }
  28845. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  28846. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  28847. }
  28848. function intersection(x1, x2, y1, y2) {
  28849. return Math.min(x2, y2) - Math.max(x1, y1);
  28850. }
  28851. function newVTTCCs() {
  28852. return {
  28853. ccOffset: 0,
  28854. presentationOffset: 0,
  28855. 0: {
  28856. start: 0,
  28857. prevCC: -1,
  28858. new: true
  28859. }
  28860. };
  28861. }
  28862. const WHITESPACE_CHAR = /\s/;
  28863. const Cues = {
  28864. newCue(track, startTime, endTime, captionScreen) {
  28865. const result = [];
  28866. let row;
  28867. // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
  28868. let cue;
  28869. let indenting;
  28870. let indent;
  28871. let text;
  28872. const Cue = self.VTTCue || self.TextTrackCue;
  28873. for (let r = 0; r < captionScreen.rows.length; r++) {
  28874. row = captionScreen.rows[r];
  28875. indenting = true;
  28876. indent = 0;
  28877. text = '';
  28878. if (!row.isEmpty()) {
  28879. var _track$cues;
  28880. for (let c = 0; c < row.chars.length; c++) {
  28881. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  28882. indent++;
  28883. } else {
  28884. text += row.chars[c].uchar;
  28885. indenting = false;
  28886. }
  28887. }
  28888. // To be used for cleaning-up orphaned roll-up captions
  28889. row.cueStartTime = startTime;
  28890. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  28891. if (startTime === endTime) {
  28892. endTime += 0.0001;
  28893. }
  28894. if (indent >= 16) {
  28895. indent--;
  28896. } else {
  28897. indent++;
  28898. }
  28899. const cueText = fixLineBreaks(text.trim());
  28900. const id = generateCueId(startTime, endTime, cueText);
  28901. // If this cue already exists in the track do not push it
  28902. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  28903. cue = new Cue(startTime, endTime, cueText);
  28904. cue.id = id;
  28905. cue.line = r + 1;
  28906. cue.align = 'left';
  28907. // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
  28908. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  28909. // Firefox throws an exception and captions break with out of bounds 0-100 values
  28910. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  28911. result.push(cue);
  28912. }
  28913. }
  28914. }
  28915. if (track && result.length) {
  28916. // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
  28917. result.sort((cueA, cueB) => {
  28918. if (cueA.line === 'auto' || cueB.line === 'auto') {
  28919. return 0;
  28920. }
  28921. if (cueA.line > 8 && cueB.line > 8) {
  28922. return cueB.line - cueA.line;
  28923. }
  28924. return cueA.line - cueB.line;
  28925. });
  28926. result.forEach(cue => addCueToTrack(track, cue));
  28927. }
  28928. return result;
  28929. }
  28930. };
  28931. function fetchSupported() {
  28932. if (
  28933. // @ts-ignore
  28934. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  28935. try {
  28936. new self.ReadableStream({}); // eslint-disable-line no-new
  28937. return true;
  28938. } catch (e) {
  28939. /* noop */
  28940. }
  28941. }
  28942. return false;
  28943. }
  28944. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  28945. class FetchLoader {
  28946. constructor(config) {
  28947. this.fetchSetup = void 0;
  28948. this.requestTimeout = void 0;
  28949. this.request = null;
  28950. this.response = null;
  28951. this.controller = void 0;
  28952. this.context = null;
  28953. this.config = null;
  28954. this.callbacks = null;
  28955. this.stats = void 0;
  28956. this.loader = null;
  28957. this.fetchSetup = config.fetchSetup || getRequest;
  28958. this.controller = new self.AbortController();
  28959. this.stats = new LoadStats();
  28960. }
  28961. destroy() {
  28962. this.loader = this.callbacks = this.context = this.config = this.request = null;
  28963. this.abortInternal();
  28964. this.response = null;
  28965. // @ts-ignore
  28966. this.fetchSetup = this.controller = this.stats = null;
  28967. }
  28968. abortInternal() {
  28969. if (this.controller && !this.stats.loading.end) {
  28970. this.stats.aborted = true;
  28971. this.controller.abort();
  28972. }
  28973. }
  28974. abort() {
  28975. var _this$callbacks;
  28976. this.abortInternal();
  28977. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  28978. this.callbacks.onAbort(this.stats, this.context, this.response);
  28979. }
  28980. }
  28981. load(context, config, callbacks) {
  28982. const stats = this.stats;
  28983. if (stats.loading.start) {
  28984. throw new Error('Loader can only be used once.');
  28985. }
  28986. stats.loading.start = self.performance.now();
  28987. const initParams = getRequestParameters(context, this.controller.signal);
  28988. const isArrayBuffer = context.responseType === 'arraybuffer';
  28989. const LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  28990. const {
  28991. maxTimeToFirstByteMs,
  28992. maxLoadTimeMs
  28993. } = config.loadPolicy;
  28994. this.context = context;
  28995. this.config = config;
  28996. this.callbacks = callbacks;
  28997. this.request = this.fetchSetup(context, initParams);
  28998. self.clearTimeout(this.requestTimeout);
  28999. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  29000. this.requestTimeout = self.setTimeout(() => {
  29001. if (this.callbacks) {
  29002. this.abortInternal();
  29003. this.callbacks.onTimeout(stats, context, this.response);
  29004. }
  29005. }, config.timeout);
  29006. const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  29007. fetchPromise.then(response => {
  29008. var _this$callbacks2;
  29009. this.response = this.loader = response;
  29010. const first = Math.max(self.performance.now(), stats.loading.start);
  29011. self.clearTimeout(this.requestTimeout);
  29012. config.timeout = maxLoadTimeMs;
  29013. this.requestTimeout = self.setTimeout(() => {
  29014. if (this.callbacks) {
  29015. this.abortInternal();
  29016. this.callbacks.onTimeout(stats, context, this.response);
  29017. }
  29018. }, maxLoadTimeMs - (first - stats.loading.start));
  29019. if (!response.ok) {
  29020. const {
  29021. status,
  29022. statusText
  29023. } = response;
  29024. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  29025. }
  29026. stats.loading.first = first;
  29027. stats.total = getContentLength(response.headers) || stats.total;
  29028. const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  29029. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  29030. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  29031. }
  29032. if (isArrayBuffer) {
  29033. return response.arrayBuffer();
  29034. }
  29035. if (context.responseType === 'json') {
  29036. return response.json();
  29037. }
  29038. return response.text();
  29039. }).then(responseData => {
  29040. var _this$callbacks3, _this$callbacks4;
  29041. const response = this.response;
  29042. if (!response) {
  29043. throw new Error('loader destroyed');
  29044. }
  29045. self.clearTimeout(this.requestTimeout);
  29046. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  29047. const total = responseData[LENGTH];
  29048. if (total) {
  29049. stats.loaded = stats.total = total;
  29050. }
  29051. const loaderResponse = {
  29052. url: response.url,
  29053. data: responseData,
  29054. code: response.status
  29055. };
  29056. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  29057. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  29058. onProgress(stats, context, responseData, response);
  29059. }
  29060. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  29061. }).catch(error => {
  29062. var _this$callbacks5;
  29063. self.clearTimeout(this.requestTimeout);
  29064. if (stats.aborted) {
  29065. return;
  29066. }
  29067. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  29068. // when destroying, 'error' itself can be undefined
  29069. const code = !error ? 0 : error.code || 0;
  29070. const text = !error ? null : error.message;
  29071. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  29072. code,
  29073. text
  29074. }, context, error ? error.details : null, stats);
  29075. });
  29076. }
  29077. getCacheAge() {
  29078. let result = null;
  29079. if (this.response) {
  29080. const ageHeader = this.response.headers.get('age');
  29081. result = ageHeader ? parseFloat(ageHeader) : null;
  29082. }
  29083. return result;
  29084. }
  29085. getResponseHeader(name) {
  29086. return this.response ? this.response.headers.get(name) : null;
  29087. }
  29088. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  29089. const chunkCache = new ChunkCache();
  29090. const reader = response.body.getReader();
  29091. const pump = () => {
  29092. return reader.read().then(data => {
  29093. if (data.done) {
  29094. if (chunkCache.dataLength) {
  29095. onProgress(stats, context, chunkCache.flush().buffer, response);
  29096. }
  29097. return Promise.resolve(new ArrayBuffer(0));
  29098. }
  29099. const chunk = data.value;
  29100. const len = chunk.length;
  29101. stats.loaded += len;
  29102. if (len < highWaterMark || chunkCache.dataLength) {
  29103. // The current chunk is too small to to be emitted or the cache already has data
  29104. // Push it to the cache
  29105. chunkCache.push(chunk);
  29106. if (chunkCache.dataLength >= highWaterMark) {
  29107. // flush in order to join the typed arrays
  29108. onProgress(stats, context, chunkCache.flush().buffer, response);
  29109. }
  29110. } else {
  29111. // If there's nothing cached already, and the chache is large enough
  29112. // just emit the progress event
  29113. onProgress(stats, context, chunk.buffer, response);
  29114. }
  29115. return pump();
  29116. }).catch(() => {
  29117. /* aborted */
  29118. return Promise.reject();
  29119. });
  29120. };
  29121. return pump();
  29122. }
  29123. }
  29124. function getRequestParameters(context, signal) {
  29125. const initParams = {
  29126. method: 'GET',
  29127. mode: 'cors',
  29128. credentials: 'same-origin',
  29129. signal,
  29130. headers: new self.Headers(_extends({}, context.headers))
  29131. };
  29132. if (context.rangeEnd) {
  29133. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  29134. }
  29135. return initParams;
  29136. }
  29137. function getByteRangeLength(byteRangeHeader) {
  29138. const result = BYTERANGE.exec(byteRangeHeader);
  29139. if (result) {
  29140. return parseInt(result[2]) - parseInt(result[1]) + 1;
  29141. }
  29142. }
  29143. function getContentLength(headers) {
  29144. const contentRange = headers.get('Content-Range');
  29145. if (contentRange) {
  29146. const byteRangeLength = getByteRangeLength(contentRange);
  29147. if (isFiniteNumber(byteRangeLength)) {
  29148. return byteRangeLength;
  29149. }
  29150. }
  29151. const contentLength = headers.get('Content-Length');
  29152. if (contentLength) {
  29153. return parseInt(contentLength);
  29154. }
  29155. }
  29156. function getRequest(context, initParams) {
  29157. return new self.Request(context.url, initParams);
  29158. }
  29159. class FetchError extends Error {
  29160. constructor(message, code, details) {
  29161. super(message);
  29162. this.code = void 0;
  29163. this.details = void 0;
  29164. this.code = code;
  29165. this.details = details;
  29166. }
  29167. }
  29168. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  29169. class XhrLoader {
  29170. constructor(config) {
  29171. this.xhrSetup = void 0;
  29172. this.requestTimeout = void 0;
  29173. this.retryTimeout = void 0;
  29174. this.retryDelay = void 0;
  29175. this.config = null;
  29176. this.callbacks = null;
  29177. this.context = null;
  29178. this.loader = null;
  29179. this.stats = void 0;
  29180. this.xhrSetup = config ? config.xhrSetup || null : null;
  29181. this.stats = new LoadStats();
  29182. this.retryDelay = 0;
  29183. }
  29184. destroy() {
  29185. this.callbacks = null;
  29186. this.abortInternal();
  29187. this.loader = null;
  29188. this.config = null;
  29189. this.context = null;
  29190. this.xhrSetup = null;
  29191. }
  29192. abortInternal() {
  29193. const loader = this.loader;
  29194. self.clearTimeout(this.requestTimeout);
  29195. self.clearTimeout(this.retryTimeout);
  29196. if (loader) {
  29197. loader.onreadystatechange = null;
  29198. loader.onprogress = null;
  29199. if (loader.readyState !== 4) {
  29200. this.stats.aborted = true;
  29201. loader.abort();
  29202. }
  29203. }
  29204. }
  29205. abort() {
  29206. var _this$callbacks;
  29207. this.abortInternal();
  29208. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  29209. this.callbacks.onAbort(this.stats, this.context, this.loader);
  29210. }
  29211. }
  29212. load(context, config, callbacks) {
  29213. if (this.stats.loading.start) {
  29214. throw new Error('Loader can only be used once.');
  29215. }
  29216. this.stats.loading.start = self.performance.now();
  29217. this.context = context;
  29218. this.config = config;
  29219. this.callbacks = callbacks;
  29220. this.loadInternal();
  29221. }
  29222. loadInternal() {
  29223. const {
  29224. config,
  29225. context
  29226. } = this;
  29227. if (!config || !context) {
  29228. return;
  29229. }
  29230. const xhr = this.loader = new self.XMLHttpRequest();
  29231. const stats = this.stats;
  29232. stats.loading.first = 0;
  29233. stats.loaded = 0;
  29234. stats.aborted = false;
  29235. const xhrSetup = this.xhrSetup;
  29236. if (xhrSetup) {
  29237. Promise.resolve().then(() => {
  29238. if (this.loader !== xhr || this.stats.aborted) return;
  29239. return xhrSetup(xhr, context.url);
  29240. }).catch(error => {
  29241. if (this.loader !== xhr || this.stats.aborted) return;
  29242. xhr.open('GET', context.url, true);
  29243. return xhrSetup(xhr, context.url);
  29244. }).then(() => {
  29245. if (this.loader !== xhr || this.stats.aborted) return;
  29246. this.openAndSendXhr(xhr, context, config);
  29247. }).catch(error => {
  29248. var _this$callbacks2;
  29249. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  29250. (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  29251. code: xhr.status,
  29252. text: error.message
  29253. }, context, xhr, stats);
  29254. return;
  29255. });
  29256. } else {
  29257. this.openAndSendXhr(xhr, context, config);
  29258. }
  29259. }
  29260. openAndSendXhr(xhr, context, config) {
  29261. if (!xhr.readyState) {
  29262. xhr.open('GET', context.url, true);
  29263. }
  29264. const headers = context.headers;
  29265. const {
  29266. maxTimeToFirstByteMs,
  29267. maxLoadTimeMs
  29268. } = config.loadPolicy;
  29269. if (headers) {
  29270. for (const header in headers) {
  29271. xhr.setRequestHeader(header, headers[header]);
  29272. }
  29273. }
  29274. if (context.rangeEnd) {
  29275. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  29276. }
  29277. xhr.onreadystatechange = this.readystatechange.bind(this);
  29278. xhr.onprogress = this.loadprogress.bind(this);
  29279. xhr.responseType = context.responseType;
  29280. // setup timeout before we perform request
  29281. self.clearTimeout(this.requestTimeout);
  29282. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  29283. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  29284. xhr.send();
  29285. }
  29286. readystatechange() {
  29287. const {
  29288. context,
  29289. loader: xhr,
  29290. stats
  29291. } = this;
  29292. if (!context || !xhr) {
  29293. return;
  29294. }
  29295. const readyState = xhr.readyState;
  29296. const config = this.config;
  29297. // don't proceed if xhr has been aborted
  29298. if (stats.aborted) {
  29299. return;
  29300. }
  29301. // >= HEADERS_RECEIVED
  29302. if (readyState >= 2) {
  29303. if (stats.loading.first === 0) {
  29304. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  29305. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  29306. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  29307. self.clearTimeout(this.requestTimeout);
  29308. config.timeout = config.loadPolicy.maxLoadTimeMs;
  29309. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  29310. }
  29311. }
  29312. if (readyState === 4) {
  29313. self.clearTimeout(this.requestTimeout);
  29314. xhr.onreadystatechange = null;
  29315. xhr.onprogress = null;
  29316. const status = xhr.status;
  29317. // http status between 200 to 299 are all successful
  29318. const useResponseText = xhr.responseType === 'text' ? xhr.responseText : null;
  29319. if (status >= 200 && status < 300) {
  29320. const data = useResponseText != null ? useResponseText : xhr.response;
  29321. if (data != null) {
  29322. var _this$callbacks3, _this$callbacks4;
  29323. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  29324. const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  29325. stats.loaded = stats.total = len;
  29326. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  29327. const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  29328. if (onProgress) {
  29329. onProgress(stats, context, data, xhr);
  29330. }
  29331. const _response = {
  29332. url: xhr.responseURL,
  29333. data: data,
  29334. code: status
  29335. };
  29336. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  29337. return;
  29338. }
  29339. }
  29340. // Handle bad status or nullish response
  29341. const retryConfig = config.loadPolicy.errorRetry;
  29342. const retryCount = stats.retry;
  29343. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  29344. const response = {
  29345. url: context.url,
  29346. data: undefined,
  29347. code: status
  29348. };
  29349. if (shouldRetry(retryConfig, retryCount, false, response)) {
  29350. this.retry(retryConfig);
  29351. } else {
  29352. var _this$callbacks5;
  29353. logger.error(`${status} while loading ${context.url}`);
  29354. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  29355. code: status,
  29356. text: xhr.statusText
  29357. }, context, xhr, stats);
  29358. }
  29359. }
  29360. }
  29361. }
  29362. loadtimeout() {
  29363. if (!this.config) return;
  29364. const retryConfig = this.config.loadPolicy.timeoutRetry;
  29365. const retryCount = this.stats.retry;
  29366. if (shouldRetry(retryConfig, retryCount, true)) {
  29367. this.retry(retryConfig);
  29368. } else {
  29369. var _this$context;
  29370. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  29371. const callbacks = this.callbacks;
  29372. if (callbacks) {
  29373. this.abortInternal();
  29374. callbacks.onTimeout(this.stats, this.context, this.loader);
  29375. }
  29376. }
  29377. }
  29378. retry(retryConfig) {
  29379. const {
  29380. context,
  29381. stats
  29382. } = this;
  29383. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  29384. stats.retry++;
  29385. logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  29386. // abort and reset internal state
  29387. this.abortInternal();
  29388. this.loader = null;
  29389. // schedule retry
  29390. self.clearTimeout(this.retryTimeout);
  29391. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  29392. }
  29393. loadprogress(event) {
  29394. const stats = this.stats;
  29395. stats.loaded = event.loaded;
  29396. if (event.lengthComputable) {
  29397. stats.total = event.total;
  29398. }
  29399. }
  29400. getCacheAge() {
  29401. let result = null;
  29402. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  29403. const ageHeader = this.loader.getResponseHeader('age');
  29404. result = ageHeader ? parseFloat(ageHeader) : null;
  29405. }
  29406. return result;
  29407. }
  29408. getResponseHeader(name) {
  29409. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {
  29410. return this.loader.getResponseHeader(name);
  29411. }
  29412. return null;
  29413. }
  29414. }
  29415. /**
  29416. * @deprecated use fragLoadPolicy.default
  29417. */
  29418. /**
  29419. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  29420. */
  29421. const defaultLoadPolicy = {
  29422. maxTimeToFirstByteMs: 8000,
  29423. maxLoadTimeMs: 20000,
  29424. timeoutRetry: null,
  29425. errorRetry: null
  29426. };
  29427. /**
  29428. * @ignore
  29429. * If possible, keep hlsDefaultConfig shallow
  29430. * It is cloned whenever a new Hls instance is created, by keeping the config
  29431. * shallow the properties are cloned, and we don't end up manipulating the default
  29432. */
  29433. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  29434. autoStartLoad: true,
  29435. // used by stream-controller
  29436. startPosition: -1,
  29437. // used by stream-controller
  29438. defaultAudioCodec: undefined,
  29439. // used by stream-controller
  29440. debug: false,
  29441. // used by logger
  29442. capLevelOnFPSDrop: false,
  29443. // used by fps-controller
  29444. capLevelToPlayerSize: false,
  29445. // used by cap-level-controller
  29446. ignoreDevicePixelRatio: false,
  29447. // used by cap-level-controller
  29448. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  29449. // used by cap-level-controller
  29450. preferManagedMediaSource: true,
  29451. initialLiveManifestSize: 1,
  29452. // used by stream-controller
  29453. maxBufferLength: 30,
  29454. // used by stream-controller
  29455. backBufferLength: Infinity,
  29456. // used by buffer-controller
  29457. frontBufferFlushThreshold: Infinity,
  29458. startOnSegmentBoundary: false,
  29459. // used by stream-controller
  29460. maxBufferSize: 60 * 1000 * 1000,
  29461. // used by stream-controller
  29462. maxFragLookUpTolerance: 0.25,
  29463. // used by stream-controller
  29464. maxBufferHole: 0.1,
  29465. // used by stream-controller and gap-controller
  29466. detectStallWithCurrentTimeMs: 1250,
  29467. // used by gap-controller
  29468. highBufferWatchdogPeriod: 2,
  29469. // used by gap-controller
  29470. nudgeOffset: 0.1,
  29471. // used by gap-controller
  29472. nudgeMaxRetry: 3,
  29473. // used by gap-controller
  29474. nudgeOnVideoHole: true,
  29475. // used by gap-controller
  29476. liveSyncMode: 'edge',
  29477. // used by stream-controller
  29478. liveSyncDurationCount: 3,
  29479. // used by latency-controller
  29480. liveSyncOnStallIncrease: 1,
  29481. // used by latency-controller
  29482. liveMaxLatencyDurationCount: Infinity,
  29483. // used by latency-controller
  29484. liveSyncDuration: undefined,
  29485. // used by latency-controller
  29486. liveMaxLatencyDuration: undefined,
  29487. // used by latency-controller
  29488. maxLiveSyncPlaybackRate: 1,
  29489. // used by latency-controller
  29490. liveDurationInfinity: false,
  29491. // used by buffer-controller
  29492. /**
  29493. * @deprecated use backBufferLength
  29494. */
  29495. liveBackBufferLength: null,
  29496. // used by buffer-controller
  29497. maxMaxBufferLength: 600,
  29498. // used by stream-controller
  29499. enableWorker: true,
  29500. // used by transmuxer
  29501. workerPath: null,
  29502. // used by transmuxer
  29503. enableSoftwareAES: true,
  29504. // used by decrypter
  29505. startLevel: undefined,
  29506. // used by level-controller
  29507. startFragPrefetch: false,
  29508. // used by stream-controller
  29509. fpsDroppedMonitoringPeriod: 5000,
  29510. // used by fps-controller
  29511. fpsDroppedMonitoringThreshold: 0.2,
  29512. // used by fps-controller
  29513. appendErrorMaxRetry: 3,
  29514. // used by buffer-controller
  29515. ignorePlaylistParsingErrors: false,
  29516. loader: XhrLoader,
  29517. // loader: FetchLoader,
  29518. fLoader: undefined,
  29519. // used by fragment-loader
  29520. pLoader: undefined,
  29521. // used by playlist-loader
  29522. xhrSetup: undefined,
  29523. // used by xhr-loader
  29524. licenseXhrSetup: undefined,
  29525. // used by eme-controller
  29526. licenseResponseCallback: undefined,
  29527. // used by eme-controller
  29528. abrController: AbrController,
  29529. bufferController: BufferController,
  29530. capLevelController: CapLevelController,
  29531. errorController: ErrorController,
  29532. fpsController: FPSController,
  29533. stretchShortVideoTrack: false,
  29534. // used by mp4-remuxer
  29535. maxAudioFramesDrift: 1,
  29536. // used by mp4-remuxer
  29537. forceKeyFrameOnDiscontinuity: true,
  29538. // used by ts-demuxer
  29539. abrEwmaFastLive: 3,
  29540. // used by abr-controller
  29541. abrEwmaSlowLive: 9,
  29542. // used by abr-controller
  29543. abrEwmaFastVoD: 3,
  29544. // used by abr-controller
  29545. abrEwmaSlowVoD: 9,
  29546. // used by abr-controller
  29547. abrEwmaDefaultEstimate: 5e5,
  29548. // 500 kbps // used by abr-controller
  29549. abrEwmaDefaultEstimateMax: 5e6,
  29550. // 5 mbps
  29551. abrBandWidthFactor: 0.95,
  29552. // used by abr-controller
  29553. abrBandWidthUpFactor: 0.7,
  29554. // used by abr-controller
  29555. abrMaxWithRealBitrate: false,
  29556. // used by abr-controller
  29557. maxStarvationDelay: 4,
  29558. // used by abr-controller
  29559. maxLoadingDelay: 4,
  29560. // used by abr-controller
  29561. minAutoBitrate: 0,
  29562. // used by hls
  29563. emeEnabled: false,
  29564. // used by eme-controller
  29565. widevineLicenseUrl: undefined,
  29566. // used by eme-controller
  29567. drmSystems: {},
  29568. // used by eme-controller
  29569. drmSystemOptions: {},
  29570. // used by eme-controller
  29571. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess ,
  29572. // used by eme-controller
  29573. requireKeySystemAccessOnStart: false,
  29574. // used by eme-controller
  29575. testBandwidth: true,
  29576. progressive: false,
  29577. lowLatencyMode: true,
  29578. cmcd: undefined,
  29579. enableDateRangeMetadataCues: true,
  29580. enableEmsgMetadataCues: true,
  29581. enableEmsgKLVMetadata: false,
  29582. enableID3MetadataCues: true,
  29583. enableInterstitialPlayback: true,
  29584. interstitialAppendInPlace: true,
  29585. interstitialLiveLookAhead: 10,
  29586. useMediaCapabilities: true,
  29587. preserveManualLevelOnError: false,
  29588. certLoadPolicy: {
  29589. default: defaultLoadPolicy
  29590. },
  29591. keyLoadPolicy: {
  29592. default: {
  29593. maxTimeToFirstByteMs: 8000,
  29594. maxLoadTimeMs: 20000,
  29595. timeoutRetry: {
  29596. maxNumRetry: 1,
  29597. retryDelayMs: 1000,
  29598. maxRetryDelayMs: 20000,
  29599. backoff: 'linear'
  29600. },
  29601. errorRetry: {
  29602. maxNumRetry: 8,
  29603. retryDelayMs: 1000,
  29604. maxRetryDelayMs: 20000,
  29605. backoff: 'linear'
  29606. }
  29607. }
  29608. },
  29609. manifestLoadPolicy: {
  29610. default: {
  29611. maxTimeToFirstByteMs: Infinity,
  29612. maxLoadTimeMs: 20000,
  29613. timeoutRetry: {
  29614. maxNumRetry: 2,
  29615. retryDelayMs: 0,
  29616. maxRetryDelayMs: 0
  29617. },
  29618. errorRetry: {
  29619. maxNumRetry: 1,
  29620. retryDelayMs: 1000,
  29621. maxRetryDelayMs: 8000
  29622. }
  29623. }
  29624. },
  29625. playlistLoadPolicy: {
  29626. default: {
  29627. maxTimeToFirstByteMs: 10000,
  29628. maxLoadTimeMs: 20000,
  29629. timeoutRetry: {
  29630. maxNumRetry: 2,
  29631. retryDelayMs: 0,
  29632. maxRetryDelayMs: 0
  29633. },
  29634. errorRetry: {
  29635. maxNumRetry: 2,
  29636. retryDelayMs: 1000,
  29637. maxRetryDelayMs: 8000
  29638. }
  29639. }
  29640. },
  29641. fragLoadPolicy: {
  29642. default: {
  29643. maxTimeToFirstByteMs: 10000,
  29644. maxLoadTimeMs: 120000,
  29645. timeoutRetry: {
  29646. maxNumRetry: 4,
  29647. retryDelayMs: 0,
  29648. maxRetryDelayMs: 0
  29649. },
  29650. errorRetry: {
  29651. maxNumRetry: 6,
  29652. retryDelayMs: 1000,
  29653. maxRetryDelayMs: 8000
  29654. }
  29655. }
  29656. },
  29657. steeringManifestLoadPolicy: {
  29658. default: {
  29659. maxTimeToFirstByteMs: 10000,
  29660. maxLoadTimeMs: 20000,
  29661. timeoutRetry: {
  29662. maxNumRetry: 2,
  29663. retryDelayMs: 0,
  29664. maxRetryDelayMs: 0
  29665. },
  29666. errorRetry: {
  29667. maxNumRetry: 1,
  29668. retryDelayMs: 1000,
  29669. maxRetryDelayMs: 8000
  29670. }
  29671. }
  29672. },
  29673. interstitialAssetListLoadPolicy: {
  29674. default: {
  29675. maxTimeToFirstByteMs: 10000,
  29676. maxLoadTimeMs: 30000,
  29677. timeoutRetry: {
  29678. maxNumRetry: 0,
  29679. retryDelayMs: 0,
  29680. maxRetryDelayMs: 0
  29681. },
  29682. errorRetry: {
  29683. maxNumRetry: 0,
  29684. retryDelayMs: 1000,
  29685. maxRetryDelayMs: 8000
  29686. }
  29687. }
  29688. },
  29689. // These default settings are deprecated in favor of the above policies
  29690. // and are maintained for backwards compatibility
  29691. manifestLoadingTimeOut: 10000,
  29692. manifestLoadingMaxRetry: 1,
  29693. manifestLoadingRetryDelay: 1000,
  29694. manifestLoadingMaxRetryTimeout: 64000,
  29695. levelLoadingTimeOut: 10000,
  29696. levelLoadingMaxRetry: 4,
  29697. levelLoadingRetryDelay: 1000,
  29698. levelLoadingMaxRetryTimeout: 64000,
  29699. fragLoadingTimeOut: 20000,
  29700. fragLoadingMaxRetry: 6,
  29701. fragLoadingRetryDelay: 1000,
  29702. fragLoadingMaxRetryTimeout: 64000
  29703. }, timelineConfig()), {}, {
  29704. subtitleStreamController: SubtitleStreamController ,
  29705. subtitleTrackController: SubtitleTrackController ,
  29706. timelineController: TimelineController ,
  29707. audioStreamController: AudioStreamController ,
  29708. audioTrackController: AudioTrackController ,
  29709. emeController: EMEController ,
  29710. cmcdController: CMCDController ,
  29711. contentSteeringController: ContentSteeringController ,
  29712. interstitialsController: InterstitialsController
  29713. });
  29714. function timelineConfig() {
  29715. return {
  29716. cueHandler: Cues,
  29717. // used by timeline-controller
  29718. enableWebVTT: true,
  29719. // used by timeline-controller
  29720. enableIMSC1: true,
  29721. // used by timeline-controller
  29722. enableCEA708Captions: true,
  29723. // used by timeline-controller
  29724. captionsTextTrack1Label: 'English',
  29725. // used by timeline-controller
  29726. captionsTextTrack1LanguageCode: 'en',
  29727. // used by timeline-controller
  29728. captionsTextTrack2Label: 'Spanish',
  29729. // used by timeline-controller
  29730. captionsTextTrack2LanguageCode: 'es',
  29731. // used by timeline-controller
  29732. captionsTextTrack3Label: 'Unknown CC',
  29733. // used by timeline-controller
  29734. captionsTextTrack3LanguageCode: '',
  29735. // used by timeline-controller
  29736. captionsTextTrack4Label: 'Unknown CC',
  29737. // used by timeline-controller
  29738. captionsTextTrack4LanguageCode: '',
  29739. // used by timeline-controller
  29740. renderTextTracksNatively: true
  29741. };
  29742. }
  29743. /**
  29744. * @ignore
  29745. */
  29746. function mergeConfig(defaultConfig, userConfig, logger) {
  29747. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  29748. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  29749. }
  29750. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  29751. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  29752. }
  29753. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  29754. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  29755. }
  29756. const defaultsCopy = deepCpy(defaultConfig);
  29757. // Backwards compatibility with deprecated config values
  29758. const deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  29759. const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  29760. deprecatedSettingTypes.forEach(type => {
  29761. const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;
  29762. const policyNotSet = userConfig[policyName] === undefined;
  29763. const report = [];
  29764. deprecatedSettings.forEach(setting => {
  29765. const deprecatedSetting = `${type}Loading${setting}`;
  29766. const value = userConfig[deprecatedSetting];
  29767. if (value !== undefined && policyNotSet) {
  29768. report.push(deprecatedSetting);
  29769. const settings = defaultsCopy[policyName].default;
  29770. userConfig[policyName] = {
  29771. default: settings
  29772. };
  29773. switch (setting) {
  29774. case 'TimeOut':
  29775. settings.maxLoadTimeMs = value;
  29776. settings.maxTimeToFirstByteMs = value;
  29777. break;
  29778. case 'MaxRetry':
  29779. settings.errorRetry.maxNumRetry = value;
  29780. settings.timeoutRetry.maxNumRetry = value;
  29781. break;
  29782. case 'RetryDelay':
  29783. settings.errorRetry.retryDelayMs = value;
  29784. settings.timeoutRetry.retryDelayMs = value;
  29785. break;
  29786. case 'MaxRetryTimeout':
  29787. settings.errorRetry.maxRetryDelayMs = value;
  29788. settings.timeoutRetry.maxRetryDelayMs = value;
  29789. break;
  29790. }
  29791. }
  29792. });
  29793. if (report.length) {
  29794. logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${stringify(userConfig[policyName])}`);
  29795. }
  29796. });
  29797. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  29798. }
  29799. function deepCpy(obj) {
  29800. if (obj && typeof obj === 'object') {
  29801. if (Array.isArray(obj)) {
  29802. return obj.map(deepCpy);
  29803. }
  29804. return Object.keys(obj).reduce((result, key) => {
  29805. result[key] = deepCpy(obj[key]);
  29806. return result;
  29807. }, {});
  29808. }
  29809. return obj;
  29810. }
  29811. /**
  29812. * @ignore
  29813. */
  29814. function enableStreamingMode(config, logger) {
  29815. const currentLoader = config.loader;
  29816. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  29817. // If a developer has configured their own loader, respect that choice
  29818. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  29819. config.progressive = false;
  29820. } else {
  29821. const canStreamProgressively = fetchSupported();
  29822. if (canStreamProgressively) {
  29823. config.loader = FetchLoader;
  29824. config.progressive = true;
  29825. config.enableSoftwareAES = true;
  29826. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  29827. }
  29828. }
  29829. }
  29830. const MAX_START_GAP_JUMP = 2.0;
  29831. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  29832. const SKIP_BUFFER_RANGE_START = 0.05;
  29833. const TICK_INTERVAL$1 = 100;
  29834. class GapController extends TaskLoop {
  29835. constructor(hls, fragmentTracker) {
  29836. super('gap-controller', hls.logger);
  29837. this.hls = null;
  29838. this.fragmentTracker = null;
  29839. this.media = null;
  29840. this.mediaSource = void 0;
  29841. this.nudgeRetry = 0;
  29842. this.stallReported = false;
  29843. this.stalled = null;
  29844. this.moved = false;
  29845. this.seeking = false;
  29846. this.buffered = {};
  29847. this.lastCurrentTime = 0;
  29848. this.ended = 0;
  29849. this.waiting = 0;
  29850. this.onMediaPlaying = () => {
  29851. this.ended = 0;
  29852. this.waiting = 0;
  29853. };
  29854. this.onMediaWaiting = () => {
  29855. var _this$media;
  29856. if ((_this$media = this.media) != null && _this$media.seeking) {
  29857. return;
  29858. }
  29859. this.waiting = self.performance.now();
  29860. this.tick();
  29861. };
  29862. this.onMediaEnded = () => {
  29863. if (this.hls) {
  29864. var _this$media2;
  29865. // ended is set when triggering MEDIA_ENDED so that we do not trigger it again on stall or on tick with media.ended
  29866. this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  29867. this.hls.trigger(Events.MEDIA_ENDED, {
  29868. stalled: false
  29869. });
  29870. }
  29871. };
  29872. this.hls = hls;
  29873. this.fragmentTracker = fragmentTracker;
  29874. this.registerListeners();
  29875. }
  29876. registerListeners() {
  29877. const {
  29878. hls
  29879. } = this;
  29880. if (hls) {
  29881. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29882. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29883. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  29884. }
  29885. }
  29886. unregisterListeners() {
  29887. const {
  29888. hls
  29889. } = this;
  29890. if (hls) {
  29891. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  29892. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29893. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  29894. }
  29895. }
  29896. destroy() {
  29897. super.destroy();
  29898. this.unregisterListeners();
  29899. this.media = this.hls = this.fragmentTracker = null;
  29900. this.mediaSource = undefined;
  29901. }
  29902. onMediaAttached(event, data) {
  29903. this.setInterval(TICK_INTERVAL$1);
  29904. this.mediaSource = data.mediaSource;
  29905. const media = this.media = data.media;
  29906. addEventListener(media, 'playing', this.onMediaPlaying);
  29907. addEventListener(media, 'waiting', this.onMediaWaiting);
  29908. addEventListener(media, 'ended', this.onMediaEnded);
  29909. }
  29910. onMediaDetaching(event, data) {
  29911. this.clearInterval();
  29912. const {
  29913. media
  29914. } = this;
  29915. if (media) {
  29916. removeEventListener(media, 'playing', this.onMediaPlaying);
  29917. removeEventListener(media, 'waiting', this.onMediaWaiting);
  29918. removeEventListener(media, 'ended', this.onMediaEnded);
  29919. this.media = null;
  29920. }
  29921. this.mediaSource = undefined;
  29922. }
  29923. onBufferAppended(event, data) {
  29924. this.buffered = data.timeRanges;
  29925. }
  29926. get hasBuffered() {
  29927. return Object.keys(this.buffered).length > 0;
  29928. }
  29929. tick() {
  29930. var _this$media3;
  29931. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  29932. return;
  29933. }
  29934. const currentTime = this.media.currentTime;
  29935. this.poll(currentTime, this.lastCurrentTime);
  29936. this.lastCurrentTime = currentTime;
  29937. }
  29938. /**
  29939. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  29940. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  29941. *
  29942. * @param lastCurrentTime - Previously read playhead position
  29943. */
  29944. poll(currentTime, lastCurrentTime) {
  29945. var _this$hls, _this$hls2;
  29946. const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  29947. if (!config) {
  29948. return;
  29949. }
  29950. const media = this.media;
  29951. if (!media) {
  29952. return;
  29953. }
  29954. const {
  29955. seeking
  29956. } = media;
  29957. const seeked = this.seeking && !seeking;
  29958. const beginSeek = !this.seeking && seeking;
  29959. const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  29960. this.seeking = seeking;
  29961. // The playhead is moving, no-op
  29962. if (currentTime !== lastCurrentTime) {
  29963. if (lastCurrentTime) {
  29964. this.ended = 0;
  29965. }
  29966. this.moved = true;
  29967. if (!seeking) {
  29968. this.nudgeRetry = 0;
  29969. // When crossing between buffered video time ranges, but not audio, flush pipeline with seek (Chrome)
  29970. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  29971. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  29972. }
  29973. }
  29974. if (this.waiting === 0) {
  29975. this.stallResolved(currentTime);
  29976. }
  29977. return;
  29978. }
  29979. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  29980. if (beginSeek || seeked) {
  29981. if (seeked) {
  29982. this.stallResolved(currentTime);
  29983. }
  29984. return;
  29985. }
  29986. // The playhead should not be moving
  29987. if (pausedEndedOrHalted) {
  29988. this.nudgeRetry = 0;
  29989. this.stallResolved(currentTime);
  29990. // Fire MEDIA_ENDED to workaround event not being dispatched by browser
  29991. if (!this.ended && media.ended && this.hls) {
  29992. this.ended = currentTime || 1;
  29993. this.hls.trigger(Events.MEDIA_ENDED, {
  29994. stalled: false
  29995. });
  29996. }
  29997. return;
  29998. }
  29999. if (!BufferHelper.getBuffered(media).length) {
  30000. this.nudgeRetry = 0;
  30001. return;
  30002. }
  30003. // Resolve stalls at buffer holes using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  30004. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  30005. const nextStart = bufferInfo.nextStart || 0;
  30006. const fragmentTracker = this.fragmentTracker;
  30007. if (seeking && fragmentTracker && this.hls) {
  30008. // Is there a fragment loading/parsing/appending before currentTime?
  30009. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  30010. // Waiting for seeking in a buffered range to complete
  30011. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  30012. // Next buffered range is too far ahead to jump to while still seeking
  30013. const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  30014. if (hasEnoughBuffer || noBufferHole) {
  30015. return;
  30016. }
  30017. // Reset moved state when seeking to a point in or before a gap/hole
  30018. this.moved = false;
  30019. }
  30020. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  30021. // The addition poll gives the browser a chance to jump the gap for us
  30022. const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  30023. if (!this.moved && this.stalled !== null && fragmentTracker) {
  30024. // There is no playable buffer (seeked, waiting for buffer)
  30025. const isBuffered = bufferInfo.len > 0;
  30026. if (!isBuffered && !nextStart) {
  30027. return;
  30028. }
  30029. // Jump start gaps within jump threshold
  30030. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  30031. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  30032. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  30033. // that begins over 1 target duration after the video start position.
  30034. const isLive = !!(levelDetails != null && levelDetails.live);
  30035. const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  30036. const partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  30037. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  30038. if (!media.paused) {
  30039. this._trySkipBufferHole(partialOrGap);
  30040. }
  30041. return;
  30042. }
  30043. }
  30044. // Start tracking stall time
  30045. const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  30046. const tnow = self.performance.now();
  30047. const tWaiting = this.waiting;
  30048. let stalled = this.stalled;
  30049. if (stalled === null) {
  30050. // Use time of recent "waiting" event
  30051. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  30052. stalled = this.stalled = tWaiting;
  30053. } else {
  30054. this.stalled = tnow;
  30055. return;
  30056. }
  30057. }
  30058. const stalledDuration = tnow - stalled;
  30059. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  30060. var _this$mediaSource;
  30061. // Dispatch MEDIA_ENDED when media.ended/ended event is not signalled at end of stream
  30062. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === 'ended' && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
  30063. if (this.ended) {
  30064. return;
  30065. }
  30066. this.ended = currentTime || 1;
  30067. this.hls.trigger(Events.MEDIA_ENDED, {
  30068. stalled: true
  30069. });
  30070. return;
  30071. }
  30072. // Report stalling after trying to fix
  30073. this._reportStall(bufferInfo);
  30074. if (!this.media || !this.hls) {
  30075. return;
  30076. }
  30077. }
  30078. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  30079. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  30080. }
  30081. stallResolved(currentTime) {
  30082. const stalled = this.stalled;
  30083. if (stalled && this.hls) {
  30084. this.stalled = null;
  30085. // The playhead is now moving, but was previously stalled
  30086. if (this.stallReported) {
  30087. const stalledDuration = self.performance.now() - stalled;
  30088. this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);
  30089. this.stallReported = false;
  30090. this.waiting = 0;
  30091. this.hls.trigger(Events.STALL_RESOLVED, {});
  30092. }
  30093. }
  30094. }
  30095. nudgeOnVideoHole(currentTime, lastCurrentTime) {
  30096. var _this$buffered$audio;
  30097. // Chrome will play one second past a hole in video buffered time ranges without rendering any video from the subsequent range and then stall as long as audio is buffered:
  30098. // https://github.com/video-dev/hls.js/issues/5631
  30099. // https://issues.chromium.org/issues/40280613#comment10
  30100. // Detect the potential for this situation and proactively seek to flush the video pipeline once the playhead passes the start of the video hole.
  30101. // When there are audio and video buffers and currentTime is past the end of the first video buffered range...
  30102. const videoSourceBuffered = this.buffered.video;
  30103. if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
  30104. // and audio is buffered at the playhead
  30105. const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  30106. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  30107. const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  30108. const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  30109. // nudge when crossing into another video buffered range (hole).
  30110. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  30111. const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  30112. const holeStart = videoTimes[lastBufferedIndex].end;
  30113. const holeEnd = videoTimes[lastBufferedIndex + 1].start;
  30114. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 &&
  30115. // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  30116. currentTime - holeStart < 2) {
  30117. const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);
  30118. this.warn(error.message);
  30119. // Magic number to flush the pipeline without interuption to audio playback:
  30120. this.media.currentTime += 0.000001;
  30121. const frag = this.fragmentTracker.getPartialFragment(currentTime) || undefined;
  30122. const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  30123. this.hls.trigger(Events.ERROR, {
  30124. type: ErrorTypes.MEDIA_ERROR,
  30125. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  30126. fatal: false,
  30127. error,
  30128. reason: error.message,
  30129. frag,
  30130. buffer: bufferInfo.len,
  30131. bufferInfo
  30132. });
  30133. }
  30134. }
  30135. }
  30136. }
  30137. }
  30138. /**
  30139. * Detects and attempts to fix known buffer stalling issues.
  30140. * @param bufferInfo - The properties of the current buffer.
  30141. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  30142. * @private
  30143. */
  30144. _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  30145. var _this$hls3, _this$hls4;
  30146. const {
  30147. fragmentTracker,
  30148. media
  30149. } = this;
  30150. const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  30151. if (!media || !fragmentTracker || !config) {
  30152. return;
  30153. }
  30154. const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  30155. const partial = fragmentTracker.getPartialFragment(currentTime);
  30156. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  30157. // Try to skip over the buffer hole caused by a partial fragment
  30158. // This method isn't limited by the size of the gap between buffered ranges
  30159. const targetTime = this._trySkipBufferHole(partial);
  30160. // we return here in this case, meaning
  30161. // the branch below only executes when we haven't seeked to a new position
  30162. if (targetTime || !this.media) {
  30163. return;
  30164. }
  30165. }
  30166. // if we haven't had to skip over a buffer hole of a partial fragment
  30167. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  30168. // needs to cross some sort of threshold covering all source-buffers content
  30169. // to start playing properly.
  30170. const bufferedRanges = bufferInfo.buffered;
  30171. const adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  30172. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1000 || this.waiting)) {
  30173. this.warn('Trying to nudge playhead over buffer-hole');
  30174. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  30175. // We only try to jump the hole if it's under the configured size
  30176. this._tryNudgeBuffer(bufferInfo);
  30177. }
  30178. }
  30179. adjacentTraversal(bufferInfo, currentTime) {
  30180. const fragmentTracker = this.fragmentTracker;
  30181. const nextStart = bufferInfo.nextStart;
  30182. if (fragmentTracker && nextStart) {
  30183. const current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  30184. const next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  30185. if (current && next) {
  30186. return next.sn - current.sn < 2;
  30187. }
  30188. }
  30189. return false;
  30190. }
  30191. /**
  30192. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  30193. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  30194. * @private
  30195. */
  30196. _reportStall(bufferInfo) {
  30197. const {
  30198. hls,
  30199. media,
  30200. stallReported,
  30201. stalled
  30202. } = this;
  30203. if (!stallReported && stalled !== null && media && hls) {
  30204. // Report stalled error once
  30205. this.stallReported = true;
  30206. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);
  30207. this.warn(error.message);
  30208. hls.trigger(Events.ERROR, {
  30209. type: ErrorTypes.MEDIA_ERROR,
  30210. details: ErrorDetails.BUFFER_STALLED_ERROR,
  30211. fatal: false,
  30212. error,
  30213. buffer: bufferInfo.len,
  30214. bufferInfo,
  30215. stalled: {
  30216. start: stalled
  30217. }
  30218. });
  30219. }
  30220. }
  30221. /**
  30222. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  30223. * @param partial - The partial fragment found at the current time (where playback is stalling).
  30224. * @private
  30225. */
  30226. _trySkipBufferHole(partial) {
  30227. var _this$hls5;
  30228. const {
  30229. fragmentTracker,
  30230. media
  30231. } = this;
  30232. const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  30233. if (!media || !fragmentTracker || !config) {
  30234. return 0;
  30235. }
  30236. // Check if currentTime is between unbuffered regions of partial fragments
  30237. const currentTime = media.currentTime;
  30238. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  30239. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  30240. if (startTime && this.hls) {
  30241. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  30242. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  30243. const gapLength = startTime - currentTime;
  30244. if (gapLength > 0 && (bufferStarved || waiting)) {
  30245. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  30246. if (gapLength > config.maxBufferHole) {
  30247. let startGap = false;
  30248. if (currentTime === 0) {
  30249. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  30250. if (startFrag && startTime < startFrag.end) {
  30251. startGap = true;
  30252. }
  30253. }
  30254. if (!startGap) {
  30255. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  30256. if (startProvisioned) {
  30257. var _this$hls$loadLevelOb;
  30258. // Do not seek when selected variant playlist is unloaded
  30259. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  30260. return 0;
  30261. }
  30262. // Do not seek when required fragments are inflight or appending
  30263. const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  30264. if (inFlightDependency) {
  30265. return 0;
  30266. }
  30267. // Do not seek if we can't walk tracked fragments to end of gap
  30268. let moreToLoad = false;
  30269. let pos = startProvisioned.end;
  30270. while (pos < startTime) {
  30271. const provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  30272. if (provisioned) {
  30273. pos += provisioned.duration;
  30274. } else {
  30275. moreToLoad = true;
  30276. break;
  30277. }
  30278. }
  30279. if (moreToLoad) {
  30280. return 0;
  30281. }
  30282. }
  30283. }
  30284. }
  30285. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  30286. this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  30287. this.moved = true;
  30288. media.currentTime = targetTime;
  30289. if (!(partial != null && partial.gap)) {
  30290. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  30291. this.hls.trigger(Events.ERROR, {
  30292. type: ErrorTypes.MEDIA_ERROR,
  30293. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  30294. fatal: false,
  30295. error,
  30296. reason: error.message,
  30297. frag: partial || undefined,
  30298. buffer: bufferInfo.len,
  30299. bufferInfo
  30300. });
  30301. }
  30302. return targetTime;
  30303. }
  30304. }
  30305. return 0;
  30306. }
  30307. /**
  30308. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  30309. * @private
  30310. */
  30311. _tryNudgeBuffer(bufferInfo) {
  30312. const {
  30313. hls,
  30314. media,
  30315. nudgeRetry
  30316. } = this;
  30317. const config = hls == null ? void 0 : hls.config;
  30318. if (!media || !config) {
  30319. return 0;
  30320. }
  30321. const currentTime = media.currentTime;
  30322. this.nudgeRetry++;
  30323. if (nudgeRetry < config.nudgeMaxRetry) {
  30324. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  30325. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  30326. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  30327. this.warn(error.message);
  30328. media.currentTime = targetTime;
  30329. hls.trigger(Events.ERROR, {
  30330. type: ErrorTypes.MEDIA_ERROR,
  30331. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  30332. error,
  30333. fatal: false,
  30334. buffer: bufferInfo.len,
  30335. bufferInfo
  30336. });
  30337. } else {
  30338. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  30339. this.error(error.message);
  30340. hls.trigger(Events.ERROR, {
  30341. type: ErrorTypes.MEDIA_ERROR,
  30342. details: ErrorDetails.BUFFER_STALLED_ERROR,
  30343. error,
  30344. fatal: true,
  30345. buffer: bufferInfo.len,
  30346. bufferInfo
  30347. });
  30348. }
  30349. }
  30350. }
  30351. function getInFlightDependency(inFlightFragments, currentTime) {
  30352. const main = inFlight(inFlightFragments.main);
  30353. if (main && main.start <= currentTime) {
  30354. return main;
  30355. }
  30356. const audio = inFlight(inFlightFragments.audio);
  30357. if (audio && audio.start <= currentTime) {
  30358. return audio;
  30359. }
  30360. return null;
  30361. }
  30362. function inFlight(inFlightData) {
  30363. if (!inFlightData) {
  30364. return null;
  30365. }
  30366. switch (inFlightData.state) {
  30367. case State.IDLE:
  30368. case State.STOPPED:
  30369. case State.ENDED:
  30370. case State.ERROR:
  30371. return null;
  30372. }
  30373. return inFlightData.frag;
  30374. }
  30375. const MIN_CUE_DURATION = 0.25;
  30376. function getCueClass() {
  30377. if (typeof self === 'undefined') return undefined;
  30378. return self.VTTCue || self.TextTrackCue;
  30379. }
  30380. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  30381. let cue = new Cue(startTime, endTime, '');
  30382. try {
  30383. cue.value = data;
  30384. if (type) {
  30385. cue.type = type;
  30386. }
  30387. } catch (e) {
  30388. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  30389. type
  30390. }, data) : data));
  30391. }
  30392. return cue;
  30393. }
  30394. // VTTCue latest draft allows an infinite duration, fallback
  30395. // to MAX_VALUE if necessary
  30396. const MAX_CUE_ENDTIME = (() => {
  30397. const Cue = getCueClass();
  30398. try {
  30399. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  30400. } catch (e) {
  30401. return Number.MAX_VALUE;
  30402. }
  30403. return Number.POSITIVE_INFINITY;
  30404. })();
  30405. class ID3TrackController {
  30406. constructor(hls) {
  30407. this.hls = void 0;
  30408. this.id3Track = null;
  30409. this.media = null;
  30410. this.dateRangeCuesAppended = {};
  30411. this.removeCues = true;
  30412. this.onEventCueEnter = () => {
  30413. if (!this.hls) {
  30414. return;
  30415. }
  30416. this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  30417. };
  30418. this.hls = hls;
  30419. this._registerListeners();
  30420. }
  30421. destroy() {
  30422. this._unregisterListeners();
  30423. this.id3Track = null;
  30424. this.media = null;
  30425. this.dateRangeCuesAppended = {};
  30426. // @ts-ignore
  30427. this.hls = this.onEventCueEnter = null;
  30428. }
  30429. _registerListeners() {
  30430. const {
  30431. hls
  30432. } = this;
  30433. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  30434. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30435. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30436. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30437. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  30438. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  30439. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  30440. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  30441. }
  30442. _unregisterListeners() {
  30443. const {
  30444. hls
  30445. } = this;
  30446. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  30447. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30448. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30449. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30450. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  30451. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  30452. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  30453. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  30454. }
  30455. // Add ID3 metatadata text track.
  30456. onMediaAttaching(event, data) {
  30457. var _data$overrides;
  30458. this.media = data.media;
  30459. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  30460. this.removeCues = false;
  30461. }
  30462. }
  30463. onMediaAttached() {
  30464. const details = this.hls.latestLevelDetails;
  30465. if (details) {
  30466. this.updateDateRangeCues(details);
  30467. }
  30468. }
  30469. onMediaDetaching(event, data) {
  30470. this.media = null;
  30471. const transferringMedia = !!data.transferMedia;
  30472. if (transferringMedia) {
  30473. return;
  30474. }
  30475. if (this.id3Track) {
  30476. if (this.removeCues) {
  30477. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  30478. }
  30479. this.id3Track = null;
  30480. }
  30481. this.dateRangeCuesAppended = {};
  30482. }
  30483. onManifestLoading() {
  30484. this.dateRangeCuesAppended = {};
  30485. }
  30486. createTrack(media) {
  30487. const track = this.getID3Track(media.textTracks);
  30488. track.mode = 'hidden';
  30489. return track;
  30490. }
  30491. getID3Track(textTracks) {
  30492. if (!this.media) {
  30493. return;
  30494. }
  30495. for (let i = 0; i < textTracks.length; i++) {
  30496. const textTrack = textTracks[i];
  30497. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  30498. // send 'addtrack' when reusing the textTrack for metadata,
  30499. // same as what we do for captions
  30500. sendAddTrackEvent(textTrack, this.media);
  30501. return textTrack;
  30502. }
  30503. }
  30504. return this.media.addTextTrack('metadata', 'id3');
  30505. }
  30506. onFragParsingMetadata(event, data) {
  30507. if (!this.media) {
  30508. return;
  30509. }
  30510. const {
  30511. hls: {
  30512. config: {
  30513. enableEmsgMetadataCues,
  30514. enableID3MetadataCues
  30515. }
  30516. }
  30517. } = this;
  30518. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  30519. return;
  30520. }
  30521. const {
  30522. samples
  30523. } = data;
  30524. // create track dynamically
  30525. if (!this.id3Track) {
  30526. this.id3Track = this.createTrack(this.media);
  30527. }
  30528. const Cue = getCueClass();
  30529. if (!Cue) {
  30530. return;
  30531. }
  30532. for (let i = 0; i < samples.length; i++) {
  30533. const type = samples[i].type;
  30534. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  30535. continue;
  30536. }
  30537. const frames = getId3Frames(samples[i].data);
  30538. if (frames) {
  30539. const startTime = samples[i].pts;
  30540. let endTime = startTime + samples[i].duration;
  30541. if (endTime > MAX_CUE_ENDTIME) {
  30542. endTime = MAX_CUE_ENDTIME;
  30543. }
  30544. const timeDiff = endTime - startTime;
  30545. if (timeDiff <= 0) {
  30546. endTime = startTime + MIN_CUE_DURATION;
  30547. }
  30548. for (let j = 0; j < frames.length; j++) {
  30549. const frame = frames[j];
  30550. // Safari doesn't put the timestamp frame in the TextTrack
  30551. if (!isId3TimestampFrame(frame)) {
  30552. // add a bounds to any unbounded cues
  30553. this.updateId3CueEnds(startTime, type);
  30554. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  30555. if (cue) {
  30556. this.id3Track.addCue(cue);
  30557. }
  30558. }
  30559. }
  30560. }
  30561. }
  30562. }
  30563. updateId3CueEnds(startTime, type) {
  30564. var _this$id3Track;
  30565. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  30566. if (cues) {
  30567. for (let i = cues.length; i--;) {
  30568. const cue = cues[i];
  30569. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  30570. cue.endTime = startTime;
  30571. }
  30572. }
  30573. }
  30574. }
  30575. onBufferFlushing(event, {
  30576. startOffset,
  30577. endOffset,
  30578. type
  30579. }) {
  30580. const {
  30581. id3Track,
  30582. hls
  30583. } = this;
  30584. if (!hls) {
  30585. return;
  30586. }
  30587. const {
  30588. config: {
  30589. enableEmsgMetadataCues,
  30590. enableID3MetadataCues
  30591. }
  30592. } = hls;
  30593. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  30594. let predicate;
  30595. if (type === 'audio') {
  30596. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  30597. } else if (type === 'video') {
  30598. predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  30599. } else {
  30600. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  30601. }
  30602. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  30603. }
  30604. }
  30605. onLevelUpdated(event, {
  30606. details
  30607. }) {
  30608. this.updateDateRangeCues(details, true);
  30609. }
  30610. onLevelPtsUpdated(event, data) {
  30611. if (Math.abs(data.drift) > 0.01) {
  30612. this.updateDateRangeCues(data.details);
  30613. }
  30614. }
  30615. updateDateRangeCues(details, removeOldCues) {
  30616. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  30617. return;
  30618. }
  30619. const {
  30620. id3Track
  30621. } = this;
  30622. const {
  30623. dateRanges
  30624. } = details;
  30625. const ids = Object.keys(dateRanges);
  30626. let dateRangeCuesAppended = this.dateRangeCuesAppended;
  30627. // Remove cues from track not found in details.dateRanges
  30628. if (id3Track && removeOldCues) {
  30629. var _id3Track$cues;
  30630. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  30631. const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));
  30632. for (let i = idsToRemove.length; i--;) {
  30633. const id = idsToRemove[i];
  30634. const cues = dateRangeCuesAppended[id].cues;
  30635. delete dateRangeCuesAppended[id];
  30636. Object.keys(cues).forEach(key => {
  30637. try {
  30638. const cue = cues[key];
  30639. cue.removeEventListener('enter', this.onEventCueEnter);
  30640. id3Track.removeCue(cue);
  30641. } catch (e) {
  30642. /* no-op */
  30643. }
  30644. });
  30645. }
  30646. } else {
  30647. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  30648. }
  30649. }
  30650. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  30651. const lastFragment = details.fragments[details.fragments.length - 1];
  30652. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  30653. return;
  30654. }
  30655. if (!this.id3Track) {
  30656. this.id3Track = this.createTrack(this.media);
  30657. }
  30658. const Cue = getCueClass();
  30659. for (let i = 0; i < ids.length; i++) {
  30660. const id = ids[i];
  30661. const dateRange = dateRanges[id];
  30662. const startTime = dateRange.startTime;
  30663. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  30664. const appendedDateRangeCues = dateRangeCuesAppended[id];
  30665. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  30666. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  30667. let endTime = MAX_CUE_ENDTIME;
  30668. const {
  30669. duration,
  30670. endDate
  30671. } = dateRange;
  30672. if (endDate && duration !== null) {
  30673. endTime = startTime + duration;
  30674. durationKnown = true;
  30675. } else if (dateRange.endOnNext && !durationKnown) {
  30676. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {
  30677. if (id !== dateRange.id) {
  30678. const otherDateRange = dateRanges[id];
  30679. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  30680. return otherDateRange;
  30681. }
  30682. }
  30683. return candidateDateRange;
  30684. }, null);
  30685. if (nextDateRangeWithSameClass) {
  30686. endTime = nextDateRangeWithSameClass.startTime;
  30687. durationKnown = true;
  30688. }
  30689. }
  30690. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  30691. // This is to emulate Safari HLS playback handling of DateRange tags
  30692. const attributes = Object.keys(dateRange.attr);
  30693. for (let j = 0; j < attributes.length; j++) {
  30694. const key = attributes[j];
  30695. if (!isDateRangeCueAttribute(key)) {
  30696. continue;
  30697. }
  30698. const cue = cues[key];
  30699. if (cue) {
  30700. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  30701. cue.endTime = endTime;
  30702. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  30703. cue.startTime = startTime;
  30704. cue.endTime = endTime;
  30705. }
  30706. } else if (Cue) {
  30707. let data = dateRange.attr[key];
  30708. if (isSCTE35Attribute(key)) {
  30709. data = hexToArrayBuffer(data);
  30710. }
  30711. const payload = {
  30712. key,
  30713. data
  30714. };
  30715. const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  30716. if (_cue) {
  30717. _cue.id = id;
  30718. this.id3Track.addCue(_cue);
  30719. cues[key] = _cue;
  30720. if (this.hls.config.interstitialsController) {
  30721. if (key === 'X-ASSET-LIST' || key === 'X-ASSET-URL') {
  30722. _cue.addEventListener('enter', this.onEventCueEnter);
  30723. }
  30724. }
  30725. }
  30726. }
  30727. }
  30728. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  30729. dateRangeCuesAppended[id] = {
  30730. cues,
  30731. dateRange,
  30732. durationKnown
  30733. };
  30734. }
  30735. }
  30736. }
  30737. class LatencyController {
  30738. constructor(hls) {
  30739. this.hls = void 0;
  30740. this.config = void 0;
  30741. this.media = null;
  30742. this.currentTime = 0;
  30743. this.stallCount = 0;
  30744. this._latency = null;
  30745. this._targetLatencyUpdated = false;
  30746. this.onTimeupdate = () => {
  30747. const {
  30748. media
  30749. } = this;
  30750. const levelDetails = this.levelDetails;
  30751. if (!media || !levelDetails) {
  30752. return;
  30753. }
  30754. this.currentTime = media.currentTime;
  30755. const latency = this.computeLatency();
  30756. if (latency === null) {
  30757. return;
  30758. }
  30759. this._latency = latency;
  30760. // Adapt playbackRate to meet target latency in low-latency mode
  30761. const {
  30762. lowLatencyMode,
  30763. maxLiveSyncPlaybackRate
  30764. } = this.config;
  30765. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  30766. return;
  30767. }
  30768. const targetLatency = this.targetLatency;
  30769. if (targetLatency === null) {
  30770. return;
  30771. }
  30772. const distanceFromTarget = latency - targetLatency;
  30773. // Only adjust playbackRate when within one target duration of targetLatency
  30774. // and more than one second from under-buffering.
  30775. // Playback further than one target duration from target can be considered DVR playback.
  30776. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  30777. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  30778. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  30779. const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  30780. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  30781. const playbackRate = Math.min(max, Math.max(1, rate));
  30782. this.changeMediaPlaybackRate(media, playbackRate);
  30783. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  30784. this.changeMediaPlaybackRate(media, 1);
  30785. }
  30786. };
  30787. this.hls = hls;
  30788. this.config = hls.config;
  30789. this.registerListeners();
  30790. }
  30791. get levelDetails() {
  30792. var _this$hls;
  30793. return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;
  30794. }
  30795. get latency() {
  30796. return this._latency || 0;
  30797. }
  30798. get maxLatency() {
  30799. const {
  30800. config
  30801. } = this;
  30802. if (config.liveMaxLatencyDuration !== undefined) {
  30803. return config.liveMaxLatencyDuration;
  30804. }
  30805. const levelDetails = this.levelDetails;
  30806. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  30807. }
  30808. get targetLatency() {
  30809. const levelDetails = this.levelDetails;
  30810. if (levelDetails === null || this.hls === null) {
  30811. return null;
  30812. }
  30813. const {
  30814. holdBack,
  30815. partHoldBack,
  30816. targetduration
  30817. } = levelDetails;
  30818. const {
  30819. liveSyncDuration,
  30820. liveSyncDurationCount,
  30821. lowLatencyMode
  30822. } = this.config;
  30823. const userConfig = this.hls.userConfig;
  30824. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  30825. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  30826. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  30827. }
  30828. const maxLiveSyncOnStallIncrease = targetduration;
  30829. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  30830. }
  30831. set targetLatency(latency) {
  30832. this.stallCount = 0;
  30833. this.config.liveSyncDuration = latency;
  30834. this._targetLatencyUpdated = true;
  30835. }
  30836. get liveSyncPosition() {
  30837. const liveEdge = this.estimateLiveEdge();
  30838. const targetLatency = this.targetLatency;
  30839. if (liveEdge === null || targetLatency === null) {
  30840. return null;
  30841. }
  30842. const levelDetails = this.levelDetails;
  30843. if (levelDetails === null) {
  30844. return null;
  30845. }
  30846. const edge = levelDetails.edge;
  30847. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  30848. const min = edge - levelDetails.totalduration;
  30849. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  30850. return Math.min(Math.max(min, syncPosition), max);
  30851. }
  30852. get drift() {
  30853. const levelDetails = this.levelDetails;
  30854. if (levelDetails === null) {
  30855. return 1;
  30856. }
  30857. return levelDetails.drift;
  30858. }
  30859. get edgeStalled() {
  30860. const levelDetails = this.levelDetails;
  30861. if (levelDetails === null) {
  30862. return 0;
  30863. }
  30864. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  30865. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  30866. }
  30867. get forwardBufferLength() {
  30868. const {
  30869. media
  30870. } = this;
  30871. const levelDetails = this.levelDetails;
  30872. if (!media || !levelDetails) {
  30873. return 0;
  30874. }
  30875. const bufferedRanges = media.buffered.length;
  30876. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  30877. }
  30878. destroy() {
  30879. this.unregisterListeners();
  30880. this.onMediaDetaching();
  30881. this.hls = null;
  30882. }
  30883. registerListeners() {
  30884. const {
  30885. hls
  30886. } = this;
  30887. if (!hls) {
  30888. return;
  30889. }
  30890. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30891. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30892. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30893. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  30894. hls.on(Events.ERROR, this.onError, this);
  30895. }
  30896. unregisterListeners() {
  30897. const {
  30898. hls
  30899. } = this;
  30900. if (!hls) {
  30901. return;
  30902. }
  30903. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30904. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30905. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30906. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  30907. hls.off(Events.ERROR, this.onError, this);
  30908. }
  30909. onMediaAttached(event, data) {
  30910. this.media = data.media;
  30911. this.media.addEventListener('timeupdate', this.onTimeupdate);
  30912. }
  30913. onMediaDetaching() {
  30914. if (this.media) {
  30915. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  30916. this.media = null;
  30917. }
  30918. }
  30919. onManifestLoading() {
  30920. this._latency = null;
  30921. this.stallCount = 0;
  30922. }
  30923. onLevelUpdated(event, {
  30924. details
  30925. }) {
  30926. if (details.advanced) {
  30927. this.onTimeupdate();
  30928. }
  30929. if (!details.live && this.media) {
  30930. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  30931. }
  30932. }
  30933. onError(event, data) {
  30934. var _this$levelDetails;
  30935. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  30936. return;
  30937. }
  30938. this.stallCount++;
  30939. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  30940. this.hls.logger.warn('[latency-controller]: Stall detected, adjusting target latency');
  30941. }
  30942. }
  30943. changeMediaPlaybackRate(media, playbackRate) {
  30944. var _this$hls2, _this$targetLatency;
  30945. if (media.playbackRate === playbackRate) {
  30946. return;
  30947. }
  30948. (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);
  30949. media.playbackRate = playbackRate;
  30950. }
  30951. estimateLiveEdge() {
  30952. const levelDetails = this.levelDetails;
  30953. if (levelDetails === null) {
  30954. return null;
  30955. }
  30956. return levelDetails.edge + levelDetails.age;
  30957. }
  30958. computeLatency() {
  30959. const liveEdge = this.estimateLiveEdge();
  30960. if (liveEdge === null) {
  30961. return null;
  30962. }
  30963. return liveEdge - this.currentTime;
  30964. }
  30965. }
  30966. class LevelController extends BasePlaylistController {
  30967. constructor(hls, contentSteeringController) {
  30968. super(hls, 'level-controller');
  30969. this._levels = [];
  30970. this._firstLevel = -1;
  30971. this._maxAutoLevel = -1;
  30972. this._startLevel = void 0;
  30973. this.currentLevel = null;
  30974. this.currentLevelIndex = -1;
  30975. this.manualLevelIndex = -1;
  30976. this.steering = void 0;
  30977. this.onParsedComplete = void 0;
  30978. this.steering = contentSteeringController;
  30979. this._registerListeners();
  30980. }
  30981. _registerListeners() {
  30982. const {
  30983. hls
  30984. } = this;
  30985. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30986. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  30987. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  30988. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  30989. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  30990. hls.on(Events.ERROR, this.onError, this);
  30991. }
  30992. _unregisterListeners() {
  30993. const {
  30994. hls
  30995. } = this;
  30996. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  30997. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  30998. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  30999. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31000. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  31001. hls.off(Events.ERROR, this.onError, this);
  31002. }
  31003. destroy() {
  31004. this._unregisterListeners();
  31005. this.steering = null;
  31006. this.resetLevels();
  31007. super.destroy();
  31008. }
  31009. stopLoad() {
  31010. const levels = this._levels;
  31011. // clean up live level details to force reload them, and reset load errors
  31012. levels.forEach(level => {
  31013. level.loadError = 0;
  31014. level.fragmentError = 0;
  31015. });
  31016. super.stopLoad();
  31017. }
  31018. resetLevels() {
  31019. this._startLevel = undefined;
  31020. this.manualLevelIndex = -1;
  31021. this.currentLevelIndex = -1;
  31022. this.currentLevel = null;
  31023. this._levels = [];
  31024. this._maxAutoLevel = -1;
  31025. }
  31026. onManifestLoading(event, data) {
  31027. this.resetLevels();
  31028. }
  31029. onManifestLoaded(event, data) {
  31030. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  31031. const levels = [];
  31032. const redundantSet = {};
  31033. const generatePathwaySet = {};
  31034. let resolutionFound = false;
  31035. let videoCodecFound = false;
  31036. let audioCodecFound = false;
  31037. data.levels.forEach(levelParsed => {
  31038. const attributes = levelParsed.attrs;
  31039. let {
  31040. audioCodec,
  31041. videoCodec
  31042. } = levelParsed;
  31043. if (audioCodec) {
  31044. // Returns empty and set to undefined for 'mp4a.40.34' with fallback to 'audio/mpeg' SourceBuffer
  31045. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || undefined;
  31046. }
  31047. if (videoCodec) {
  31048. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  31049. }
  31050. // only keep levels with supported audio/video codecs
  31051. const {
  31052. width,
  31053. height,
  31054. unknownCodecs
  31055. } = levelParsed;
  31056. let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  31057. if (unknownCodecs) {
  31058. // Treat unknown codec as audio or video codec based on passing `isTypeSupported` check
  31059. // (allows for playback of any supported codec even if not indexed in utils/codecs)
  31060. for (let i = unknownUnsupportedCodecCount; i--;) {
  31061. const unknownCodec = unknownCodecs[i];
  31062. if (this.isAudioSupported(unknownCodec)) {
  31063. levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;
  31064. unknownUnsupportedCodecCount--;
  31065. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  31066. } else if (this.isVideoSupported(unknownCodec)) {
  31067. levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;
  31068. unknownUnsupportedCodecCount--;
  31069. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  31070. }
  31071. }
  31072. }
  31073. resolutionFound || (resolutionFound = !!(width && height));
  31074. videoCodecFound || (videoCodecFound = !!videoCodec);
  31075. audioCodecFound || (audioCodecFound = !!audioCodec);
  31076. if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {
  31077. this.log(`Some or all CODECS not supported "${attributes.CODECS}"`);
  31078. return;
  31079. }
  31080. const {
  31081. CODECS,
  31082. 'FRAME-RATE': FRAMERATE,
  31083. 'HDCP-LEVEL': HDCP,
  31084. 'PATHWAY-ID': PATHWAY,
  31085. RESOLUTION,
  31086. 'VIDEO-RANGE': VIDEO_RANGE
  31087. } = attributes;
  31088. const contentSteeringPrefix = `${PATHWAY || '.'}-`;
  31089. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  31090. if (!redundantSet[levelKey]) {
  31091. const level = this.createLevel(levelParsed);
  31092. redundantSet[levelKey] = level;
  31093. generatePathwaySet[levelKey] = 1;
  31094. levels.push(level);
  31095. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  31096. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  31097. // Content Steering controller to handles Pathway fallback on error
  31098. const pathwayCount = generatePathwaySet[levelKey] += 1;
  31099. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  31100. const level = this.createLevel(levelParsed);
  31101. redundantSet[levelKey] = level;
  31102. levels.push(level);
  31103. } else {
  31104. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  31105. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  31106. }
  31107. });
  31108. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  31109. }
  31110. createLevel(levelParsed) {
  31111. const level = new Level(levelParsed);
  31112. const supplemental = levelParsed.supplemental;
  31113. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  31114. const error = new Error(`SUPPLEMENTAL-CODECS not supported "${supplemental.videoCodec}"`);
  31115. this.log(error.message);
  31116. level.supportedResult = getUnsupportedResult(error, []);
  31117. }
  31118. return level;
  31119. }
  31120. isAudioSupported(codec) {
  31121. return areCodecsMediaSourceSupported(codec, 'audio', this.hls.config.preferManagedMediaSource);
  31122. }
  31123. isVideoSupported(codec) {
  31124. return areCodecsMediaSourceSupported(codec, 'video', this.hls.config.preferManagedMediaSource);
  31125. }
  31126. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  31127. let audioTracks = [];
  31128. let subtitleTracks = [];
  31129. let levels = filteredLevels;
  31130. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  31131. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  31132. levels = levels.filter(({
  31133. videoCodec,
  31134. videoRange,
  31135. width,
  31136. height
  31137. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  31138. }
  31139. if (levels.length === 0) {
  31140. // Dispatch error after MANIFEST_LOADED is done propagating
  31141. Promise.resolve().then(() => {
  31142. if (this.hls) {
  31143. let message = 'no level with compatible codecs found in manifest';
  31144. let reason = message;
  31145. if (data.levels.length) {
  31146. reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map(level => level.attrs.CODECS).filter((value, index, array) => array.indexOf(value) === index))}`;
  31147. this.warn(reason);
  31148. message += ` (${reason})`;
  31149. }
  31150. const error = new Error(message);
  31151. this.hls.trigger(Events.ERROR, {
  31152. type: ErrorTypes.MEDIA_ERROR,
  31153. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  31154. fatal: true,
  31155. url: data.url,
  31156. error,
  31157. reason
  31158. });
  31159. }
  31160. });
  31161. return;
  31162. }
  31163. if (data.audioTracks) {
  31164. audioTracks = data.audioTracks.filter(track => !track.audioCodec || this.isAudioSupported(track.audioCodec));
  31165. // Assign ids after filtering as array indices by group-id
  31166. assignTrackIdsByGroup(audioTracks);
  31167. }
  31168. if (data.subtitles) {
  31169. subtitleTracks = data.subtitles;
  31170. assignTrackIdsByGroup(subtitleTracks);
  31171. }
  31172. // start bitrate is the first bitrate of the manifest
  31173. const unsortedLevels = levels.slice(0);
  31174. // sort levels from lowest to highest
  31175. levels.sort((a, b) => {
  31176. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  31177. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  31178. }
  31179. // sort on height before bitrate for cap-level-controller
  31180. if (resolutionFound && a.height !== b.height) {
  31181. return a.height - b.height;
  31182. }
  31183. if (a.frameRate !== b.frameRate) {
  31184. return a.frameRate - b.frameRate;
  31185. }
  31186. if (a.videoRange !== b.videoRange) {
  31187. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  31188. }
  31189. if (a.videoCodec !== b.videoCodec) {
  31190. const valueA = videoCodecPreferenceValue(a.videoCodec);
  31191. const valueB = videoCodecPreferenceValue(b.videoCodec);
  31192. if (valueA !== valueB) {
  31193. return valueB - valueA;
  31194. }
  31195. }
  31196. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  31197. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  31198. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  31199. if (valueA !== valueB) {
  31200. return valueB - valueA;
  31201. }
  31202. }
  31203. if (a.averageBitrate !== b.averageBitrate) {
  31204. return a.averageBitrate - b.averageBitrate;
  31205. }
  31206. return 0;
  31207. });
  31208. let firstLevelInPlaylist = unsortedLevels[0];
  31209. if (this.steering) {
  31210. levels = this.steering.filterParsedLevels(levels);
  31211. if (levels.length !== unsortedLevels.length) {
  31212. for (let i = 0; i < unsortedLevels.length; i++) {
  31213. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  31214. firstLevelInPlaylist = unsortedLevels[i];
  31215. break;
  31216. }
  31217. }
  31218. }
  31219. }
  31220. this._levels = levels;
  31221. // find index of first level in sorted levels
  31222. for (let i = 0; i < levels.length; i++) {
  31223. if (levels[i] === firstLevelInPlaylist) {
  31224. var _this$hls$userConfig;
  31225. this._firstLevel = i;
  31226. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  31227. const bandwidthEstimate = this.hls.bandwidthEstimate;
  31228. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  31229. // Update default bwe to first variant bitrate as long it has not been configured or set
  31230. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  31231. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  31232. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  31233. this.hls.bandwidthEstimate = startingBwEstimate;
  31234. }
  31235. }
  31236. break;
  31237. }
  31238. }
  31239. // Audio is only alternate if manifest include a URI along with the audio group tag,
  31240. // and this is not an audio-only stream where levels contain audio-only
  31241. const audioOnly = audioCodecFound && !videoCodecFound;
  31242. const config = this.hls.config;
  31243. const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  31244. const edata = {
  31245. levels,
  31246. audioTracks,
  31247. subtitleTracks,
  31248. sessionData: data.sessionData,
  31249. sessionKeys: data.sessionKeys,
  31250. firstLevel: this._firstLevel,
  31251. stats: data.stats,
  31252. audio: audioCodecFound,
  31253. video: videoCodecFound,
  31254. altAudio: altAudioEnabled && !audioOnly && audioTracks.some(t => !!t.url)
  31255. };
  31256. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  31257. }
  31258. get levels() {
  31259. if (this._levels.length === 0) {
  31260. return null;
  31261. }
  31262. return this._levels;
  31263. }
  31264. get loadLevelObj() {
  31265. return this.currentLevel;
  31266. }
  31267. get level() {
  31268. return this.currentLevelIndex;
  31269. }
  31270. set level(newLevel) {
  31271. const levels = this._levels;
  31272. if (levels.length === 0) {
  31273. return;
  31274. }
  31275. // check if level idx is valid
  31276. if (newLevel < 0 || newLevel >= levels.length) {
  31277. // invalid level id given, trigger error
  31278. const error = new Error('invalid level idx');
  31279. const fatal = newLevel < 0;
  31280. this.hls.trigger(Events.ERROR, {
  31281. type: ErrorTypes.OTHER_ERROR,
  31282. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  31283. level: newLevel,
  31284. fatal,
  31285. error,
  31286. reason: error.message
  31287. });
  31288. if (fatal) {
  31289. return;
  31290. }
  31291. newLevel = Math.min(newLevel, levels.length - 1);
  31292. }
  31293. const lastLevelIndex = this.currentLevelIndex;
  31294. const lastLevel = this.currentLevel;
  31295. const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  31296. const level = levels[newLevel];
  31297. const pathwayId = level.attrs['PATHWAY-ID'];
  31298. this.currentLevelIndex = newLevel;
  31299. this.currentLevel = level;
  31300. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  31301. return;
  31302. }
  31303. 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 : ''}`);
  31304. const levelSwitchingData = {
  31305. level: newLevel,
  31306. attrs: level.attrs,
  31307. details: level.details,
  31308. bitrate: level.bitrate,
  31309. averageBitrate: level.averageBitrate,
  31310. maxBitrate: level.maxBitrate,
  31311. realBitrate: level.realBitrate,
  31312. width: level.width,
  31313. height: level.height,
  31314. codecSet: level.codecSet,
  31315. audioCodec: level.audioCodec,
  31316. videoCodec: level.videoCodec,
  31317. audioGroups: level.audioGroups,
  31318. subtitleGroups: level.subtitleGroups,
  31319. loaded: level.loaded,
  31320. loadError: level.loadError,
  31321. fragmentError: level.fragmentError,
  31322. name: level.name,
  31323. id: level.id,
  31324. uri: level.uri,
  31325. url: level.url,
  31326. urlId: 0,
  31327. audioGroupIds: level.audioGroupIds,
  31328. textGroupIds: level.textGroupIds
  31329. };
  31330. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  31331. // check if we need to load playlist for this level
  31332. const levelDetails = level.details;
  31333. if (!levelDetails || levelDetails.live) {
  31334. // level not retrieved yet, or live playlist we need to (re)load it
  31335. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  31336. this.loadPlaylist(hlsUrlParameters);
  31337. }
  31338. }
  31339. get manualLevel() {
  31340. return this.manualLevelIndex;
  31341. }
  31342. set manualLevel(newLevel) {
  31343. this.manualLevelIndex = newLevel;
  31344. if (this._startLevel === undefined) {
  31345. this._startLevel = newLevel;
  31346. }
  31347. if (newLevel !== -1) {
  31348. this.level = newLevel;
  31349. }
  31350. }
  31351. get firstLevel() {
  31352. return this._firstLevel;
  31353. }
  31354. set firstLevel(newLevel) {
  31355. this._firstLevel = newLevel;
  31356. }
  31357. get startLevel() {
  31358. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  31359. if (this._startLevel === undefined) {
  31360. const configStartLevel = this.hls.config.startLevel;
  31361. if (configStartLevel !== undefined) {
  31362. return configStartLevel;
  31363. }
  31364. return this.hls.firstAutoLevel;
  31365. }
  31366. return this._startLevel;
  31367. }
  31368. set startLevel(newLevel) {
  31369. this._startLevel = newLevel;
  31370. }
  31371. get pathways() {
  31372. if (this.steering) {
  31373. return this.steering.pathways();
  31374. }
  31375. return [];
  31376. }
  31377. get pathwayPriority() {
  31378. if (this.steering) {
  31379. return this.steering.pathwayPriority;
  31380. }
  31381. return null;
  31382. }
  31383. set pathwayPriority(pathwayPriority) {
  31384. if (this.steering) {
  31385. const pathwaysList = this.steering.pathways();
  31386. const filteredPathwayPriority = pathwayPriority.filter(pathwayId => {
  31387. return pathwaysList.indexOf(pathwayId) !== -1;
  31388. });
  31389. if (pathwayPriority.length < 1) {
  31390. this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);
  31391. return;
  31392. }
  31393. this.steering.pathwayPriority = filteredPathwayPriority;
  31394. }
  31395. }
  31396. onError(event, data) {
  31397. if (data.fatal || !data.context) {
  31398. return;
  31399. }
  31400. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  31401. this.checkRetry(data);
  31402. }
  31403. }
  31404. // reset errors on the successful load of a fragment
  31405. onFragBuffered(event, {
  31406. frag
  31407. }) {
  31408. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  31409. const el = frag.elementaryStreams;
  31410. if (!Object.keys(el).some(type => !!el[type])) {
  31411. return;
  31412. }
  31413. const level = this._levels[frag.level];
  31414. if (level != null && level.loadError) {
  31415. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  31416. level.loadError = 0;
  31417. }
  31418. }
  31419. }
  31420. onLevelLoaded(event, data) {
  31421. var _data$deliveryDirecti2;
  31422. const {
  31423. level,
  31424. details
  31425. } = data;
  31426. const curLevel = data.levelInfo;
  31427. if (!curLevel) {
  31428. var _data$deliveryDirecti;
  31429. this.warn(`Invalid level index ${level}`);
  31430. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  31431. details.deltaUpdateFailed = true;
  31432. }
  31433. return;
  31434. }
  31435. // only process level loaded events matching with expected level or prior to switch when media playlist is loaded directly
  31436. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  31437. // reset level load error counter on successful level loaded only if there is no issues with fragments
  31438. if (curLevel.fragmentError === 0) {
  31439. curLevel.loadError = 0;
  31440. }
  31441. // Ignore matching details populated by loading a Media Playlist directly
  31442. let previousDetails = curLevel.details;
  31443. if (previousDetails === data.details && previousDetails.advanced) {
  31444. previousDetails = undefined;
  31445. }
  31446. this.playlistLoaded(level, data, previousDetails);
  31447. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  31448. // received a delta playlist update that cannot be merged
  31449. details.deltaUpdateFailed = true;
  31450. }
  31451. }
  31452. loadPlaylist(hlsUrlParameters) {
  31453. super.loadPlaylist();
  31454. if (this.shouldLoadPlaylist(this.currentLevel)) {
  31455. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  31456. }
  31457. }
  31458. loadingPlaylist(currentLevel, hlsUrlParameters) {
  31459. super.loadingPlaylist(currentLevel, hlsUrlParameters);
  31460. const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  31461. const currentLevelIndex = this.currentLevelIndex;
  31462. const pathwayId = currentLevel.attrs['PATHWAY-ID'];
  31463. const details = currentLevel.details;
  31464. const age = details == null ? void 0 : details.age;
  31465. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${pathwayId ? ' Pathway ' + pathwayId : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);
  31466. this.hls.trigger(Events.LEVEL_LOADING, {
  31467. url,
  31468. level: currentLevelIndex,
  31469. levelInfo: currentLevel,
  31470. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  31471. id: 0,
  31472. // Deprecated Level urlId
  31473. deliveryDirectives: hlsUrlParameters || null
  31474. });
  31475. }
  31476. get nextLoadLevel() {
  31477. if (this.manualLevelIndex !== -1) {
  31478. return this.manualLevelIndex;
  31479. } else {
  31480. return this.hls.nextAutoLevel;
  31481. }
  31482. }
  31483. set nextLoadLevel(nextLevel) {
  31484. this.level = nextLevel;
  31485. if (this.manualLevelIndex === -1) {
  31486. this.hls.nextAutoLevel = nextLevel;
  31487. }
  31488. }
  31489. removeLevel(levelIndex) {
  31490. var _this$currentLevel;
  31491. if (this._levels.length === 1) {
  31492. return;
  31493. }
  31494. const levels = this._levels.filter((level, index) => {
  31495. if (index !== levelIndex) {
  31496. return true;
  31497. }
  31498. if (this.steering) {
  31499. this.steering.removeLevel(level);
  31500. }
  31501. if (level === this.currentLevel) {
  31502. this.currentLevel = null;
  31503. this.currentLevelIndex = -1;
  31504. if (level.details) {
  31505. level.details.fragments.forEach(f => f.level = -1);
  31506. }
  31507. }
  31508. return false;
  31509. });
  31510. reassignFragmentLevelIndexes(levels);
  31511. this._levels = levels;
  31512. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  31513. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  31514. }
  31515. if (this.manualLevelIndex > -1) {
  31516. this.manualLevelIndex = this.currentLevelIndex;
  31517. }
  31518. const maxLevel = levels.length - 1;
  31519. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  31520. if (this._startLevel) {
  31521. this._startLevel = Math.min(this._startLevel, maxLevel);
  31522. }
  31523. this.hls.trigger(Events.LEVELS_UPDATED, {
  31524. levels
  31525. });
  31526. }
  31527. onLevelsUpdated(event, {
  31528. levels
  31529. }) {
  31530. this._levels = levels;
  31531. }
  31532. checkMaxAutoUpdated() {
  31533. const {
  31534. autoLevelCapping,
  31535. maxAutoLevel,
  31536. maxHdcpLevel
  31537. } = this.hls;
  31538. if (this._maxAutoLevel !== maxAutoLevel) {
  31539. this._maxAutoLevel = maxAutoLevel;
  31540. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  31541. autoLevelCapping,
  31542. levels: this.levels,
  31543. maxAutoLevel,
  31544. minAutoLevel: this.hls.minAutoLevel,
  31545. maxHdcpLevel
  31546. });
  31547. }
  31548. }
  31549. }
  31550. function assignTrackIdsByGroup(tracks) {
  31551. const groups = {};
  31552. tracks.forEach(track => {
  31553. const groupId = track.groupId || '';
  31554. track.id = groups[groupId] = groups[groupId] || 0;
  31555. groups[groupId]++;
  31556. });
  31557. }
  31558. function getSourceBuffer() {
  31559. return self.SourceBuffer || self.WebKitSourceBuffer;
  31560. }
  31561. function isMSESupported() {
  31562. const mediaSource = getMediaSource();
  31563. if (!mediaSource) {
  31564. return false;
  31565. }
  31566. // if SourceBuffer is exposed ensure its API is valid
  31567. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  31568. const sourceBuffer = getSourceBuffer();
  31569. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  31570. }
  31571. function isSupported() {
  31572. if (!isMSESupported()) {
  31573. return false;
  31574. }
  31575. const mediaSource = getMediaSource();
  31576. 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'))));
  31577. }
  31578. function changeTypeSupported() {
  31579. var _sourceBuffer$prototy;
  31580. const sourceBuffer = getSourceBuffer();
  31581. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  31582. }
  31583. const TICK_INTERVAL = 100; // how often to tick in ms
  31584. class StreamController extends BaseStreamController {
  31585. constructor(hls, fragmentTracker, keyLoader) {
  31586. super(hls, fragmentTracker, keyLoader, 'stream-controller', PlaylistLevelType.MAIN);
  31587. this.audioCodecSwap = false;
  31588. this.level = -1;
  31589. this._forceStartLoad = false;
  31590. this._hasEnoughToStart = false;
  31591. this.altAudio = 0;
  31592. this.audioOnly = false;
  31593. this.fragPlaying = null;
  31594. this.fragLastKbps = 0;
  31595. this.couldBacktrack = false;
  31596. this.backtrackFragment = null;
  31597. this.audioCodecSwitch = false;
  31598. this.videoBuffer = null;
  31599. this.onMediaPlaying = () => {
  31600. // tick to speed up FRAG_CHANGED triggering
  31601. this.tick();
  31602. };
  31603. this.onMediaSeeked = () => {
  31604. const media = this.media;
  31605. const currentTime = media ? media.currentTime : null;
  31606. if (currentTime === null || !isFiniteNumber(currentTime)) {
  31607. return;
  31608. }
  31609. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  31610. // If seeked was issued before buffer was appended do not tick immediately
  31611. if (!this.getBufferedFrag(currentTime)) {
  31612. return;
  31613. }
  31614. const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  31615. if (bufferInfo === null || bufferInfo.len === 0) {
  31616. this.warn(`Main forward buffer length at ${currentTime} on "seeked" event ${bufferInfo ? bufferInfo.len : 'empty'})`);
  31617. return;
  31618. }
  31619. // tick to speed up FRAG_CHANGED triggering
  31620. this.tick();
  31621. };
  31622. this.registerListeners();
  31623. }
  31624. registerListeners() {
  31625. super.registerListeners();
  31626. const {
  31627. hls
  31628. } = this;
  31629. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  31630. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  31631. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31632. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  31633. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  31634. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  31635. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  31636. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  31637. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31638. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  31639. }
  31640. unregisterListeners() {
  31641. super.unregisterListeners();
  31642. const {
  31643. hls
  31644. } = this;
  31645. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  31646. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31647. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  31648. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  31649. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  31650. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  31651. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  31652. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31653. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  31654. }
  31655. onHandlerDestroying() {
  31656. // @ts-ignore
  31657. this.onMediaPlaying = this.onMediaSeeked = null;
  31658. this.unregisterListeners();
  31659. super.onHandlerDestroying();
  31660. }
  31661. startLoad(startPosition, skipSeekToStartPosition) {
  31662. if (this.levels) {
  31663. const {
  31664. lastCurrentTime,
  31665. hls
  31666. } = this;
  31667. this.stopLoad();
  31668. this.setInterval(TICK_INTERVAL);
  31669. this.level = -1;
  31670. if (!this.startFragRequested) {
  31671. // determine load level
  31672. let startLevel = hls.startLevel;
  31673. if (startLevel === -1) {
  31674. if (hls.config.testBandwidth && this.levels.length > 1) {
  31675. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  31676. startLevel = 0;
  31677. this.bitrateTest = true;
  31678. } else {
  31679. startLevel = hls.firstAutoLevel;
  31680. }
  31681. }
  31682. // set new level to playlist loader : this will trigger start level load
  31683. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  31684. hls.nextLoadLevel = startLevel;
  31685. this.level = hls.loadLevel;
  31686. this._hasEnoughToStart = !!skipSeekToStartPosition;
  31687. }
  31688. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  31689. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  31690. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  31691. startPosition = lastCurrentTime;
  31692. }
  31693. this.state = State.IDLE;
  31694. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  31695. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  31696. this.tick();
  31697. } else {
  31698. this._forceStartLoad = true;
  31699. this.state = State.STOPPED;
  31700. }
  31701. }
  31702. stopLoad() {
  31703. this._forceStartLoad = false;
  31704. super.stopLoad();
  31705. }
  31706. doTick() {
  31707. switch (this.state) {
  31708. case State.WAITING_LEVEL:
  31709. {
  31710. const {
  31711. levels,
  31712. level
  31713. } = this;
  31714. const currentLevel = levels == null ? void 0 : levels[level];
  31715. const details = currentLevel == null ? void 0 : currentLevel.details;
  31716. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  31717. if (this.waitForCdnTuneIn(details)) {
  31718. break;
  31719. }
  31720. this.state = State.IDLE;
  31721. break;
  31722. } else if (this.hls.nextLoadLevel !== this.level) {
  31723. this.state = State.IDLE;
  31724. break;
  31725. }
  31726. break;
  31727. }
  31728. case State.FRAG_LOADING_WAITING_RETRY:
  31729. {
  31730. var _this$media;
  31731. const now = self.performance.now();
  31732. const retryDate = this.retryDate;
  31733. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  31734. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  31735. const {
  31736. levels,
  31737. level
  31738. } = this;
  31739. const currentLevel = levels == null ? void 0 : levels[level];
  31740. this.resetStartWhenNotLoaded(currentLevel || null);
  31741. this.state = State.IDLE;
  31742. }
  31743. }
  31744. break;
  31745. }
  31746. if (this.state === State.IDLE) {
  31747. this.doTickIdle();
  31748. }
  31749. this.onTickEnd();
  31750. }
  31751. onTickEnd() {
  31752. var _this$media2;
  31753. super.onTickEnd();
  31754. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  31755. this.lastCurrentTime = this.media.currentTime;
  31756. }
  31757. this.checkFragmentChanged();
  31758. }
  31759. doTickIdle() {
  31760. const {
  31761. hls,
  31762. levelLastLoaded,
  31763. levels,
  31764. media
  31765. } = this;
  31766. // if start level not parsed yet OR
  31767. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  31768. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  31769. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  31770. return;
  31771. }
  31772. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  31773. if (this.altAudio && this.audioOnly) {
  31774. return;
  31775. }
  31776. const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  31777. if (!(levels != null && levels[level])) {
  31778. return;
  31779. }
  31780. const levelInfo = levels[level];
  31781. // if buffer length is less than maxBufLen try to load a new fragment
  31782. const bufferInfo = this.getMainFwdBufferInfo();
  31783. if (bufferInfo === null) {
  31784. return;
  31785. }
  31786. const lastDetails = this.getLevelDetails();
  31787. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  31788. const data = {};
  31789. if (this.altAudio === 2) {
  31790. data.type = 'video';
  31791. }
  31792. this.hls.trigger(Events.BUFFER_EOS, data);
  31793. this.state = State.ENDED;
  31794. return;
  31795. }
  31796. if (!this.buffering) {
  31797. return;
  31798. }
  31799. // set next load level : this will trigger a playlist load if needed
  31800. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  31801. this.log(`Adapting to level ${level} from level ${this.level}`);
  31802. }
  31803. this.level = hls.nextLoadLevel = level;
  31804. const levelDetails = levelInfo.details;
  31805. // if level info not retrieved yet, switch state and wait for level retrieval
  31806. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  31807. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  31808. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  31809. this.level = level;
  31810. this.state = State.WAITING_LEVEL;
  31811. this.startFragRequested = false;
  31812. return;
  31813. }
  31814. const bufferLen = bufferInfo.len;
  31815. // 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
  31816. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  31817. // Stay idle if we are still with buffer margins
  31818. if (bufferLen >= maxBufLen) {
  31819. return;
  31820. }
  31821. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  31822. this.backtrackFragment = null;
  31823. }
  31824. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  31825. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  31826. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  31827. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  31828. var _this$backtrackFragme;
  31829. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  31830. const fragIdx = backtrackSn - levelDetails.startSN;
  31831. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  31832. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  31833. frag = backtrackFrag;
  31834. this.fragmentTracker.removeFragment(backtrackFrag);
  31835. }
  31836. } else if (this.backtrackFragment && bufferInfo.len) {
  31837. this.backtrackFragment = null;
  31838. }
  31839. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  31840. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  31841. const gapStart = frag.gap;
  31842. if (!gapStart) {
  31843. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  31844. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  31845. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  31846. if (mediaBuffer) {
  31847. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  31848. }
  31849. }
  31850. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  31851. }
  31852. if (!frag) {
  31853. return;
  31854. }
  31855. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  31856. frag = frag.initSegment;
  31857. }
  31858. this.loadFragment(frag, levelInfo, targetBufferTime);
  31859. }
  31860. loadFragment(frag, level, targetBufferTime) {
  31861. // Check if fragment is not loaded
  31862. const fragState = this.fragmentTracker.getState(frag);
  31863. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  31864. if (!isMediaFragment(frag)) {
  31865. this._loadInitSegment(frag, level);
  31866. } else if (this.bitrateTest) {
  31867. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  31868. this._loadBitrateTestFrag(frag, level);
  31869. } else {
  31870. super.loadFragment(frag, level, targetBufferTime);
  31871. }
  31872. } else {
  31873. this.clearTrackerIfNeeded(frag);
  31874. }
  31875. }
  31876. getBufferedFrag(position) {
  31877. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  31878. }
  31879. followingBufferedFrag(frag) {
  31880. if (frag) {
  31881. // try to get range of next fragment (500ms after this range)
  31882. return this.getBufferedFrag(frag.end + 0.5);
  31883. }
  31884. return null;
  31885. }
  31886. /*
  31887. on immediate level switch :
  31888. - pause playback if playing
  31889. - cancel any pending load request
  31890. - and trigger a buffer flush
  31891. */
  31892. immediateLevelSwitch() {
  31893. this.abortCurrentFrag();
  31894. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  31895. }
  31896. /**
  31897. * try to switch ASAP without breaking video playback:
  31898. * in order to ensure smooth but quick level switching,
  31899. * we need to find the next flushable buffer range
  31900. * we should take into account new segment fetch time
  31901. */
  31902. nextLevelSwitch() {
  31903. const {
  31904. levels,
  31905. media
  31906. } = this;
  31907. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  31908. if (media != null && media.readyState) {
  31909. let fetchdelay;
  31910. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  31911. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  31912. // flush buffer preceding current fragment (flush until current fragment start offset)
  31913. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  31914. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  31915. }
  31916. const levelDetails = this.getLevelDetails();
  31917. if (levelDetails != null && levelDetails.live) {
  31918. const bufferInfo = this.getMainFwdBufferInfo();
  31919. // Do not flush in live stream with low buffer
  31920. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  31921. return;
  31922. }
  31923. }
  31924. if (!media.paused && levels) {
  31925. // add a safety delay of 1s
  31926. const nextLevelId = this.hls.nextLoadLevel;
  31927. const nextLevel = levels[nextLevelId];
  31928. const fragLastKbps = this.fragLastKbps;
  31929. if (fragLastKbps && this.fragCurrent) {
  31930. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  31931. } else {
  31932. fetchdelay = 0;
  31933. }
  31934. } else {
  31935. fetchdelay = 0;
  31936. }
  31937. // this.log('fetchdelay:'+fetchdelay);
  31938. // find buffer range that will be reached once new fragment will be fetched
  31939. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  31940. if (bufferedFrag) {
  31941. // we can flush buffer range following this one without stalling playback
  31942. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  31943. if (nextBufferedFrag) {
  31944. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  31945. this.abortCurrentFrag();
  31946. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  31947. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  31948. const fragDuration = nextBufferedFrag.duration;
  31949. 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)));
  31950. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  31951. }
  31952. }
  31953. }
  31954. }
  31955. abortCurrentFrag() {
  31956. const fragCurrent = this.fragCurrent;
  31957. this.fragCurrent = null;
  31958. this.backtrackFragment = null;
  31959. if (fragCurrent) {
  31960. fragCurrent.abortRequests();
  31961. this.fragmentTracker.removeFragment(fragCurrent);
  31962. }
  31963. switch (this.state) {
  31964. case State.KEY_LOADING:
  31965. case State.FRAG_LOADING:
  31966. case State.FRAG_LOADING_WAITING_RETRY:
  31967. case State.PARSING:
  31968. case State.PARSED:
  31969. this.state = State.IDLE;
  31970. break;
  31971. }
  31972. this.nextLoadPosition = this.getLoadPosition();
  31973. }
  31974. flushMainBuffer(startOffset, endOffset) {
  31975. super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? 'video' : null);
  31976. }
  31977. onMediaAttached(event, data) {
  31978. super.onMediaAttached(event, data);
  31979. const media = data.media;
  31980. addEventListener(media, 'playing', this.onMediaPlaying);
  31981. addEventListener(media, 'seeked', this.onMediaSeeked);
  31982. }
  31983. onMediaDetaching(event, data) {
  31984. const {
  31985. media
  31986. } = this;
  31987. if (media) {
  31988. removeEventListener(media, 'playing', this.onMediaPlaying);
  31989. removeEventListener(media, 'seeked', this.onMediaSeeked);
  31990. }
  31991. this.videoBuffer = null;
  31992. this.fragPlaying = null;
  31993. super.onMediaDetaching(event, data);
  31994. const transferringMedia = !!data.transferMedia;
  31995. if (transferringMedia) {
  31996. return;
  31997. }
  31998. this._hasEnoughToStart = false;
  31999. }
  32000. onManifestLoading() {
  32001. super.onManifestLoading();
  32002. // reset buffer on manifest loading
  32003. this.log('Trigger BUFFER_RESET');
  32004. this.hls.trigger(Events.BUFFER_RESET, undefined);
  32005. this.couldBacktrack = false;
  32006. this.fragLastKbps = 0;
  32007. this.fragPlaying = this.backtrackFragment = null;
  32008. this.altAudio = 0;
  32009. this.audioOnly = false;
  32010. }
  32011. onManifestParsed(event, data) {
  32012. // detect if we have different kind of audio codecs used amongst playlists
  32013. let aac = false;
  32014. let heaac = false;
  32015. data.levels.forEach(level => {
  32016. const codec = level.audioCodec;
  32017. if (codec) {
  32018. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  32019. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  32020. }
  32021. });
  32022. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  32023. if (this.audioCodecSwitch) {
  32024. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  32025. }
  32026. this.levels = data.levels;
  32027. this.startFragRequested = false;
  32028. }
  32029. onLevelLoading(event, data) {
  32030. const {
  32031. levels
  32032. } = this;
  32033. if (!levels || this.state !== State.IDLE) {
  32034. return;
  32035. }
  32036. const level = data.levelInfo;
  32037. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  32038. this.state = State.WAITING_LEVEL;
  32039. }
  32040. }
  32041. onLevelLoaded(event, data) {
  32042. var _curLevel$details;
  32043. const {
  32044. levels,
  32045. startFragRequested
  32046. } = this;
  32047. const newLevelId = data.level;
  32048. const newDetails = data.details;
  32049. const duration = newDetails.totalduration;
  32050. if (!levels) {
  32051. this.warn(`Levels were reset while loading level ${newLevelId}`);
  32052. return;
  32053. }
  32054. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  32055. const curLevel = data.levelInfo;
  32056. const fragCurrent = this.fragCurrent;
  32057. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  32058. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  32059. this.abortCurrentFrag();
  32060. }
  32061. }
  32062. let sliding = 0;
  32063. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  32064. var _this$levelLastLoaded;
  32065. this.checkLiveUpdate(newDetails);
  32066. if (newDetails.deltaUpdateFailed) {
  32067. return;
  32068. }
  32069. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  32070. }
  32071. // override level info
  32072. curLevel.details = newDetails;
  32073. this.levelLastLoaded = curLevel;
  32074. if (!startFragRequested) {
  32075. this.setStartPosition(newDetails, sliding);
  32076. }
  32077. this.hls.trigger(Events.LEVEL_UPDATED, {
  32078. details: newDetails,
  32079. level: newLevelId
  32080. });
  32081. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  32082. if (this.state === State.WAITING_LEVEL) {
  32083. if (this.waitForCdnTuneIn(newDetails)) {
  32084. // Wait for Low-Latency CDN Tune-in
  32085. return;
  32086. }
  32087. this.state = State.IDLE;
  32088. }
  32089. if (startFragRequested && newDetails.live) {
  32090. this.synchronizeToLiveEdge(newDetails);
  32091. }
  32092. // trigger handler right now
  32093. this.tick();
  32094. }
  32095. synchronizeToLiveEdge(levelDetails) {
  32096. const {
  32097. config,
  32098. media
  32099. } = this;
  32100. if (!media) {
  32101. return;
  32102. }
  32103. const liveSyncPosition = this.hls.liveSyncPosition;
  32104. const currentTime = this.getLoadPosition();
  32105. const start = levelDetails.fragmentStart;
  32106. const end = levelDetails.edge;
  32107. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  32108. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  32109. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  32110. // Continue if buffer is starving or if current time is behind max latency
  32111. const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  32112. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  32113. if (!this._hasEnoughToStart) {
  32114. this.nextLoadPosition = liveSyncPosition;
  32115. }
  32116. // Only seek if ready and there is not a significant forward buffer available for playback
  32117. if (media.readyState) {
  32118. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  32119. if (this.config.liveSyncMode === 'buffered') {
  32120. var _bufferInfo$buffered;
  32121. const bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  32122. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  32123. media.currentTime = liveSyncPosition;
  32124. return;
  32125. }
  32126. const isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  32127. if (isLiveSyncInBuffer) {
  32128. media.currentTime = liveSyncPosition;
  32129. return;
  32130. }
  32131. const {
  32132. nextStart
  32133. } = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0);
  32134. if (nextStart) {
  32135. media.currentTime = nextStart;
  32136. }
  32137. } else {
  32138. media.currentTime = liveSyncPosition;
  32139. }
  32140. }
  32141. }
  32142. }
  32143. }
  32144. _handleFragmentLoadProgress(data) {
  32145. var _frag$initSegment;
  32146. const frag = data.frag;
  32147. const {
  32148. part,
  32149. payload
  32150. } = data;
  32151. const {
  32152. levels
  32153. } = this;
  32154. if (!levels) {
  32155. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  32156. return;
  32157. }
  32158. const currentLevel = levels[frag.level];
  32159. if (!currentLevel) {
  32160. this.warn(`Level ${frag.level} not found on progress`);
  32161. return;
  32162. }
  32163. const details = currentLevel.details;
  32164. if (!details) {
  32165. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  32166. this.fragmentTracker.removeFragment(frag);
  32167. return;
  32168. }
  32169. const videoCodec = currentLevel.videoCodec;
  32170. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  32171. const accurateTimeOffset = details.PTSKnown || !details.live;
  32172. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  32173. const audioCodec = this._getAudioCodec(currentLevel);
  32174. // transmux the MPEG-TS data to ISO-BMFF segments
  32175. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  32176. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  32177. const partIndex = part ? part.index : -1;
  32178. const partial = partIndex !== -1;
  32179. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  32180. const initPTS = this.initPTS[frag.cc];
  32181. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  32182. }
  32183. onAudioTrackSwitching(event, data) {
  32184. const hls = this.hls;
  32185. // if any URL found on new audio track, it is an alternate audio track
  32186. const fromAltAudio = this.altAudio === 2;
  32187. const altAudio = useAlternateAudio(data.url, hls);
  32188. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  32189. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  32190. // we will just have to change buffer scheduling on audioTrackSwitched
  32191. if (!altAudio) {
  32192. if (this.mediaBuffer !== this.media) {
  32193. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  32194. this.mediaBuffer = this.media;
  32195. const fragCurrent = this.fragCurrent;
  32196. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  32197. if (fragCurrent) {
  32198. this.log('Switching to main audio track, cancel main fragment load');
  32199. fragCurrent.abortRequests();
  32200. this.fragmentTracker.removeFragment(fragCurrent);
  32201. }
  32202. // destroy transmuxer to force init segment generation (following audio switch)
  32203. this.resetTransmuxer();
  32204. // switch to IDLE state to load new fragment
  32205. this.resetLoadingState();
  32206. } else if (this.audioOnly) {
  32207. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  32208. this.resetTransmuxer();
  32209. }
  32210. // If switching from alt to main audio, flush all audio and trigger track switched
  32211. if (fromAltAudio) {
  32212. this.fragmentTracker.removeAllFragments();
  32213. hls.once(Events.BUFFER_FLUSHED, () => {
  32214. var _this$hls;
  32215. (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  32216. });
  32217. hls.trigger(Events.BUFFER_FLUSHING, {
  32218. startOffset: 0,
  32219. endOffset: Number.POSITIVE_INFINITY,
  32220. type: null
  32221. });
  32222. return;
  32223. }
  32224. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  32225. } else {
  32226. this.altAudio = 1;
  32227. }
  32228. }
  32229. onAudioTrackSwitched(event, data) {
  32230. const altAudio = useAlternateAudio(data.url, this.hls);
  32231. if (altAudio) {
  32232. const videoBuffer = this.videoBuffer;
  32233. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  32234. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  32235. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  32236. this.mediaBuffer = videoBuffer;
  32237. }
  32238. }
  32239. this.altAudio = altAudio ? 2 : 0;
  32240. this.tick();
  32241. }
  32242. onBufferCreated(event, data) {
  32243. const tracks = data.tracks;
  32244. let mediaTrack;
  32245. let name;
  32246. let alternate = false;
  32247. for (const type in tracks) {
  32248. const track = tracks[type];
  32249. if (track.id === 'main') {
  32250. name = type;
  32251. mediaTrack = track;
  32252. // keep video source buffer reference
  32253. if (type === 'video') {
  32254. const videoTrack = tracks[type];
  32255. if (videoTrack) {
  32256. this.videoBuffer = videoTrack.buffer;
  32257. }
  32258. }
  32259. } else {
  32260. alternate = true;
  32261. }
  32262. }
  32263. if (alternate && mediaTrack) {
  32264. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  32265. this.mediaBuffer = mediaTrack.buffer;
  32266. } else {
  32267. this.mediaBuffer = this.media;
  32268. }
  32269. }
  32270. onFragBuffered(event, data) {
  32271. const {
  32272. frag,
  32273. part
  32274. } = data;
  32275. const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  32276. if (bufferedMainFragment) {
  32277. if (this.fragContextChanged(frag)) {
  32278. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  32279. // Avoid setting state back to IDLE, since that will interfere with a level switch
  32280. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  32281. if (this.state === State.PARSED) {
  32282. this.state = State.IDLE;
  32283. }
  32284. return;
  32285. }
  32286. const stats = part ? part.stats : frag.stats;
  32287. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  32288. if (isMediaFragment(frag)) {
  32289. this.fragPrevious = frag;
  32290. }
  32291. this.fragBufferedComplete(frag, part);
  32292. }
  32293. const media = this.media;
  32294. if (!media) {
  32295. return;
  32296. }
  32297. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  32298. this._hasEnoughToStart = true;
  32299. this.seekToStartPos();
  32300. }
  32301. if (bufferedMainFragment) {
  32302. this.tick();
  32303. }
  32304. }
  32305. get hasEnoughToStart() {
  32306. return this._hasEnoughToStart;
  32307. }
  32308. onError(event, data) {
  32309. var _data$context;
  32310. if (data.fatal) {
  32311. this.state = State.ERROR;
  32312. return;
  32313. }
  32314. switch (data.details) {
  32315. case ErrorDetails.FRAG_GAP:
  32316. case ErrorDetails.FRAG_PARSING_ERROR:
  32317. case ErrorDetails.FRAG_DECRYPT_ERROR:
  32318. case ErrorDetails.FRAG_LOAD_ERROR:
  32319. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  32320. case ErrorDetails.KEY_LOAD_ERROR:
  32321. case ErrorDetails.KEY_LOAD_TIMEOUT:
  32322. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  32323. break;
  32324. case ErrorDetails.LEVEL_LOAD_ERROR:
  32325. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  32326. case ErrorDetails.LEVEL_PARSING_ERROR:
  32327. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  32328. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  32329. this.state = State.IDLE;
  32330. }
  32331. break;
  32332. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  32333. case ErrorDetails.BUFFER_APPEND_ERROR:
  32334. if (data.parent !== 'main') {
  32335. return;
  32336. }
  32337. if (this.reduceLengthAndFlushBuffer(data)) {
  32338. this.resetLoadingState();
  32339. }
  32340. break;
  32341. case ErrorDetails.BUFFER_FULL_ERROR:
  32342. if (data.parent !== 'main') {
  32343. return;
  32344. }
  32345. if (this.reduceLengthAndFlushBuffer(data)) {
  32346. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  32347. }
  32348. break;
  32349. case ErrorDetails.INTERNAL_EXCEPTION:
  32350. this.recoverWorkerError(data);
  32351. break;
  32352. }
  32353. }
  32354. onFragLoadEmergencyAborted() {
  32355. this.state = State.IDLE;
  32356. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  32357. // in that case, reset startFragRequested flag
  32358. if (!this._hasEnoughToStart) {
  32359. this.startFragRequested = false;
  32360. this.nextLoadPosition = this.lastCurrentTime;
  32361. }
  32362. this.tickImmediate();
  32363. }
  32364. onBufferFlushed(event, {
  32365. type
  32366. }) {
  32367. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  32368. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  32369. if (mediaBuffer) {
  32370. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  32371. this.tick();
  32372. }
  32373. }
  32374. }
  32375. onLevelsUpdated(event, data) {
  32376. if (this.level > -1 && this.fragCurrent) {
  32377. this.level = this.fragCurrent.level;
  32378. if (this.level === -1) {
  32379. this.resetWhenMissingContext(this.fragCurrent);
  32380. }
  32381. }
  32382. this.levels = data.levels;
  32383. }
  32384. swapAudioCodec() {
  32385. this.audioCodecSwap = !this.audioCodecSwap;
  32386. }
  32387. /**
  32388. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  32389. */
  32390. seekToStartPos() {
  32391. const {
  32392. media
  32393. } = this;
  32394. if (!media) {
  32395. return;
  32396. }
  32397. const currentTime = media.currentTime;
  32398. let startPosition = this.startPosition;
  32399. // only adjust currentTime if different from startPosition or if startPosition not buffered
  32400. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  32401. if (startPosition >= 0 && currentTime < startPosition) {
  32402. if (media.seeking) {
  32403. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  32404. return;
  32405. }
  32406. // Offset start position by timeline offset
  32407. const timelineOffset = this.timelineOffset;
  32408. if (timelineOffset && startPosition) {
  32409. startPosition += timelineOffset;
  32410. }
  32411. const details = this.getLevelDetails();
  32412. const buffered = BufferHelper.getBuffered(media);
  32413. const bufferStart = buffered.length ? buffered.start(0) : 0;
  32414. const delta = bufferStart - startPosition;
  32415. const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  32416. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  32417. this.log(`adjusting start position by ${delta} to match buffer start`);
  32418. startPosition += delta;
  32419. this.startPosition = startPosition;
  32420. }
  32421. if (currentTime < startPosition) {
  32422. this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);
  32423. media.currentTime = startPosition;
  32424. }
  32425. }
  32426. }
  32427. _getAudioCodec(currentLevel) {
  32428. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  32429. if (this.audioCodecSwap && audioCodec) {
  32430. this.log('Swapping audio codec');
  32431. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  32432. audioCodec = 'mp4a.40.2';
  32433. } else {
  32434. audioCodec = 'mp4a.40.5';
  32435. }
  32436. }
  32437. return audioCodec;
  32438. }
  32439. _loadBitrateTestFrag(fragment, level) {
  32440. fragment.bitrateTest = true;
  32441. this._doFragLoad(fragment, level).then(data => {
  32442. const {
  32443. hls
  32444. } = this;
  32445. const frag = data == null ? void 0 : data.frag;
  32446. if (!frag || this.fragContextChanged(frag)) {
  32447. return;
  32448. }
  32449. level.fragmentError = 0;
  32450. this.state = State.IDLE;
  32451. this.startFragRequested = false;
  32452. this.bitrateTest = false;
  32453. const stats = frag.stats;
  32454. // Bitrate tests fragments are neither parsed nor buffered
  32455. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  32456. hls.trigger(Events.FRAG_LOADED, data);
  32457. frag.bitrateTest = false;
  32458. });
  32459. }
  32460. _handleTransmuxComplete(transmuxResult) {
  32461. var _id3$samples;
  32462. const id = this.playlistType;
  32463. const {
  32464. hls
  32465. } = this;
  32466. const {
  32467. remuxResult,
  32468. chunkMeta
  32469. } = transmuxResult;
  32470. const context = this.getCurrentContext(chunkMeta);
  32471. if (!context) {
  32472. this.resetWhenMissingContext(chunkMeta);
  32473. return;
  32474. }
  32475. const {
  32476. frag,
  32477. part,
  32478. level
  32479. } = context;
  32480. const {
  32481. video,
  32482. text,
  32483. id3,
  32484. initSegment
  32485. } = remuxResult;
  32486. const {
  32487. details
  32488. } = level;
  32489. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  32490. const audio = this.altAudio ? undefined : remuxResult.audio;
  32491. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  32492. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  32493. if (this.fragContextChanged(frag)) {
  32494. this.fragmentTracker.removeFragment(frag);
  32495. return;
  32496. }
  32497. this.state = State.PARSING;
  32498. if (initSegment) {
  32499. if (initSegment != null && initSegment.tracks) {
  32500. const mapFragment = frag.initSegment || frag;
  32501. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  32502. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  32503. frag: mapFragment,
  32504. id,
  32505. tracks: initSegment.tracks
  32506. });
  32507. }
  32508. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  32509. const baseTime = initSegment.initPTS;
  32510. const timescale = initSegment.timescale;
  32511. const initPTS = this.initPTS[frag.cc];
  32512. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  32513. this.initPTS[frag.cc] = {
  32514. baseTime,
  32515. timescale
  32516. };
  32517. hls.trigger(Events.INIT_PTS_FOUND, {
  32518. frag,
  32519. id,
  32520. initPTS: baseTime,
  32521. timescale
  32522. });
  32523. }
  32524. }
  32525. // Avoid buffering if backtracking this fragment
  32526. if (video && details) {
  32527. if (audio && video.type === 'audiovideo') {
  32528. this.logMuxedErr(frag);
  32529. }
  32530. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  32531. const isFirstFragment = frag.sn === details.startSN;
  32532. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  32533. if (remuxResult.independent !== false) {
  32534. const {
  32535. startPTS,
  32536. endPTS,
  32537. startDTS,
  32538. endDTS
  32539. } = video;
  32540. if (part) {
  32541. part.elementaryStreams[video.type] = {
  32542. startPTS,
  32543. endPTS,
  32544. startDTS,
  32545. endDTS
  32546. };
  32547. } else {
  32548. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  32549. this.couldBacktrack = true;
  32550. }
  32551. if (video.dropped && video.independent) {
  32552. // Backtrack if dropped frames create a gap after currentTime
  32553. const bufferInfo = this.getMainFwdBufferInfo();
  32554. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  32555. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  32556. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  32557. this.backtrack(frag);
  32558. return;
  32559. } else if (isFirstInDiscontinuity) {
  32560. // Mark segment with a gap to avoid loop loading
  32561. frag.gap = true;
  32562. }
  32563. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  32564. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  32565. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  32566. // Mark segment with a gap to skip large start gap
  32567. frag.gap = true;
  32568. }
  32569. }
  32570. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  32571. if (this.backtrackFragment) {
  32572. this.backtrackFragment = frag;
  32573. }
  32574. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  32575. } else if (isFirstFragment || isFirstInDiscontinuity) {
  32576. // Mark segment with a gap to avoid loop loading
  32577. frag.gap = true;
  32578. } else {
  32579. this.backtrack(frag);
  32580. return;
  32581. }
  32582. }
  32583. if (audio) {
  32584. const {
  32585. startPTS,
  32586. endPTS,
  32587. startDTS,
  32588. endDTS
  32589. } = audio;
  32590. if (part) {
  32591. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  32592. startPTS,
  32593. endPTS,
  32594. startDTS,
  32595. endDTS
  32596. };
  32597. }
  32598. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  32599. this.bufferFragmentData(audio, frag, part, chunkMeta);
  32600. }
  32601. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  32602. const emittedID3 = {
  32603. id,
  32604. frag,
  32605. details,
  32606. samples: id3.samples
  32607. };
  32608. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  32609. }
  32610. if (details && text) {
  32611. const emittedText = {
  32612. id,
  32613. frag,
  32614. details,
  32615. samples: text.samples
  32616. };
  32617. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  32618. }
  32619. }
  32620. logMuxedErr(frag) {
  32621. this.warn(`${isMediaFragment(frag) ? 'Media' : 'Init'} segment with muxed audiovideo where only video expected: ${frag.url}`);
  32622. }
  32623. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  32624. if (this.state !== State.PARSING) {
  32625. return;
  32626. }
  32627. this.audioOnly = !!tracks.audio && !tracks.video;
  32628. // if audio track is expected to come from audio stream controller, discard any coming from main
  32629. if (this.altAudio && !this.audioOnly) {
  32630. delete tracks.audio;
  32631. if (tracks.audiovideo) {
  32632. this.logMuxedErr(frag);
  32633. }
  32634. }
  32635. // include levelCodec in audio and video tracks
  32636. const {
  32637. audio,
  32638. video,
  32639. audiovideo
  32640. } = tracks;
  32641. if (audio) {
  32642. const levelCodec = currentLevel.audioCodec;
  32643. let audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  32644. // Add level and profile to make up for remuxer not being able to parse full codec
  32645. // (logger warning "Unhandled audio codec...")
  32646. if (audioCodec === 'mp4a') {
  32647. audioCodec = 'mp4a.40.5';
  32648. }
  32649. // Handle `audioCodecSwitch`
  32650. const ua = navigator.userAgent.toLowerCase();
  32651. if (this.audioCodecSwitch) {
  32652. if (audioCodec) {
  32653. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  32654. audioCodec = 'mp4a.40.2';
  32655. } else {
  32656. audioCodec = 'mp4a.40.5';
  32657. }
  32658. }
  32659. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  32660. // force HE-AAC, as it seems that most browsers prefers it.
  32661. // don't force HE-AAC if mono stream, or in Firefox
  32662. const audioMetadata = audio.metadata;
  32663. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  32664. audioCodec = 'mp4a.40.5';
  32665. }
  32666. }
  32667. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  32668. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  32669. // Exclude mpeg audio
  32670. audioCodec = 'mp4a.40.2';
  32671. this.log(`Android: force audio codec to ${audioCodec}`);
  32672. }
  32673. if (levelCodec && levelCodec !== audioCodec) {
  32674. this.log(`Swapping manifest audio codec "${levelCodec}" for "${audioCodec}"`);
  32675. }
  32676. audio.levelCodec = audioCodec;
  32677. audio.id = PlaylistLevelType.MAIN;
  32678. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${levelCodec || ''}/${audio.codec}]`);
  32679. delete tracks.audiovideo;
  32680. }
  32681. if (video) {
  32682. video.levelCodec = currentLevel.videoCodec;
  32683. video.id = PlaylistLevelType.MAIN;
  32684. const parsedVideoCodec = video.codec;
  32685. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  32686. // Make up for passthrough-remuxer not being able to parse full codec
  32687. // (logger warning "Unhandled video codec...")
  32688. switch (parsedVideoCodec) {
  32689. case 'hvc1':
  32690. case 'hev1':
  32691. video.codec = 'hvc1.1.6.L120.90';
  32692. break;
  32693. case 'av01':
  32694. video.codec = 'av01.0.04M.08';
  32695. break;
  32696. case 'avc1':
  32697. video.codec = 'avc1.42e01e';
  32698. break;
  32699. }
  32700. }
  32701. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${parsedVideoCodec}]${video.codec !== parsedVideoCodec ? ' parsed-corrected=' + video.codec : ''}${video.supplemental ? ' supplemental=' + video.supplemental : ''}`);
  32702. delete tracks.audiovideo;
  32703. }
  32704. if (audiovideo) {
  32705. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  32706. delete tracks.video;
  32707. delete tracks.audio;
  32708. }
  32709. const trackTypes = Object.keys(tracks);
  32710. if (trackTypes.length) {
  32711. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  32712. if (!this.hls) {
  32713. // Exit after fatal tracks error
  32714. return;
  32715. }
  32716. // loop through tracks that are going to be provided to bufferController
  32717. trackTypes.forEach(trackName => {
  32718. const track = tracks[trackName];
  32719. const initSegment = track.initSegment;
  32720. if (initSegment != null && initSegment.byteLength) {
  32721. this.hls.trigger(Events.BUFFER_APPENDING, {
  32722. type: trackName,
  32723. data: initSegment,
  32724. frag,
  32725. part: null,
  32726. chunkMeta,
  32727. parent: frag.type
  32728. });
  32729. }
  32730. });
  32731. }
  32732. // trigger handler right now
  32733. this.tickImmediate();
  32734. }
  32735. getMainFwdBufferInfo() {
  32736. // Observe video SourceBuffer (this.mediaBuffer) only when alt-audio is used, otherwise observe combined media buffer
  32737. const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  32738. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  32739. }
  32740. get maxBufferLength() {
  32741. const {
  32742. levels,
  32743. level
  32744. } = this;
  32745. const levelInfo = levels == null ? void 0 : levels[level];
  32746. if (!levelInfo) {
  32747. return this.config.maxBufferLength;
  32748. }
  32749. return this.getMaxBufferLength(levelInfo.maxBitrate);
  32750. }
  32751. backtrack(frag) {
  32752. this.couldBacktrack = true;
  32753. // Causes findFragments to backtrack through fragments to find the keyframe
  32754. this.backtrackFragment = frag;
  32755. this.resetTransmuxer();
  32756. this.flushBufferGap(frag);
  32757. this.fragmentTracker.removeFragment(frag);
  32758. this.fragPrevious = null;
  32759. this.nextLoadPosition = frag.start;
  32760. this.state = State.IDLE;
  32761. }
  32762. checkFragmentChanged() {
  32763. const video = this.media;
  32764. let fragPlayingCurrent = null;
  32765. if (video && video.readyState > 1 && video.seeking === false) {
  32766. const currentTime = video.currentTime;
  32767. /* if video element is in seeked state, currentTime can only increase.
  32768. (assuming that playback rate is positive ...)
  32769. As sometimes currentTime jumps back to zero after a
  32770. media decode error, check this, to avoid seeking back to
  32771. wrong position after a media decode error
  32772. */
  32773. if (BufferHelper.isBuffered(video, currentTime)) {
  32774. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  32775. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  32776. /* ensure that FRAG_CHANGED event is triggered at startup,
  32777. when first video frame is displayed and playback is paused.
  32778. add a tolerance of 100ms, in case current position is not buffered,
  32779. check if current pos+100ms is buffered and use that buffer range
  32780. for FRAG_CHANGED event reporting */
  32781. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  32782. }
  32783. if (fragPlayingCurrent) {
  32784. this.backtrackFragment = null;
  32785. const fragPlaying = this.fragPlaying;
  32786. const fragCurrentLevel = fragPlayingCurrent.level;
  32787. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  32788. this.fragPlaying = fragPlayingCurrent;
  32789. this.hls.trigger(Events.FRAG_CHANGED, {
  32790. frag: fragPlayingCurrent
  32791. });
  32792. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  32793. this.hls.trigger(Events.LEVEL_SWITCHED, {
  32794. level: fragCurrentLevel
  32795. });
  32796. }
  32797. }
  32798. }
  32799. }
  32800. }
  32801. get nextLevel() {
  32802. const frag = this.nextBufferedFrag;
  32803. if (frag) {
  32804. return frag.level;
  32805. }
  32806. return -1;
  32807. }
  32808. get currentFrag() {
  32809. var _this$media3;
  32810. if (this.fragPlaying) {
  32811. return this.fragPlaying;
  32812. }
  32813. const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  32814. if (isFiniteNumber(currentTime)) {
  32815. return this.getAppendedFrag(currentTime);
  32816. }
  32817. return null;
  32818. }
  32819. get currentProgramDateTime() {
  32820. var _this$media4;
  32821. const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  32822. if (isFiniteNumber(currentTime)) {
  32823. const details = this.getLevelDetails();
  32824. const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  32825. if (frag) {
  32826. const programDateTime = frag.programDateTime;
  32827. if (programDateTime !== null) {
  32828. const epocMs = programDateTime + (currentTime - frag.start) * 1000;
  32829. return new Date(epocMs);
  32830. }
  32831. }
  32832. }
  32833. return null;
  32834. }
  32835. get currentLevel() {
  32836. const frag = this.currentFrag;
  32837. if (frag) {
  32838. return frag.level;
  32839. }
  32840. return -1;
  32841. }
  32842. get nextBufferedFrag() {
  32843. const frag = this.currentFrag;
  32844. if (frag) {
  32845. return this.followingBufferedFrag(frag);
  32846. }
  32847. return null;
  32848. }
  32849. get forceStartLoad() {
  32850. return this._forceStartLoad;
  32851. }
  32852. }
  32853. class KeyLoader {
  32854. constructor(config) {
  32855. this.config = void 0;
  32856. this.keyUriToKeyInfo = {};
  32857. this.emeController = null;
  32858. this.config = config;
  32859. }
  32860. abort(type) {
  32861. for (const uri in this.keyUriToKeyInfo) {
  32862. const loader = this.keyUriToKeyInfo[uri].loader;
  32863. if (loader) {
  32864. var _loader$context;
  32865. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  32866. return;
  32867. }
  32868. loader.abort();
  32869. }
  32870. }
  32871. }
  32872. detach() {
  32873. for (const uri in this.keyUriToKeyInfo) {
  32874. const keyInfo = this.keyUriToKeyInfo[uri];
  32875. // Remove cached EME keys on detach
  32876. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  32877. delete this.keyUriToKeyInfo[uri];
  32878. }
  32879. }
  32880. }
  32881. destroy() {
  32882. this.detach();
  32883. for (const uri in this.keyUriToKeyInfo) {
  32884. const loader = this.keyUriToKeyInfo[uri].loader;
  32885. if (loader) {
  32886. loader.destroy();
  32887. }
  32888. }
  32889. this.keyUriToKeyInfo = {};
  32890. }
  32891. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  32892. return new LoadError({
  32893. type: ErrorTypes.NETWORK_ERROR,
  32894. details,
  32895. fatal: false,
  32896. frag,
  32897. response,
  32898. error,
  32899. networkDetails
  32900. });
  32901. }
  32902. loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  32903. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  32904. // Access key-system with nearest key on start (loading frag is unencrypted)
  32905. if (encryptedFragments.length) {
  32906. for (let i = 0, l = encryptedFragments.length; i < l; i++) {
  32907. const frag = encryptedFragments[i];
  32908. // Loading at or before segment with EXT-X-KEY, or first frag loading and last EXT-X-KEY
  32909. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  32910. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  32911. if (!this.emeController) {
  32912. return;
  32913. }
  32914. frag.setKeyFormat(keySystemFormat);
  32915. const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  32916. if (keySystem) {
  32917. return this.emeController.getKeySystemAccess([keySystem]);
  32918. }
  32919. });
  32920. }
  32921. }
  32922. }
  32923. if (this.config.requireKeySystemAccessOnStart) {
  32924. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  32925. if (keySystemsInConfig.length) {
  32926. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  32927. }
  32928. }
  32929. }
  32930. return null;
  32931. }
  32932. load(frag) {
  32933. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  32934. // Multiple keys, but none selected, resolve in eme-controller
  32935. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  32936. return this.loadInternal(frag, keySystemFormat);
  32937. });
  32938. }
  32939. return this.loadInternal(frag);
  32940. }
  32941. loadInternal(frag, keySystemFormat) {
  32942. var _keyInfo, _keyInfo2;
  32943. if (keySystemFormat) {
  32944. frag.setKeyFormat(keySystemFormat);
  32945. }
  32946. const decryptdata = frag.decryptdata;
  32947. if (!decryptdata) {
  32948. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');
  32949. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  32950. }
  32951. const uri = decryptdata.uri;
  32952. if (!uri) {
  32953. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  32954. }
  32955. let keyInfo = this.keyUriToKeyInfo[uri];
  32956. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  32957. decryptdata.key = keyInfo.decryptdata.key;
  32958. return Promise.resolve({
  32959. frag,
  32960. keyInfo
  32961. });
  32962. }
  32963. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  32964. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  32965. var _keyInfo$mediaKeySess;
  32966. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  32967. case undefined:
  32968. case 'status-pending':
  32969. case 'usable':
  32970. case 'usable-in-future':
  32971. return keyInfo.keyLoadPromise.then(keyLoadedData => {
  32972. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  32973. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  32974. return {
  32975. frag,
  32976. keyInfo
  32977. };
  32978. });
  32979. }
  32980. // If we have a key session and status and it is not pending or usable, continue
  32981. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  32982. }
  32983. // Load the key or return the loading promise
  32984. keyInfo = this.keyUriToKeyInfo[uri] = {
  32985. decryptdata,
  32986. keyLoadPromise: null,
  32987. loader: null,
  32988. mediaKeySessionContext: null
  32989. };
  32990. switch (decryptdata.method) {
  32991. case 'ISO-23001-7':
  32992. case 'SAMPLE-AES':
  32993. case 'SAMPLE-AES-CENC':
  32994. case 'SAMPLE-AES-CTR':
  32995. if (decryptdata.keyFormat === 'identity') {
  32996. // loadKeyHTTP handles http(s) and data URLs
  32997. return this.loadKeyHTTP(keyInfo, frag);
  32998. }
  32999. return this.loadKeyEME(keyInfo, frag);
  33000. case 'AES-128':
  33001. case 'AES-256':
  33002. case 'AES-256-CTR':
  33003. return this.loadKeyHTTP(keyInfo, frag);
  33004. default:
  33005. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  33006. }
  33007. }
  33008. loadKeyEME(keyInfo, frag) {
  33009. const keyLoadedData = {
  33010. frag,
  33011. keyInfo
  33012. };
  33013. if (this.emeController && this.config.emeEnabled) {
  33014. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  33015. if (keySessionContextPromise) {
  33016. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {
  33017. keyInfo.mediaKeySessionContext = keySessionContext;
  33018. return keyLoadedData;
  33019. })).catch(error => {
  33020. // Remove promise for license renewal or retry
  33021. keyInfo.keyLoadPromise = null;
  33022. throw error;
  33023. });
  33024. }
  33025. }
  33026. return Promise.resolve(keyLoadedData);
  33027. }
  33028. loadKeyHTTP(keyInfo, frag) {
  33029. const config = this.config;
  33030. const Loader = config.loader;
  33031. const keyLoader = new Loader(config);
  33032. frag.keyLoader = keyInfo.loader = keyLoader;
  33033. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  33034. const loaderContext = {
  33035. keyInfo,
  33036. frag,
  33037. responseType: 'arraybuffer',
  33038. url: keyInfo.decryptdata.uri
  33039. };
  33040. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  33041. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  33042. // this will also align retry logic with fragment-loader
  33043. const loadPolicy = config.keyLoadPolicy.default;
  33044. const loaderConfig = {
  33045. loadPolicy,
  33046. timeout: loadPolicy.maxLoadTimeMs,
  33047. maxRetry: 0,
  33048. retryDelay: 0,
  33049. maxRetryDelay: 0
  33050. };
  33051. const loaderCallbacks = {
  33052. onSuccess: (response, stats, context, networkDetails) => {
  33053. const {
  33054. frag,
  33055. keyInfo,
  33056. url: uri
  33057. } = context;
  33058. if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {
  33059. return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  33060. }
  33061. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  33062. // detach fragment key loader on load success
  33063. frag.keyLoader = null;
  33064. keyInfo.loader = null;
  33065. resolve({
  33066. frag,
  33067. keyInfo
  33068. });
  33069. },
  33070. onError: (response, context, networkDetails, stats) => {
  33071. this.resetLoader(context);
  33072. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  33073. url: loaderContext.url,
  33074. data: undefined
  33075. }, response)));
  33076. },
  33077. onTimeout: (stats, context, networkDetails) => {
  33078. this.resetLoader(context);
  33079. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  33080. },
  33081. onAbort: (stats, context, networkDetails) => {
  33082. this.resetLoader(context);
  33083. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  33084. }
  33085. };
  33086. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  33087. });
  33088. }
  33089. resetLoader(context) {
  33090. const {
  33091. frag,
  33092. keyInfo,
  33093. url: uri
  33094. } = context;
  33095. const loader = keyInfo.loader;
  33096. if (frag.keyLoader === loader) {
  33097. frag.keyLoader = null;
  33098. keyInfo.loader = null;
  33099. }
  33100. delete this.keyUriToKeyInfo[uri];
  33101. if (loader) {
  33102. loader.destroy();
  33103. }
  33104. }
  33105. }
  33106. function mapContextToLevelType(context) {
  33107. const {
  33108. type
  33109. } = context;
  33110. switch (type) {
  33111. case PlaylistContextType.AUDIO_TRACK:
  33112. return PlaylistLevelType.AUDIO;
  33113. case PlaylistContextType.SUBTITLE_TRACK:
  33114. return PlaylistLevelType.SUBTITLE;
  33115. default:
  33116. return PlaylistLevelType.MAIN;
  33117. }
  33118. }
  33119. function getResponseUrl(response, context) {
  33120. let url = response.url;
  33121. // responseURL not supported on some browsers (it is used to detect URL redirection)
  33122. // data-uri mode also not supported (but no need to detect redirection)
  33123. if (url === undefined || url.indexOf('data:') === 0) {
  33124. // fallback to initial URL
  33125. url = context.url;
  33126. }
  33127. return url;
  33128. }
  33129. class PlaylistLoader {
  33130. constructor(hls) {
  33131. this.hls = void 0;
  33132. this.loaders = Object.create(null);
  33133. this.variableList = null;
  33134. this.onManifestLoaded = this.checkAutostartLoad;
  33135. this.hls = hls;
  33136. this.registerListeners();
  33137. }
  33138. startLoad(startPosition) {}
  33139. stopLoad() {
  33140. this.destroyInternalLoaders();
  33141. }
  33142. registerListeners() {
  33143. const {
  33144. hls
  33145. } = this;
  33146. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33147. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  33148. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  33149. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  33150. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  33151. }
  33152. unregisterListeners() {
  33153. const {
  33154. hls
  33155. } = this;
  33156. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  33157. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  33158. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  33159. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  33160. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  33161. }
  33162. /**
  33163. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  33164. */
  33165. createInternalLoader(context) {
  33166. const config = this.hls.config;
  33167. const PLoader = config.pLoader;
  33168. const Loader = config.loader;
  33169. const InternalLoader = PLoader || Loader;
  33170. const loader = new InternalLoader(config);
  33171. this.loaders[context.type] = loader;
  33172. return loader;
  33173. }
  33174. getInternalLoader(context) {
  33175. return this.loaders[context.type];
  33176. }
  33177. resetInternalLoader(contextType) {
  33178. if (this.loaders[contextType]) {
  33179. delete this.loaders[contextType];
  33180. }
  33181. }
  33182. /**
  33183. * Call `destroy` on all internal loader instances mapped (one per context type)
  33184. */
  33185. destroyInternalLoaders() {
  33186. for (const contextType in this.loaders) {
  33187. const loader = this.loaders[contextType];
  33188. if (loader) {
  33189. loader.destroy();
  33190. }
  33191. this.resetInternalLoader(contextType);
  33192. }
  33193. }
  33194. destroy() {
  33195. this.variableList = null;
  33196. this.unregisterListeners();
  33197. this.destroyInternalLoaders();
  33198. }
  33199. onManifestLoading(event, data) {
  33200. const {
  33201. url
  33202. } = data;
  33203. this.variableList = null;
  33204. this.load({
  33205. id: null,
  33206. level: 0,
  33207. responseType: 'text',
  33208. type: PlaylistContextType.MANIFEST,
  33209. url,
  33210. deliveryDirectives: null,
  33211. levelOrTrack: null
  33212. });
  33213. }
  33214. onLevelLoading(event, data) {
  33215. const {
  33216. id,
  33217. level,
  33218. pathwayId,
  33219. url,
  33220. deliveryDirectives,
  33221. levelInfo
  33222. } = data;
  33223. this.load({
  33224. id,
  33225. level,
  33226. pathwayId,
  33227. responseType: 'text',
  33228. type: PlaylistContextType.LEVEL,
  33229. url,
  33230. deliveryDirectives,
  33231. levelOrTrack: levelInfo
  33232. });
  33233. }
  33234. onAudioTrackLoading(event, data) {
  33235. const {
  33236. id,
  33237. groupId,
  33238. url,
  33239. deliveryDirectives,
  33240. track
  33241. } = data;
  33242. this.load({
  33243. id,
  33244. groupId,
  33245. level: null,
  33246. responseType: 'text',
  33247. type: PlaylistContextType.AUDIO_TRACK,
  33248. url,
  33249. deliveryDirectives,
  33250. levelOrTrack: track
  33251. });
  33252. }
  33253. onSubtitleTrackLoading(event, data) {
  33254. const {
  33255. id,
  33256. groupId,
  33257. url,
  33258. deliveryDirectives,
  33259. track
  33260. } = data;
  33261. this.load({
  33262. id,
  33263. groupId,
  33264. level: null,
  33265. responseType: 'text',
  33266. type: PlaylistContextType.SUBTITLE_TRACK,
  33267. url,
  33268. deliveryDirectives,
  33269. levelOrTrack: track
  33270. });
  33271. }
  33272. onLevelsUpdated(event, data) {
  33273. // abort and delete loader of removed levels
  33274. const loader = this.loaders[PlaylistContextType.LEVEL];
  33275. if (loader) {
  33276. const context = loader.context;
  33277. if (context && !data.levels.some(lvl => lvl === context.levelOrTrack)) {
  33278. loader.abort();
  33279. delete this.loaders[PlaylistContextType.LEVEL];
  33280. }
  33281. }
  33282. }
  33283. load(context) {
  33284. var _context$deliveryDire;
  33285. const config = this.hls.config;
  33286. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  33287. // Check if a loader for this context already exists
  33288. let loader = this.getInternalLoader(context);
  33289. if (loader) {
  33290. const logger = this.hls.logger;
  33291. const loaderContext = loader.context;
  33292. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  33293. // same URL can't overlap, or wait for blocking request
  33294. if (loaderContext.url === context.url) {
  33295. logger.log(`[playlist-loader]: ignore ${context.url} ongoing request`);
  33296. } else {
  33297. logger.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);
  33298. }
  33299. return;
  33300. }
  33301. logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  33302. loader.abort();
  33303. }
  33304. // apply different configs for retries depending on
  33305. // context (manifest, level, audio/subs playlist)
  33306. let loadPolicy;
  33307. if (context.type === PlaylistContextType.MANIFEST) {
  33308. loadPolicy = config.manifestLoadPolicy.default;
  33309. } else {
  33310. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  33311. timeoutRetry: null,
  33312. errorRetry: null
  33313. });
  33314. }
  33315. loader = this.createInternalLoader(context);
  33316. // Override level/track timeout for LL-HLS requests
  33317. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  33318. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  33319. let levelDetails;
  33320. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  33321. levelDetails = this.hls.levels[context.level].details;
  33322. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  33323. levelDetails = this.hls.audioTracks[context.id].details;
  33324. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  33325. levelDetails = this.hls.subtitleTracks[context.id].details;
  33326. }
  33327. if (levelDetails) {
  33328. const partTarget = levelDetails.partTarget;
  33329. const targetDuration = levelDetails.targetduration;
  33330. if (partTarget && targetDuration) {
  33331. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  33332. loadPolicy = _extends({}, loadPolicy, {
  33333. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  33334. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  33335. });
  33336. }
  33337. }
  33338. }
  33339. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  33340. const loaderConfig = {
  33341. loadPolicy,
  33342. timeout: loadPolicy.maxLoadTimeMs,
  33343. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  33344. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  33345. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  33346. };
  33347. const loaderCallbacks = {
  33348. onSuccess: (response, stats, context, networkDetails) => {
  33349. const loader = this.getInternalLoader(context);
  33350. this.resetInternalLoader(context.type);
  33351. const string = response.data;
  33352. // Validate if it is an M3U8 at all
  33353. if (string.indexOf('#EXTM3U') !== 0) {
  33354. this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  33355. return;
  33356. }
  33357. stats.parsing.start = performance.now();
  33358. if (M3U8Parser.isMediaPlaylist(string) || context.type !== PlaylistContextType.MANIFEST) {
  33359. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  33360. } else {
  33361. this.handleMasterPlaylist(response, stats, context, networkDetails);
  33362. }
  33363. },
  33364. onError: (response, context, networkDetails, stats) => {
  33365. this.handleNetworkError(context, networkDetails, false, response, stats);
  33366. },
  33367. onTimeout: (stats, context, networkDetails) => {
  33368. this.handleNetworkError(context, networkDetails, true, undefined, stats);
  33369. }
  33370. };
  33371. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  33372. loader.load(context, loaderConfig, loaderCallbacks);
  33373. }
  33374. checkAutostartLoad() {
  33375. if (!this.hls) {
  33376. return;
  33377. }
  33378. const {
  33379. config: {
  33380. autoStartLoad,
  33381. startPosition
  33382. },
  33383. forceStartLoad
  33384. } = this.hls;
  33385. if (autoStartLoad || forceStartLoad) {
  33386. this.hls.logger.log(`${autoStartLoad ? 'auto' : 'force'} startLoad with configured startPosition ${startPosition}`);
  33387. this.hls.startLoad(startPosition);
  33388. }
  33389. }
  33390. handleMasterPlaylist(response, stats, context, networkDetails) {
  33391. const hls = this.hls;
  33392. const string = response.data;
  33393. const url = getResponseUrl(response, context);
  33394. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  33395. if (parsedResult.playlistParsingError) {
  33396. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  33397. return;
  33398. }
  33399. const {
  33400. contentSteering,
  33401. levels,
  33402. sessionData,
  33403. sessionKeys,
  33404. startTimeOffset,
  33405. variableList
  33406. } = parsedResult;
  33407. this.variableList = variableList;
  33408. const {
  33409. AUDIO: audioTracks = [],
  33410. SUBTITLES: subtitles,
  33411. 'CLOSED-CAPTIONS': captions
  33412. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  33413. if (audioTracks.length) {
  33414. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  33415. const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);
  33416. // if no embedded audio track defined, but audio codec signaled in quality level,
  33417. // we need to signal this main audio track this could happen with playlists with
  33418. // alt audio rendition in which quality levels (main)
  33419. // contains both audio+video. but with mixed audio track not signaled
  33420. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  33421. this.hls.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  33422. audioTracks.unshift({
  33423. type: 'main',
  33424. name: 'main',
  33425. groupId: 'main',
  33426. default: false,
  33427. autoselect: false,
  33428. forced: false,
  33429. id: -1,
  33430. attrs: new AttrList({}),
  33431. bitrate: 0,
  33432. url: ''
  33433. });
  33434. }
  33435. }
  33436. hls.trigger(Events.MANIFEST_LOADED, {
  33437. levels,
  33438. audioTracks,
  33439. subtitles,
  33440. captions,
  33441. contentSteering,
  33442. url,
  33443. stats,
  33444. networkDetails,
  33445. sessionData,
  33446. sessionKeys,
  33447. startTimeOffset,
  33448. variableList
  33449. });
  33450. }
  33451. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  33452. const hls = this.hls;
  33453. const {
  33454. id,
  33455. level,
  33456. type
  33457. } = context;
  33458. const url = getResponseUrl(response, context);
  33459. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  33460. const levelType = mapContextToLevelType(context);
  33461. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  33462. // We have done our first request (Manifest-type) and receive
  33463. // not a master playlist but a chunk-list (track/level)
  33464. // We fire the manifest-loaded event anyway with the parsed level-details
  33465. // by creating a single-level structure for it.
  33466. if (type === PlaylistContextType.MANIFEST) {
  33467. const singleLevel = {
  33468. attrs: new AttrList({}),
  33469. bitrate: 0,
  33470. details: levelDetails,
  33471. name: '',
  33472. url
  33473. };
  33474. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  33475. hls.trigger(Events.MANIFEST_LOADED, {
  33476. levels: [singleLevel],
  33477. audioTracks: [],
  33478. url,
  33479. stats,
  33480. networkDetails,
  33481. sessionData: null,
  33482. sessionKeys: null,
  33483. contentSteering: null,
  33484. startTimeOffset: null,
  33485. variableList: null
  33486. });
  33487. }
  33488. // save parsing time
  33489. stats.parsing.end = performance.now();
  33490. // extend the context with the new levelDetails property
  33491. context.levelDetails = levelDetails;
  33492. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  33493. }
  33494. handleManifestParsingError(response, context, error, networkDetails, stats) {
  33495. this.hls.trigger(Events.ERROR, {
  33496. type: ErrorTypes.NETWORK_ERROR,
  33497. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  33498. fatal: context.type === PlaylistContextType.MANIFEST,
  33499. url: response.url,
  33500. err: error,
  33501. error,
  33502. reason: error.message,
  33503. response,
  33504. context,
  33505. networkDetails,
  33506. stats
  33507. });
  33508. }
  33509. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  33510. let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;
  33511. if (context.type === PlaylistContextType.LEVEL) {
  33512. message += `: ${context.level} id: ${context.id}`;
  33513. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  33514. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  33515. }
  33516. const error = new Error(message);
  33517. this.hls.logger.warn(`[playlist-loader]: ${message}`);
  33518. let details = ErrorDetails.UNKNOWN;
  33519. let fatal = false;
  33520. const loader = this.getInternalLoader(context);
  33521. switch (context.type) {
  33522. case PlaylistContextType.MANIFEST:
  33523. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  33524. fatal = true;
  33525. break;
  33526. case PlaylistContextType.LEVEL:
  33527. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  33528. fatal = false;
  33529. break;
  33530. case PlaylistContextType.AUDIO_TRACK:
  33531. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  33532. fatal = false;
  33533. break;
  33534. case PlaylistContextType.SUBTITLE_TRACK:
  33535. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  33536. fatal = false;
  33537. break;
  33538. }
  33539. if (loader) {
  33540. this.resetInternalLoader(context.type);
  33541. }
  33542. const errorData = {
  33543. type: ErrorTypes.NETWORK_ERROR,
  33544. details,
  33545. fatal,
  33546. url: context.url,
  33547. loader,
  33548. context,
  33549. error,
  33550. networkDetails,
  33551. stats
  33552. };
  33553. if (response) {
  33554. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  33555. errorData.response = _objectSpread2({
  33556. url,
  33557. data: undefined
  33558. }, response);
  33559. }
  33560. this.hls.trigger(Events.ERROR, errorData);
  33561. }
  33562. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  33563. const hls = this.hls;
  33564. const {
  33565. type,
  33566. level,
  33567. id,
  33568. groupId,
  33569. deliveryDirectives
  33570. } = context;
  33571. const url = getResponseUrl(response, context);
  33572. const parent = mapContextToLevelType(context);
  33573. const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  33574. if (!levelDetails.fragments.length) {
  33575. const _error = levelDetails.playlistParsingError = new Error('No Segments found in Playlist');
  33576. hls.trigger(Events.ERROR, {
  33577. type: ErrorTypes.NETWORK_ERROR,
  33578. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  33579. fatal: false,
  33580. url,
  33581. error: _error,
  33582. reason: _error.message,
  33583. response,
  33584. context,
  33585. level: levelIndex,
  33586. parent,
  33587. networkDetails,
  33588. stats
  33589. });
  33590. return;
  33591. }
  33592. if (!levelDetails.targetduration) {
  33593. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  33594. }
  33595. const error = levelDetails.playlistParsingError;
  33596. if (error) {
  33597. this.hls.logger.warn(error);
  33598. if (!hls.config.ignorePlaylistParsingErrors) {
  33599. hls.trigger(Events.ERROR, {
  33600. type: ErrorTypes.NETWORK_ERROR,
  33601. details: ErrorDetails.LEVEL_PARSING_ERROR,
  33602. fatal: false,
  33603. url,
  33604. error,
  33605. reason: error.message,
  33606. response,
  33607. context,
  33608. level: levelIndex,
  33609. parent,
  33610. networkDetails,
  33611. stats
  33612. });
  33613. return;
  33614. }
  33615. levelDetails.playlistParsingError = null;
  33616. }
  33617. if (levelDetails.live && loader) {
  33618. if (loader.getCacheAge) {
  33619. levelDetails.ageHeader = loader.getCacheAge() || 0;
  33620. }
  33621. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  33622. levelDetails.ageHeader = 0;
  33623. }
  33624. }
  33625. switch (type) {
  33626. case PlaylistContextType.MANIFEST:
  33627. case PlaylistContextType.LEVEL:
  33628. hls.trigger(Events.LEVEL_LOADED, {
  33629. details: levelDetails,
  33630. levelInfo: context.levelOrTrack || hls.levels[0],
  33631. level: levelIndex || 0,
  33632. id: id || 0,
  33633. stats,
  33634. networkDetails,
  33635. deliveryDirectives,
  33636. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  33637. });
  33638. break;
  33639. case PlaylistContextType.AUDIO_TRACK:
  33640. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  33641. details: levelDetails,
  33642. track: context.levelOrTrack,
  33643. id: id || 0,
  33644. groupId: groupId || '',
  33645. stats,
  33646. networkDetails,
  33647. deliveryDirectives
  33648. });
  33649. break;
  33650. case PlaylistContextType.SUBTITLE_TRACK:
  33651. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  33652. details: levelDetails,
  33653. track: context.levelOrTrack,
  33654. id: id || 0,
  33655. groupId: groupId || '',
  33656. stats,
  33657. networkDetails,
  33658. deliveryDirectives
  33659. });
  33660. break;
  33661. }
  33662. }
  33663. }
  33664. /**
  33665. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  33666. * @public
  33667. */
  33668. class Hls {
  33669. /**
  33670. * Get the video-dev/hls.js package version.
  33671. */
  33672. static get version() {
  33673. return version;
  33674. }
  33675. /**
  33676. * Check if the required MediaSource Extensions are available.
  33677. */
  33678. static isMSESupported() {
  33679. return isMSESupported();
  33680. }
  33681. /**
  33682. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  33683. */
  33684. static isSupported() {
  33685. return isSupported();
  33686. }
  33687. /**
  33688. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  33689. */
  33690. static getMediaSource() {
  33691. return getMediaSource();
  33692. }
  33693. static get Events() {
  33694. return Events;
  33695. }
  33696. static get MetadataSchema() {
  33697. return MetadataSchema;
  33698. }
  33699. static get ErrorTypes() {
  33700. return ErrorTypes;
  33701. }
  33702. static get ErrorDetails() {
  33703. return ErrorDetails;
  33704. }
  33705. /**
  33706. * Get the default configuration applied to new instances.
  33707. */
  33708. static get DefaultConfig() {
  33709. if (!Hls.defaultConfig) {
  33710. return hlsDefaultConfig;
  33711. }
  33712. return Hls.defaultConfig;
  33713. }
  33714. /**
  33715. * Replace the default configuration applied to new instances.
  33716. */
  33717. static set DefaultConfig(defaultConfig) {
  33718. Hls.defaultConfig = defaultConfig;
  33719. }
  33720. /**
  33721. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  33722. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  33723. */
  33724. constructor(userConfig = {}) {
  33725. /**
  33726. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  33727. */
  33728. this.config = void 0;
  33729. /**
  33730. * The configuration object provided on player instantiation.
  33731. */
  33732. this.userConfig = void 0;
  33733. /**
  33734. * The logger functions used by this player instance, configured on player instantiation.
  33735. */
  33736. this.logger = void 0;
  33737. this.coreComponents = void 0;
  33738. this.networkControllers = void 0;
  33739. this._emitter = new EventEmitter();
  33740. this._autoLevelCapping = -1;
  33741. this._maxHdcpLevel = null;
  33742. this.abrController = void 0;
  33743. this.bufferController = void 0;
  33744. this.capLevelController = void 0;
  33745. this.latencyController = void 0;
  33746. this.levelController = void 0;
  33747. this.streamController = void 0;
  33748. this.audioStreamController = void 0;
  33749. this.subtititleStreamController = void 0;
  33750. this.audioTrackController = void 0;
  33751. this.subtitleTrackController = void 0;
  33752. this.interstitialsController = void 0;
  33753. this.gapController = void 0;
  33754. this.emeController = void 0;
  33755. this.cmcdController = void 0;
  33756. this._media = null;
  33757. this._url = null;
  33758. this._sessionId = void 0;
  33759. this.triggeringException = void 0;
  33760. this.started = false;
  33761. const logger = this.logger = enableLogs(userConfig.debug || false, 'Hls instance', userConfig.assetPlayerId);
  33762. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger);
  33763. this.userConfig = userConfig;
  33764. if (config.progressive) {
  33765. enableStreamingMode(config, logger);
  33766. }
  33767. // core controllers and network loaders
  33768. const {
  33769. abrController: _AbrController,
  33770. bufferController: _BufferController,
  33771. capLevelController: _CapLevelController,
  33772. errorController: _ErrorController,
  33773. fpsController: _FpsController
  33774. } = config;
  33775. const errorController = new _ErrorController(this);
  33776. const abrController = this.abrController = new _AbrController(this);
  33777. // FragmentTracker must be defined before StreamController because the order of event handling is important
  33778. const fragmentTracker = new FragmentTracker(this);
  33779. const _InterstitialsController = config.interstitialsController;
  33780. const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  33781. const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  33782. const capLevelController = this.capLevelController = new _CapLevelController(this);
  33783. const fpsController = new _FpsController(this);
  33784. const playListLoader = new PlaylistLoader(this);
  33785. const _ContentSteeringController = config.contentSteeringController;
  33786. // Instantiate ConentSteeringController before LevelController to receive Multivariant Playlist events first
  33787. const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  33788. const levelController = this.levelController = new LevelController(this, contentSteering);
  33789. const id3TrackController = new ID3TrackController(this);
  33790. const keyLoader = new KeyLoader(this.config);
  33791. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  33792. const gapController = this.gapController = new GapController(this, fragmentTracker);
  33793. // Cap level controller uses streamController to flush the buffer
  33794. capLevelController.setStreamController(streamController);
  33795. // fpsController uses streamController to switch when frames are being dropped
  33796. fpsController.setStreamController(streamController);
  33797. const networkControllers = [playListLoader, levelController, streamController];
  33798. if (interstitialsController) {
  33799. networkControllers.splice(1, 0, interstitialsController);
  33800. }
  33801. if (contentSteering) {
  33802. networkControllers.splice(1, 0, contentSteering);
  33803. }
  33804. this.networkControllers = networkControllers;
  33805. const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  33806. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  33807. const AudioStreamControllerClass = config.audioStreamController;
  33808. if (AudioStreamControllerClass) {
  33809. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  33810. }
  33811. // Instantiate subtitleTrackController before SubtitleStreamController to receive level events first
  33812. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  33813. const SubtitleStreamControllerClass = config.subtitleStreamController;
  33814. if (SubtitleStreamControllerClass) {
  33815. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  33816. }
  33817. this.createController(config.timelineController, coreComponents);
  33818. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  33819. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  33820. this.latencyController = this.createController(LatencyController, coreComponents);
  33821. this.coreComponents = coreComponents;
  33822. // Error controller handles errors before and after all other controllers
  33823. // This listener will be invoked after all other controllers error listeners
  33824. networkControllers.push(errorController);
  33825. const onErrorOut = errorController.onErrorOut;
  33826. if (typeof onErrorOut === 'function') {
  33827. this.on(Events.ERROR, onErrorOut, errorController);
  33828. }
  33829. // Autostart load handler
  33830. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  33831. }
  33832. createController(ControllerClass, components) {
  33833. if (ControllerClass) {
  33834. const controllerInstance = new ControllerClass(this);
  33835. if (components) {
  33836. components.push(controllerInstance);
  33837. }
  33838. return controllerInstance;
  33839. }
  33840. return null;
  33841. }
  33842. // Delegate the EventEmitter through the public API of Hls.js
  33843. on(event, listener, context = this) {
  33844. this._emitter.on(event, listener, context);
  33845. }
  33846. once(event, listener, context = this) {
  33847. this._emitter.once(event, listener, context);
  33848. }
  33849. removeAllListeners(event) {
  33850. this._emitter.removeAllListeners(event);
  33851. }
  33852. off(event, listener, context = this, once) {
  33853. this._emitter.off(event, listener, context, once);
  33854. }
  33855. listeners(event) {
  33856. return this._emitter.listeners(event);
  33857. }
  33858. emit(event, name, eventObject) {
  33859. return this._emitter.emit(event, name, eventObject);
  33860. }
  33861. trigger(event, eventObject) {
  33862. if (this.config.debug) {
  33863. return this.emit(event, event, eventObject);
  33864. } else {
  33865. try {
  33866. return this.emit(event, event, eventObject);
  33867. } catch (error) {
  33868. this.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  33869. // Prevent recursion in error event handlers that throw #5497
  33870. if (!this.triggeringException) {
  33871. this.triggeringException = true;
  33872. const fatal = event === Events.ERROR;
  33873. this.trigger(Events.ERROR, {
  33874. type: ErrorTypes.OTHER_ERROR,
  33875. details: ErrorDetails.INTERNAL_EXCEPTION,
  33876. fatal,
  33877. event,
  33878. error
  33879. });
  33880. this.triggeringException = false;
  33881. }
  33882. }
  33883. }
  33884. return false;
  33885. }
  33886. listenerCount(event) {
  33887. return this._emitter.listenerCount(event);
  33888. }
  33889. /**
  33890. * Dispose of the instance
  33891. */
  33892. destroy() {
  33893. this.logger.log('destroy');
  33894. this.trigger(Events.DESTROYING, undefined);
  33895. this.detachMedia();
  33896. this.removeAllListeners();
  33897. this._autoLevelCapping = -1;
  33898. this._url = null;
  33899. this.networkControllers.forEach(component => component.destroy());
  33900. this.networkControllers.length = 0;
  33901. this.coreComponents.forEach(component => component.destroy());
  33902. this.coreComponents.length = 0;
  33903. // Remove any references that could be held in config options or callbacks
  33904. const config = this.config;
  33905. config.xhrSetup = config.fetchSetup = undefined;
  33906. // @ts-ignore
  33907. this.userConfig = null;
  33908. }
  33909. /**
  33910. * Attaches Hls.js to a media element
  33911. */
  33912. attachMedia(data) {
  33913. if (!data || 'media' in data && !data.media) {
  33914. const error = new Error(`attachMedia failed: invalid argument (${data})`);
  33915. this.trigger(Events.ERROR, {
  33916. type: ErrorTypes.OTHER_ERROR,
  33917. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  33918. fatal: true,
  33919. error
  33920. });
  33921. return;
  33922. }
  33923. this.logger.log(`attachMedia`);
  33924. if (this._media) {
  33925. this.logger.warn(`media must be detached before attaching`);
  33926. this.detachMedia();
  33927. }
  33928. const attachMediaSource = 'media' in data;
  33929. const media = attachMediaSource ? data.media : data;
  33930. const attachingData = attachMediaSource ? data : {
  33931. media
  33932. };
  33933. this._media = media;
  33934. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  33935. }
  33936. /**
  33937. * Detach Hls.js from the media
  33938. */
  33939. detachMedia() {
  33940. this.logger.log('detachMedia');
  33941. this.trigger(Events.MEDIA_DETACHING, {});
  33942. this._media = null;
  33943. }
  33944. /**
  33945. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  33946. */
  33947. transferMedia() {
  33948. this._media = null;
  33949. const transferMedia = this.bufferController.transferMedia();
  33950. this.trigger(Events.MEDIA_DETACHING, {
  33951. transferMedia
  33952. });
  33953. return transferMedia;
  33954. }
  33955. /**
  33956. * Set the source URL. Can be relative or absolute.
  33957. */
  33958. loadSource(url) {
  33959. this.stopLoad();
  33960. const media = this.media;
  33961. const loadedSource = this._url;
  33962. const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  33963. alwaysNormalize: true
  33964. });
  33965. this._autoLevelCapping = -1;
  33966. this._maxHdcpLevel = null;
  33967. this.logger.log(`loadSource:${loadingSource}`);
  33968. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  33969. // Remove and re-create MediaSource
  33970. this.detachMedia();
  33971. this.attachMedia(media);
  33972. }
  33973. // when attaching to a source URL, trigger a playlist load
  33974. this.trigger(Events.MANIFEST_LOADING, {
  33975. url: url
  33976. });
  33977. }
  33978. /**
  33979. * Gets the currently loaded URL
  33980. */
  33981. get url() {
  33982. return this._url;
  33983. }
  33984. /**
  33985. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  33986. */
  33987. get hasEnoughToStart() {
  33988. return this.streamController.hasEnoughToStart;
  33989. }
  33990. /**
  33991. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  33992. */
  33993. get startPosition() {
  33994. return this.streamController.startPositionValue;
  33995. }
  33996. /**
  33997. * Start loading data from the stream source.
  33998. * Depending on default config, client starts loading automatically when a source is set.
  33999. *
  34000. * @param startPosition - Set the start position to stream from.
  34001. * Defaults to -1 (None: starts from earliest point)
  34002. */
  34003. startLoad(startPosition = -1, skipSeekToStartPosition) {
  34004. this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ', <skip seek to start>' : '')})`);
  34005. this.started = true;
  34006. this.resumeBuffering();
  34007. for (let i = 0; i < this.networkControllers.length; i++) {
  34008. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  34009. if (!this.started || !this.networkControllers) {
  34010. break;
  34011. }
  34012. }
  34013. }
  34014. /**
  34015. * Stop loading of any stream data.
  34016. */
  34017. stopLoad() {
  34018. this.logger.log('stopLoad');
  34019. this.started = false;
  34020. for (let i = 0; i < this.networkControllers.length; i++) {
  34021. this.networkControllers[i].stopLoad();
  34022. if (this.started || !this.networkControllers) {
  34023. break;
  34024. }
  34025. }
  34026. }
  34027. /**
  34028. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  34029. */
  34030. get loadingEnabled() {
  34031. return this.started;
  34032. }
  34033. /**
  34034. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  34035. */
  34036. get bufferingEnabled() {
  34037. return this.streamController.bufferingEnabled;
  34038. }
  34039. /**
  34040. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  34041. */
  34042. resumeBuffering() {
  34043. if (!this.bufferingEnabled) {
  34044. this.logger.log(`resume buffering`);
  34045. this.networkControllers.forEach(controller => {
  34046. if (controller.resumeBuffering) {
  34047. controller.resumeBuffering();
  34048. }
  34049. });
  34050. }
  34051. }
  34052. /**
  34053. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  34054. * This allows for media buffering to be paused without interupting playlist loading.
  34055. */
  34056. pauseBuffering() {
  34057. if (this.bufferingEnabled) {
  34058. this.logger.log(`pause buffering`);
  34059. this.networkControllers.forEach(controller => {
  34060. if (controller.pauseBuffering) {
  34061. controller.pauseBuffering();
  34062. }
  34063. });
  34064. }
  34065. }
  34066. get inFlightFragments() {
  34067. const inFlightData = {
  34068. [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag
  34069. };
  34070. if (this.audioStreamController) {
  34071. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  34072. }
  34073. if (this.subtititleStreamController) {
  34074. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  34075. }
  34076. return inFlightData;
  34077. }
  34078. /**
  34079. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  34080. */
  34081. swapAudioCodec() {
  34082. this.logger.log('swapAudioCodec');
  34083. this.streamController.swapAudioCodec();
  34084. }
  34085. /**
  34086. * When the media-element fails, this allows to detach and then re-attach it
  34087. * as one call (convenience method).
  34088. *
  34089. * Automatic recovery of media-errors by this process is configurable.
  34090. */
  34091. recoverMediaError() {
  34092. this.logger.log('recoverMediaError');
  34093. const media = this._media;
  34094. const time = media == null ? void 0 : media.currentTime;
  34095. this.detachMedia();
  34096. if (media) {
  34097. this.attachMedia(media);
  34098. if (time) {
  34099. this.startLoad(time);
  34100. }
  34101. }
  34102. }
  34103. removeLevel(levelIndex) {
  34104. this.levelController.removeLevel(levelIndex);
  34105. }
  34106. /**
  34107. * @returns a UUID for this player instance
  34108. */
  34109. get sessionId() {
  34110. let _sessionId = this._sessionId;
  34111. if (!_sessionId) {
  34112. _sessionId = this._sessionId = uuid();
  34113. }
  34114. return _sessionId;
  34115. }
  34116. /**
  34117. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  34118. */
  34119. get levels() {
  34120. const levels = this.levelController.levels;
  34121. return levels ? levels : [];
  34122. }
  34123. /**
  34124. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  34125. */
  34126. get latestLevelDetails() {
  34127. return this.streamController.getLevelDetails() || null;
  34128. }
  34129. /**
  34130. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  34131. */
  34132. get loadLevelObj() {
  34133. return this.levelController.loadLevelObj;
  34134. }
  34135. /**
  34136. * Index of quality level (variant) currently played
  34137. */
  34138. get currentLevel() {
  34139. return this.streamController.currentLevel;
  34140. }
  34141. /**
  34142. * 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.
  34143. */
  34144. set currentLevel(newLevel) {
  34145. this.logger.log(`set currentLevel:${newLevel}`);
  34146. this.levelController.manualLevel = newLevel;
  34147. this.streamController.immediateLevelSwitch();
  34148. }
  34149. /**
  34150. * Index of next quality level loaded as scheduled by stream controller.
  34151. */
  34152. get nextLevel() {
  34153. return this.streamController.nextLevel;
  34154. }
  34155. /**
  34156. * Set quality level index for next loaded data.
  34157. * This will switch the video quality asap, without interrupting playback.
  34158. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  34159. * @param newLevel - Pass -1 for automatic level selection
  34160. */
  34161. set nextLevel(newLevel) {
  34162. this.logger.log(`set nextLevel:${newLevel}`);
  34163. this.levelController.manualLevel = newLevel;
  34164. this.streamController.nextLevelSwitch();
  34165. }
  34166. /**
  34167. * Return the quality level of the currently or last (of none is loaded currently) segment
  34168. */
  34169. get loadLevel() {
  34170. return this.levelController.level;
  34171. }
  34172. /**
  34173. * Set quality level index for next loaded data in a conservative way.
  34174. * This will switch the quality without flushing, but interrupt current loading.
  34175. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  34176. * @param newLevel - Pass -1 for automatic level selection
  34177. */
  34178. set loadLevel(newLevel) {
  34179. this.logger.log(`set loadLevel:${newLevel}`);
  34180. this.levelController.manualLevel = newLevel;
  34181. }
  34182. /**
  34183. * get next quality level loaded
  34184. */
  34185. get nextLoadLevel() {
  34186. return this.levelController.nextLoadLevel;
  34187. }
  34188. /**
  34189. * Set quality level of next loaded segment in a fully "non-destructive" way.
  34190. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  34191. */
  34192. set nextLoadLevel(level) {
  34193. this.levelController.nextLoadLevel = level;
  34194. }
  34195. /**
  34196. * Return "first level": like a default level, if not set,
  34197. * falls back to index of first level referenced in manifest
  34198. */
  34199. get firstLevel() {
  34200. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  34201. }
  34202. /**
  34203. * Sets "first-level", see getter.
  34204. */
  34205. set firstLevel(newLevel) {
  34206. this.logger.log(`set firstLevel:${newLevel}`);
  34207. this.levelController.firstLevel = newLevel;
  34208. }
  34209. /**
  34210. * Return the desired start level for the first fragment that will be loaded.
  34211. * The default value of -1 indicates automatic start level selection.
  34212. * Setting hls.nextAutoLevel without setting a startLevel will result in
  34213. * the nextAutoLevel value being used for one fragment load.
  34214. */
  34215. get startLevel() {
  34216. const startLevel = this.levelController.startLevel;
  34217. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  34218. return this.abrController.forcedAutoLevel;
  34219. }
  34220. return startLevel;
  34221. }
  34222. /**
  34223. * set start level (level of first fragment that will be played back)
  34224. * if not overrided by user, first level appearing in manifest will be used as start level
  34225. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  34226. * (determined from download of first segment)
  34227. */
  34228. set startLevel(newLevel) {
  34229. this.logger.log(`set startLevel:${newLevel}`);
  34230. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  34231. if (newLevel !== -1) {
  34232. newLevel = Math.max(newLevel, this.minAutoLevel);
  34233. }
  34234. this.levelController.startLevel = newLevel;
  34235. }
  34236. /**
  34237. * Whether level capping is enabled.
  34238. * Default value is set via `config.capLevelToPlayerSize`.
  34239. */
  34240. get capLevelToPlayerSize() {
  34241. return this.config.capLevelToPlayerSize;
  34242. }
  34243. /**
  34244. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  34245. */
  34246. set capLevelToPlayerSize(shouldStartCapping) {
  34247. const newCapLevelToPlayerSize = !!shouldStartCapping;
  34248. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  34249. if (newCapLevelToPlayerSize) {
  34250. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  34251. } else {
  34252. this.capLevelController.stopCapping();
  34253. this.autoLevelCapping = -1;
  34254. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  34255. }
  34256. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  34257. }
  34258. }
  34259. /**
  34260. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  34261. */
  34262. get autoLevelCapping() {
  34263. return this._autoLevelCapping;
  34264. }
  34265. /**
  34266. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  34267. */
  34268. get bandwidthEstimate() {
  34269. const {
  34270. bwEstimator
  34271. } = this.abrController;
  34272. if (!bwEstimator) {
  34273. return NaN;
  34274. }
  34275. return bwEstimator.getEstimate();
  34276. }
  34277. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  34278. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  34279. }
  34280. get abrEwmaDefaultEstimate() {
  34281. const {
  34282. bwEstimator
  34283. } = this.abrController;
  34284. if (!bwEstimator) {
  34285. return NaN;
  34286. }
  34287. return bwEstimator.defaultEstimate;
  34288. }
  34289. /**
  34290. * get time to first byte estimate
  34291. * @type {number}
  34292. */
  34293. get ttfbEstimate() {
  34294. const {
  34295. bwEstimator
  34296. } = this.abrController;
  34297. if (!bwEstimator) {
  34298. return NaN;
  34299. }
  34300. return bwEstimator.getEstimateTTFB();
  34301. }
  34302. /**
  34303. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  34304. */
  34305. set autoLevelCapping(newLevel) {
  34306. if (this._autoLevelCapping !== newLevel) {
  34307. this.logger.log(`set autoLevelCapping:${newLevel}`);
  34308. this._autoLevelCapping = newLevel;
  34309. this.levelController.checkMaxAutoUpdated();
  34310. }
  34311. }
  34312. get maxHdcpLevel() {
  34313. return this._maxHdcpLevel;
  34314. }
  34315. set maxHdcpLevel(value) {
  34316. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  34317. this._maxHdcpLevel = value;
  34318. this.levelController.checkMaxAutoUpdated();
  34319. }
  34320. }
  34321. /**
  34322. * True when automatic level selection enabled
  34323. */
  34324. get autoLevelEnabled() {
  34325. return this.levelController.manualLevel === -1;
  34326. }
  34327. /**
  34328. * Level set manually (if any)
  34329. */
  34330. get manualLevel() {
  34331. return this.levelController.manualLevel;
  34332. }
  34333. /**
  34334. * min level selectable in auto mode according to config.minAutoBitrate
  34335. */
  34336. get minAutoLevel() {
  34337. const {
  34338. levels,
  34339. config: {
  34340. minAutoBitrate
  34341. }
  34342. } = this;
  34343. if (!levels) return 0;
  34344. const len = levels.length;
  34345. for (let i = 0; i < len; i++) {
  34346. if (levels[i].maxBitrate >= minAutoBitrate) {
  34347. return i;
  34348. }
  34349. }
  34350. return 0;
  34351. }
  34352. /**
  34353. * max level selectable in auto mode according to autoLevelCapping
  34354. */
  34355. get maxAutoLevel() {
  34356. const {
  34357. levels,
  34358. autoLevelCapping,
  34359. maxHdcpLevel
  34360. } = this;
  34361. let maxAutoLevel;
  34362. if (autoLevelCapping === -1 && levels != null && levels.length) {
  34363. maxAutoLevel = levels.length - 1;
  34364. } else {
  34365. maxAutoLevel = autoLevelCapping;
  34366. }
  34367. if (maxHdcpLevel) {
  34368. for (let i = maxAutoLevel; i--;) {
  34369. const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  34370. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  34371. return i;
  34372. }
  34373. }
  34374. }
  34375. return maxAutoLevel;
  34376. }
  34377. get firstAutoLevel() {
  34378. return this.abrController.firstAutoLevel;
  34379. }
  34380. /**
  34381. * next automatically selected quality level
  34382. */
  34383. get nextAutoLevel() {
  34384. return this.abrController.nextAutoLevel;
  34385. }
  34386. /**
  34387. * this setter is used to force next auto level.
  34388. * this is useful to force a switch down in auto mode:
  34389. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  34390. * forced value is valid for one fragment. upon successful frag loading at forced level,
  34391. * this value will be resetted to -1 by ABR controller.
  34392. */
  34393. set nextAutoLevel(nextLevel) {
  34394. this.abrController.nextAutoLevel = nextLevel;
  34395. }
  34396. /**
  34397. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  34398. */
  34399. get playingDate() {
  34400. return this.streamController.currentProgramDateTime;
  34401. }
  34402. get mainForwardBufferInfo() {
  34403. return this.streamController.getMainFwdBufferInfo();
  34404. }
  34405. get maxBufferLength() {
  34406. return this.streamController.maxBufferLength;
  34407. }
  34408. /**
  34409. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  34410. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  34411. */
  34412. setAudioOption(audioOption) {
  34413. var _this$audioTrackContr;
  34414. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  34415. }
  34416. /**
  34417. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  34418. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  34419. */
  34420. setSubtitleOption(subtitleOption) {
  34421. var _this$subtitleTrackCo;
  34422. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  34423. }
  34424. /**
  34425. * Get the complete list of audio tracks across all media groups
  34426. */
  34427. get allAudioTracks() {
  34428. const audioTrackController = this.audioTrackController;
  34429. return audioTrackController ? audioTrackController.allAudioTracks : [];
  34430. }
  34431. /**
  34432. * Get the list of selectable audio tracks
  34433. */
  34434. get audioTracks() {
  34435. const audioTrackController = this.audioTrackController;
  34436. return audioTrackController ? audioTrackController.audioTracks : [];
  34437. }
  34438. /**
  34439. * index of the selected audio track (index in audio track lists)
  34440. */
  34441. get audioTrack() {
  34442. const audioTrackController = this.audioTrackController;
  34443. return audioTrackController ? audioTrackController.audioTrack : -1;
  34444. }
  34445. /**
  34446. * selects an audio track, based on its index in audio track lists
  34447. */
  34448. set audioTrack(audioTrackId) {
  34449. const audioTrackController = this.audioTrackController;
  34450. if (audioTrackController) {
  34451. audioTrackController.audioTrack = audioTrackId;
  34452. }
  34453. }
  34454. /**
  34455. * get the complete list of subtitle tracks across all media groups
  34456. */
  34457. get allSubtitleTracks() {
  34458. const subtitleTrackController = this.subtitleTrackController;
  34459. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  34460. }
  34461. /**
  34462. * get alternate subtitle tracks list from playlist
  34463. */
  34464. get subtitleTracks() {
  34465. const subtitleTrackController = this.subtitleTrackController;
  34466. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  34467. }
  34468. /**
  34469. * index of the selected subtitle track (index in subtitle track lists)
  34470. */
  34471. get subtitleTrack() {
  34472. const subtitleTrackController = this.subtitleTrackController;
  34473. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  34474. }
  34475. get media() {
  34476. return this._media;
  34477. }
  34478. /**
  34479. * select an subtitle track, based on its index in subtitle track lists
  34480. */
  34481. set subtitleTrack(subtitleTrackId) {
  34482. const subtitleTrackController = this.subtitleTrackController;
  34483. if (subtitleTrackController) {
  34484. subtitleTrackController.subtitleTrack = subtitleTrackId;
  34485. }
  34486. }
  34487. /**
  34488. * Whether subtitle display is enabled or not
  34489. */
  34490. get subtitleDisplay() {
  34491. const subtitleTrackController = this.subtitleTrackController;
  34492. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  34493. }
  34494. /**
  34495. * Enable/disable subtitle display rendering
  34496. */
  34497. set subtitleDisplay(value) {
  34498. const subtitleTrackController = this.subtitleTrackController;
  34499. if (subtitleTrackController) {
  34500. subtitleTrackController.subtitleDisplay = value;
  34501. }
  34502. }
  34503. /**
  34504. * get mode for Low-Latency HLS loading
  34505. */
  34506. get lowLatencyMode() {
  34507. return this.config.lowLatencyMode;
  34508. }
  34509. /**
  34510. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  34511. */
  34512. set lowLatencyMode(mode) {
  34513. this.config.lowLatencyMode = mode;
  34514. }
  34515. /**
  34516. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  34517. * @returns null prior to loading live Playlist
  34518. */
  34519. get liveSyncPosition() {
  34520. return this.latencyController.liveSyncPosition;
  34521. }
  34522. /**
  34523. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  34524. * @returns 0 before first playlist is loaded
  34525. */
  34526. get latency() {
  34527. return this.latencyController.latency;
  34528. }
  34529. /**
  34530. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  34531. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  34532. * @returns 0 before first playlist is loaded
  34533. */
  34534. get maxLatency() {
  34535. return this.latencyController.maxLatency;
  34536. }
  34537. /**
  34538. * target distance from the edge as calculated by the latency controller
  34539. */
  34540. get targetLatency() {
  34541. return this.latencyController.targetLatency;
  34542. }
  34543. set targetLatency(latency) {
  34544. this.latencyController.targetLatency = latency;
  34545. }
  34546. /**
  34547. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  34548. */
  34549. get drift() {
  34550. return this.latencyController.drift;
  34551. }
  34552. /**
  34553. * set to true when startLoad is called before MANIFEST_PARSED event
  34554. */
  34555. get forceStartLoad() {
  34556. return this.streamController.forceStartLoad;
  34557. }
  34558. /**
  34559. * ContentSteering pathways getter
  34560. */
  34561. get pathways() {
  34562. return this.levelController.pathways;
  34563. }
  34564. /**
  34565. * ContentSteering pathwayPriority getter/setter
  34566. */
  34567. get pathwayPriority() {
  34568. return this.levelController.pathwayPriority;
  34569. }
  34570. set pathwayPriority(pathwayPriority) {
  34571. this.levelController.pathwayPriority = pathwayPriority;
  34572. }
  34573. /**
  34574. * returns true when all SourceBuffers are buffered to the end
  34575. */
  34576. get bufferedToEnd() {
  34577. var _this$bufferControlle;
  34578. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  34579. }
  34580. /**
  34581. * returns Interstitials Program Manager
  34582. */
  34583. get interstitialsManager() {
  34584. var _this$interstitialsCo;
  34585. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  34586. }
  34587. /**
  34588. * returns mediaCapabilities.decodingInfo for a variant/rendition
  34589. */
  34590. getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {
  34591. const audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  34592. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  34593. }
  34594. }
  34595. Hls.defaultConfig = void 0;
  34596. export { AbrController, AttrList, AudioStreamController, AudioTrackController, BasePlaylistController, BaseSegment, BaseStreamController, BufferController, CMCDController, CapLevelController, ChunkMetadata, ContentSteeringController, Cues, DateRange, EMEController, ErrorActionFlags, ErrorController, ErrorDetails, ErrorTypes, Events, FPSController, FetchLoader, Fragment, Hls, HlsSkip, HlsUrlParameters, KeySystemFormats, KeySystems, Level, LevelDetails, LevelKey, LoadStats, M3U8Parser, MetadataSchema, NetworkErrorAction, Part, PlaylistLevelType, SubtitleStreamController, SubtitleTrackController, TimelineController, XhrLoader, Hls as default, fetchSupported, getMediaSource, isMSESupported, isSupported, requestMediaKeySystemAccess };
  34597. //# sourceMappingURL=hls.mjs.map