hls.mjs 973 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597
  1. function getDefaultExportFromCjs (x) {
  2. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  3. }
  4. var urlToolkit = {exports: {}};
  5. (function (module, exports) {
  6. // see https://tools.ietf.org/html/rfc1808
  7. (function (root) {
  8. var URL_REGEX =
  9. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  10. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  11. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  12. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  13. var URLToolkit = {
  14. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  15. // E.g
  16. // With opts.alwaysNormalize = false (default, spec compliant)
  17. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  18. // With opts.alwaysNormalize = true (not spec compliant)
  19. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  20. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  21. opts = opts || {};
  22. // remove any remaining space and CRLF
  23. baseURL = baseURL.trim();
  24. relativeURL = relativeURL.trim();
  25. if (!relativeURL) {
  26. // 2a) If the embedded URL is entirely empty, it inherits the
  27. // entire base URL (i.e., is set equal to the base URL)
  28. // and we are done.
  29. if (!opts.alwaysNormalize) {
  30. return baseURL;
  31. }
  32. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  33. if (!basePartsForNormalise) {
  34. throw new Error('Error trying to parse base URL.');
  35. }
  36. basePartsForNormalise.path = URLToolkit.normalizePath(
  37. basePartsForNormalise.path
  38. );
  39. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  40. }
  41. var relativeParts = URLToolkit.parseURL(relativeURL);
  42. if (!relativeParts) {
  43. throw new Error('Error trying to parse relative URL.');
  44. }
  45. if (relativeParts.scheme) {
  46. // 2b) If the embedded URL starts with a scheme name, it is
  47. // interpreted as an absolute URL and we are done.
  48. if (!opts.alwaysNormalize) {
  49. return relativeURL;
  50. }
  51. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  52. return URLToolkit.buildURLFromParts(relativeParts);
  53. }
  54. var baseParts = URLToolkit.parseURL(baseURL);
  55. if (!baseParts) {
  56. throw new Error('Error trying to parse base URL.');
  57. }
  58. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  59. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  60. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  61. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  62. baseParts.netLoc = pathParts[1];
  63. baseParts.path = pathParts[2];
  64. }
  65. if (baseParts.netLoc && !baseParts.path) {
  66. baseParts.path = '/';
  67. }
  68. var builtParts = {
  69. // 2c) Otherwise, the embedded URL inherits the scheme of
  70. // the base URL.
  71. scheme: baseParts.scheme,
  72. netLoc: relativeParts.netLoc,
  73. path: null,
  74. params: relativeParts.params,
  75. query: relativeParts.query,
  76. fragment: relativeParts.fragment,
  77. };
  78. if (!relativeParts.netLoc) {
  79. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  80. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  81. // (if any) of the base URL.
  82. builtParts.netLoc = baseParts.netLoc;
  83. // 4) If the embedded URL path is preceded by a slash "/", the
  84. // path is not relative and we skip to Step 7.
  85. if (relativeParts.path[0] !== '/') {
  86. if (!relativeParts.path) {
  87. // 5) If the embedded URL path is empty (and not preceded by a
  88. // slash), then the embedded URL inherits the base URL path
  89. builtParts.path = baseParts.path;
  90. // 5a) if the embedded URL's <params> is non-empty, we skip to
  91. // step 7; otherwise, it inherits the <params> of the base
  92. // URL (if any) and
  93. if (!relativeParts.params) {
  94. builtParts.params = baseParts.params;
  95. // 5b) if the embedded URL's <query> is non-empty, we skip to
  96. // step 7; otherwise, it inherits the <query> of the base
  97. // URL (if any) and we skip to step 7.
  98. if (!relativeParts.query) {
  99. builtParts.query = baseParts.query;
  100. }
  101. }
  102. } else {
  103. // 6) The last segment of the base URL's path (anything
  104. // following the rightmost slash "/", or the entire path if no
  105. // slash is present) is removed and the embedded URL's path is
  106. // appended in its place.
  107. var baseURLPath = baseParts.path;
  108. var newPath =
  109. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  110. relativeParts.path;
  111. builtParts.path = URLToolkit.normalizePath(newPath);
  112. }
  113. }
  114. }
  115. if (builtParts.path === null) {
  116. builtParts.path = opts.alwaysNormalize
  117. ? URLToolkit.normalizePath(relativeParts.path)
  118. : relativeParts.path;
  119. }
  120. return URLToolkit.buildURLFromParts(builtParts);
  121. },
  122. parseURL: function (url) {
  123. var parts = URL_REGEX.exec(url);
  124. if (!parts) {
  125. return null;
  126. }
  127. return {
  128. scheme: parts[1] || '',
  129. netLoc: parts[2] || '',
  130. path: parts[3] || '',
  131. params: parts[4] || '',
  132. query: parts[5] || '',
  133. fragment: parts[6] || '',
  134. };
  135. },
  136. normalizePath: function (path) {
  137. // The following operations are
  138. // then applied, in order, to the new path:
  139. // 6a) All occurrences of "./", where "." is a complete path
  140. // segment, are removed.
  141. // 6b) If the path ends with "." as a complete path segment,
  142. // that "." is removed.
  143. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  144. // 6c) All occurrences of "<segment>/../", where <segment> is a
  145. // complete path segment not equal to "..", are removed.
  146. // Removal of these path segments is performed iteratively,
  147. // removing the leftmost matching pattern on each iteration,
  148. // until no matching pattern remains.
  149. // 6d) If the path ends with "<segment>/..", where <segment> is a
  150. // complete path segment not equal to "..", that
  151. // "<segment>/.." is removed.
  152. while (
  153. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  154. ) {}
  155. return path.split('').reverse().join('');
  156. },
  157. buildURLFromParts: function (parts) {
  158. return (
  159. parts.scheme +
  160. parts.netLoc +
  161. parts.path +
  162. parts.params +
  163. parts.query +
  164. parts.fragment
  165. );
  166. },
  167. };
  168. module.exports = URLToolkit;
  169. })();
  170. } (urlToolkit));
  171. var urlToolkitExports = urlToolkit.exports;
  172. function ownKeys(e, r) {
  173. var t = Object.keys(e);
  174. if (Object.getOwnPropertySymbols) {
  175. var o = Object.getOwnPropertySymbols(e);
  176. r && (o = o.filter(function (r) {
  177. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  178. })), t.push.apply(t, o);
  179. }
  180. return t;
  181. }
  182. function _objectSpread2(e) {
  183. for (var r = 1; r < arguments.length; r++) {
  184. var t = null != arguments[r] ? arguments[r] : {};
  185. r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
  186. _defineProperty(e, r, t[r]);
  187. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  188. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  189. });
  190. }
  191. return e;
  192. }
  193. function _toPrimitive(t, r) {
  194. if ("object" != typeof t || !t) return t;
  195. var e = t[Symbol.toPrimitive];
  196. if (void 0 !== e) {
  197. var i = e.call(t, r || "default");
  198. if ("object" != typeof i) return i;
  199. throw new TypeError("@@toPrimitive must return a primitive value.");
  200. }
  201. return ("string" === r ? String : Number)(t);
  202. }
  203. function _toPropertyKey(t) {
  204. var i = _toPrimitive(t, "string");
  205. return "symbol" == typeof i ? i : String(i);
  206. }
  207. function _defineProperty(obj, key, value) {
  208. key = _toPropertyKey(key);
  209. if (key in obj) {
  210. Object.defineProperty(obj, key, {
  211. value: value,
  212. enumerable: true,
  213. configurable: true,
  214. writable: true
  215. });
  216. } else {
  217. obj[key] = value;
  218. }
  219. return obj;
  220. }
  221. function _extends() {
  222. _extends = Object.assign ? Object.assign.bind() : function (target) {
  223. for (var i = 1; i < arguments.length; i++) {
  224. var source = arguments[i];
  225. for (var key in source) {
  226. if (Object.prototype.hasOwnProperty.call(source, key)) {
  227. target[key] = source[key];
  228. }
  229. }
  230. }
  231. return target;
  232. };
  233. return _extends.apply(this, arguments);
  234. }
  235. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  236. const isFiniteNumber = Number.isFinite || function (value) {
  237. return typeof value === 'number' && isFinite(value);
  238. };
  239. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  240. const isSafeInteger = Number.isSafeInteger || function (value) {
  241. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  242. };
  243. const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  244. let Events = /*#__PURE__*/function (Events) {
  245. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  246. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  247. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  248. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  249. Events["BUFFER_RESET"] = "hlsBufferReset";
  250. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  251. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  252. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  253. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  254. Events["BUFFER_EOS"] = "hlsBufferEos";
  255. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  256. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  257. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  258. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  259. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  260. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  261. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  262. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  263. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  264. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  265. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  266. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  267. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  268. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  269. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  270. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  271. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  272. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  273. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  274. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  275. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  276. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  277. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  278. Events["CUES_PARSED"] = "hlsCuesParsed";
  279. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  280. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  281. Events["FRAG_LOADING"] = "hlsFragLoading";
  282. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  283. Events["FRAG_LOADED"] = "hlsFragLoaded";
  284. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  285. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  286. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  287. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  288. Events["FRAG_PARSED"] = "hlsFragParsed";
  289. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  290. Events["FRAG_CHANGED"] = "hlsFragChanged";
  291. Events["FPS_DROP"] = "hlsFpsDrop";
  292. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  293. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  294. Events["ERROR"] = "hlsError";
  295. Events["DESTROYING"] = "hlsDestroying";
  296. Events["KEY_LOADING"] = "hlsKeyLoading";
  297. Events["KEY_LOADED"] = "hlsKeyLoaded";
  298. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  299. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  300. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  301. return Events;
  302. }({});
  303. /**
  304. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  305. */
  306. let ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  307. ErrorTypes["NETWORK_ERROR"] = "networkError";
  308. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  309. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  310. ErrorTypes["MUX_ERROR"] = "muxError";
  311. ErrorTypes["OTHER_ERROR"] = "otherError";
  312. return ErrorTypes;
  313. }({});
  314. let ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  315. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  316. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  317. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  318. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  319. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  320. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  321. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  322. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  323. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  324. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  325. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  326. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  327. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  328. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  329. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  330. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  331. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  332. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  333. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  334. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  335. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  336. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  337. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  338. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  339. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  340. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  341. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  342. ErrorDetails["FRAG_GAP"] = "fragGap";
  343. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  344. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  345. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  346. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  347. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  348. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  349. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  350. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  351. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  352. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  353. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  354. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  355. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  356. ErrorDetails["UNKNOWN"] = "unknown";
  357. return ErrorDetails;
  358. }({});
  359. const noop = function noop() {};
  360. const fakeLogger = {
  361. trace: noop,
  362. debug: noop,
  363. log: noop,
  364. warn: noop,
  365. info: noop,
  366. error: noop
  367. };
  368. let exportedLogger = fakeLogger;
  369. // let lastCallTime;
  370. // function formatMsgWithTimeInfo(type, msg) {
  371. // const now = Date.now();
  372. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  373. // lastCallTime = now;
  374. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  375. // return msg;
  376. // }
  377. function consolePrintFn(type) {
  378. const func = self.console[type];
  379. if (func) {
  380. return func.bind(self.console, `[${type}] >`);
  381. }
  382. return noop;
  383. }
  384. function exportLoggerFunctions(debugConfig, ...functions) {
  385. functions.forEach(function (type) {
  386. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  387. });
  388. }
  389. function enableLogs(debugConfig, id) {
  390. // check that console is available
  391. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  392. exportLoggerFunctions(debugConfig,
  393. // Remove out from list here to hard-disable a log-level
  394. // 'trace',
  395. 'debug', 'log', 'info', 'warn', 'error');
  396. // Some browsers don't allow to use bind on console object anyway
  397. // fallback to default if needed
  398. try {
  399. exportedLogger.log(`Debug logs enabled for "${id}" in hls.js version ${"1.5.15"}`);
  400. } catch (e) {
  401. exportedLogger = fakeLogger;
  402. }
  403. } else {
  404. exportedLogger = fakeLogger;
  405. }
  406. }
  407. const logger = exportedLogger;
  408. const DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  409. const ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  410. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  411. class AttrList {
  412. constructor(attrs) {
  413. if (typeof attrs === 'string') {
  414. attrs = AttrList.parseAttrList(attrs);
  415. }
  416. _extends(this, attrs);
  417. }
  418. get clientAttrs() {
  419. return Object.keys(this).filter(attr => attr.substring(0, 2) === 'X-');
  420. }
  421. decimalInteger(attrName) {
  422. const intValue = parseInt(this[attrName], 10);
  423. if (intValue > Number.MAX_SAFE_INTEGER) {
  424. return Infinity;
  425. }
  426. return intValue;
  427. }
  428. hexadecimalInteger(attrName) {
  429. if (this[attrName]) {
  430. let stringValue = (this[attrName] || '0x').slice(2);
  431. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  432. const value = new Uint8Array(stringValue.length / 2);
  433. for (let i = 0; i < stringValue.length / 2; i++) {
  434. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  435. }
  436. return value;
  437. } else {
  438. return null;
  439. }
  440. }
  441. hexadecimalIntegerAsNumber(attrName) {
  442. const intValue = parseInt(this[attrName], 16);
  443. if (intValue > Number.MAX_SAFE_INTEGER) {
  444. return Infinity;
  445. }
  446. return intValue;
  447. }
  448. decimalFloatingPoint(attrName) {
  449. return parseFloat(this[attrName]);
  450. }
  451. optionalFloat(attrName, defaultValue) {
  452. const value = this[attrName];
  453. return value ? parseFloat(value) : defaultValue;
  454. }
  455. enumeratedString(attrName) {
  456. return this[attrName];
  457. }
  458. bool(attrName) {
  459. return this[attrName] === 'YES';
  460. }
  461. decimalResolution(attrName) {
  462. const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  463. if (res === null) {
  464. return undefined;
  465. }
  466. return {
  467. width: parseInt(res[1], 10),
  468. height: parseInt(res[2], 10)
  469. };
  470. }
  471. static parseAttrList(input) {
  472. let match;
  473. const attrs = {};
  474. const quote = '"';
  475. ATTR_LIST_REGEX.lastIndex = 0;
  476. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  477. let value = match[2];
  478. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  479. value = value.slice(1, -1);
  480. }
  481. const name = match[1].trim();
  482. attrs[name] = value;
  483. }
  484. return attrs;
  485. }
  486. }
  487. // Avoid exporting const enum so that these values can be inlined
  488. function isDateRangeCueAttribute(attrName) {
  489. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  490. }
  491. function isSCTE35Attribute(attrName) {
  492. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN";
  493. }
  494. class DateRange {
  495. constructor(dateRangeAttr, dateRangeWithSameId) {
  496. this.attr = void 0;
  497. this._startDate = void 0;
  498. this._endDate = void 0;
  499. this._badValueForSameId = void 0;
  500. if (dateRangeWithSameId) {
  501. const previousAttr = dateRangeWithSameId.attr;
  502. for (const key in previousAttr) {
  503. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  504. logger.warn(`DATERANGE tag attribute: "${key}" does not match for tags with ID: "${dateRangeAttr.ID}"`);
  505. this._badValueForSameId = key;
  506. break;
  507. }
  508. }
  509. // Merge DateRange tags with the same ID
  510. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  511. }
  512. this.attr = dateRangeAttr;
  513. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  514. if ("END-DATE" in this.attr) {
  515. const endDate = new Date(this.attr["END-DATE"]);
  516. if (isFiniteNumber(endDate.getTime())) {
  517. this._endDate = endDate;
  518. }
  519. }
  520. }
  521. get id() {
  522. return this.attr.ID;
  523. }
  524. get class() {
  525. return this.attr.CLASS;
  526. }
  527. get startDate() {
  528. return this._startDate;
  529. }
  530. get endDate() {
  531. if (this._endDate) {
  532. return this._endDate;
  533. }
  534. const duration = this.duration;
  535. if (duration !== null) {
  536. return new Date(this._startDate.getTime() + duration * 1000);
  537. }
  538. return null;
  539. }
  540. get duration() {
  541. if ("DURATION" in this.attr) {
  542. const duration = this.attr.decimalFloatingPoint("DURATION");
  543. if (isFiniteNumber(duration)) {
  544. return duration;
  545. }
  546. } else if (this._endDate) {
  547. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  548. }
  549. return null;
  550. }
  551. get plannedDuration() {
  552. if ("PLANNED-DURATION" in this.attr) {
  553. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  554. }
  555. return null;
  556. }
  557. get endOnNext() {
  558. return this.attr.bool("END-ON-NEXT");
  559. }
  560. get isValid() {
  561. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class);
  562. }
  563. }
  564. class LoadStats {
  565. constructor() {
  566. this.aborted = false;
  567. this.loaded = 0;
  568. this.retry = 0;
  569. this.total = 0;
  570. this.chunkCount = 0;
  571. this.bwEstimate = 0;
  572. this.loading = {
  573. start: 0,
  574. first: 0,
  575. end: 0
  576. };
  577. this.parsing = {
  578. start: 0,
  579. end: 0
  580. };
  581. this.buffering = {
  582. start: 0,
  583. first: 0,
  584. end: 0
  585. };
  586. }
  587. }
  588. var ElementaryStreamTypes = {
  589. AUDIO: "audio",
  590. VIDEO: "video",
  591. AUDIOVIDEO: "audiovideo"
  592. };
  593. class BaseSegment {
  594. constructor(baseurl) {
  595. this._byteRange = null;
  596. this._url = null;
  597. // baseurl is the URL to the playlist
  598. this.baseurl = void 0;
  599. // relurl is the portion of the URL that comes from inside the playlist.
  600. this.relurl = void 0;
  601. // Holds the types of data this fragment supports
  602. this.elementaryStreams = {
  603. [ElementaryStreamTypes.AUDIO]: null,
  604. [ElementaryStreamTypes.VIDEO]: null,
  605. [ElementaryStreamTypes.AUDIOVIDEO]: null
  606. };
  607. this.baseurl = baseurl;
  608. }
  609. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  610. setByteRange(value, previous) {
  611. const params = value.split('@', 2);
  612. let start;
  613. if (params.length === 1) {
  614. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  615. } else {
  616. start = parseInt(params[1]);
  617. }
  618. this._byteRange = [start, parseInt(params[0]) + start];
  619. }
  620. get byteRange() {
  621. if (!this._byteRange) {
  622. return [];
  623. }
  624. return this._byteRange;
  625. }
  626. get byteRangeStartOffset() {
  627. return this.byteRange[0];
  628. }
  629. get byteRangeEndOffset() {
  630. return this.byteRange[1];
  631. }
  632. get url() {
  633. if (!this._url && this.baseurl && this.relurl) {
  634. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  635. alwaysNormalize: true
  636. });
  637. }
  638. return this._url || '';
  639. }
  640. set url(value) {
  641. this._url = value;
  642. }
  643. }
  644. /**
  645. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  646. */
  647. class Fragment extends BaseSegment {
  648. constructor(type, baseurl) {
  649. super(baseurl);
  650. this._decryptdata = null;
  651. this.rawProgramDateTime = null;
  652. this.programDateTime = null;
  653. this.tagList = [];
  654. // EXTINF has to be present for a m3u8 to be considered valid
  655. this.duration = 0;
  656. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  657. this.sn = 0;
  658. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  659. // core difference from the private field _decryptdata is the lack of the initialized IV
  660. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  661. this.levelkeys = void 0;
  662. // A string representing the fragment type
  663. this.type = void 0;
  664. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  665. this.loader = null;
  666. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  667. this.keyLoader = null;
  668. // The level/track index to which the fragment belongs
  669. this.level = -1;
  670. // The continuity counter of the fragment
  671. this.cc = 0;
  672. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  673. this.startPTS = void 0;
  674. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  675. this.endPTS = void 0;
  676. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  677. this.startDTS = void 0;
  678. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  679. this.endDTS = void 0;
  680. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  681. this.start = 0;
  682. // Set by `updateFragPTSDTS` in level-helper
  683. this.deltaPTS = void 0;
  684. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  685. this.maxStartPTS = void 0;
  686. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  687. this.minEndPTS = void 0;
  688. // Load/parse timing information
  689. this.stats = new LoadStats();
  690. // Init Segment bytes (unset for media segments)
  691. this.data = void 0;
  692. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  693. this.bitrateTest = false;
  694. // #EXTINF segment title
  695. this.title = null;
  696. // The Media Initialization Section for this segment
  697. this.initSegment = null;
  698. // Fragment is the last fragment in the media playlist
  699. this.endList = void 0;
  700. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  701. this.gap = void 0;
  702. // Deprecated
  703. this.urlId = 0;
  704. this.type = type;
  705. }
  706. get decryptdata() {
  707. const {
  708. levelkeys
  709. } = this;
  710. if (!levelkeys && !this._decryptdata) {
  711. return null;
  712. }
  713. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  714. const key = this.levelkeys.identity;
  715. if (key) {
  716. this._decryptdata = key.getDecryptData(this.sn);
  717. } else {
  718. const keyFormats = Object.keys(this.levelkeys);
  719. if (keyFormats.length === 1) {
  720. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  721. }
  722. }
  723. }
  724. return this._decryptdata;
  725. }
  726. get end() {
  727. return this.start + this.duration;
  728. }
  729. get endProgramDateTime() {
  730. if (this.programDateTime === null) {
  731. return null;
  732. }
  733. if (!isFiniteNumber(this.programDateTime)) {
  734. return null;
  735. }
  736. const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  737. return this.programDateTime + duration * 1000;
  738. }
  739. get encrypted() {
  740. var _this$_decryptdata;
  741. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  742. // when we want the fragment to start reporting that it is encrypted.
  743. // Currently, keyFormat will only be set for identity keys
  744. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  745. return true;
  746. } else if (this.levelkeys) {
  747. const keyFormats = Object.keys(this.levelkeys);
  748. const len = keyFormats.length;
  749. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  750. return true;
  751. }
  752. }
  753. return false;
  754. }
  755. setKeyFormat(keyFormat) {
  756. if (this.levelkeys) {
  757. const key = this.levelkeys[keyFormat];
  758. if (key && !this._decryptdata) {
  759. this._decryptdata = key.getDecryptData(this.sn);
  760. }
  761. }
  762. }
  763. abortRequests() {
  764. var _this$loader, _this$keyLoader;
  765. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  766. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  767. }
  768. setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {
  769. const {
  770. elementaryStreams
  771. } = this;
  772. const info = elementaryStreams[type];
  773. if (!info) {
  774. elementaryStreams[type] = {
  775. startPTS,
  776. endPTS,
  777. startDTS,
  778. endDTS,
  779. partial
  780. };
  781. return;
  782. }
  783. info.startPTS = Math.min(info.startPTS, startPTS);
  784. info.endPTS = Math.max(info.endPTS, endPTS);
  785. info.startDTS = Math.min(info.startDTS, startDTS);
  786. info.endDTS = Math.max(info.endDTS, endDTS);
  787. }
  788. clearElementaryStreamInfo() {
  789. const {
  790. elementaryStreams
  791. } = this;
  792. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  793. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  794. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  795. }
  796. }
  797. /**
  798. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  799. */
  800. class Part extends BaseSegment {
  801. constructor(partAttrs, frag, baseurl, index, previous) {
  802. super(baseurl);
  803. this.fragOffset = 0;
  804. this.duration = 0;
  805. this.gap = false;
  806. this.independent = false;
  807. this.relurl = void 0;
  808. this.fragment = void 0;
  809. this.index = void 0;
  810. this.stats = new LoadStats();
  811. this.duration = partAttrs.decimalFloatingPoint('DURATION');
  812. this.gap = partAttrs.bool('GAP');
  813. this.independent = partAttrs.bool('INDEPENDENT');
  814. this.relurl = partAttrs.enumeratedString('URI');
  815. this.fragment = frag;
  816. this.index = index;
  817. const byteRange = partAttrs.enumeratedString('BYTERANGE');
  818. if (byteRange) {
  819. this.setByteRange(byteRange, previous);
  820. }
  821. if (previous) {
  822. this.fragOffset = previous.fragOffset + previous.duration;
  823. }
  824. }
  825. get start() {
  826. return this.fragment.start + this.fragOffset;
  827. }
  828. get end() {
  829. return this.start + this.duration;
  830. }
  831. get loaded() {
  832. const {
  833. elementaryStreams
  834. } = this;
  835. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  836. }
  837. }
  838. const DEFAULT_TARGET_DURATION = 10;
  839. /**
  840. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  841. */
  842. class LevelDetails {
  843. constructor(baseUrl) {
  844. this.PTSKnown = false;
  845. this.alignedSliding = false;
  846. this.averagetargetduration = void 0;
  847. this.endCC = 0;
  848. this.endSN = 0;
  849. this.fragments = void 0;
  850. this.fragmentHint = void 0;
  851. this.partList = null;
  852. this.dateRanges = void 0;
  853. this.live = true;
  854. this.ageHeader = 0;
  855. this.advancedDateTime = void 0;
  856. this.updated = true;
  857. this.advanced = true;
  858. this.availabilityDelay = void 0;
  859. // Manifest reload synchronization
  860. this.misses = 0;
  861. this.startCC = 0;
  862. this.startSN = 0;
  863. this.startTimeOffset = null;
  864. this.targetduration = 0;
  865. this.totalduration = 0;
  866. this.type = null;
  867. this.url = void 0;
  868. this.m3u8 = '';
  869. this.version = null;
  870. this.canBlockReload = false;
  871. this.canSkipUntil = 0;
  872. this.canSkipDateRanges = false;
  873. this.skippedSegments = 0;
  874. this.recentlyRemovedDateranges = void 0;
  875. this.partHoldBack = 0;
  876. this.holdBack = 0;
  877. this.partTarget = 0;
  878. this.preloadHint = void 0;
  879. this.renditionReports = void 0;
  880. this.tuneInGoal = 0;
  881. this.deltaUpdateFailed = void 0;
  882. this.driftStartTime = 0;
  883. this.driftEndTime = 0;
  884. this.driftStart = 0;
  885. this.driftEnd = 0;
  886. this.encryptedFragments = void 0;
  887. this.playlistParsingError = null;
  888. this.variableList = null;
  889. this.hasVariableRefs = false;
  890. this.fragments = [];
  891. this.encryptedFragments = [];
  892. this.dateRanges = {};
  893. this.url = baseUrl;
  894. }
  895. reloaded(previous) {
  896. if (!previous) {
  897. this.advanced = true;
  898. this.updated = true;
  899. return;
  900. }
  901. const partSnDiff = this.lastPartSn - previous.lastPartSn;
  902. const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  903. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  904. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  905. if (this.updated || this.advanced) {
  906. this.misses = Math.floor(previous.misses * 0.6);
  907. } else {
  908. this.misses = previous.misses + 1;
  909. }
  910. this.availabilityDelay = previous.availabilityDelay;
  911. }
  912. get hasProgramDateTime() {
  913. if (this.fragments.length) {
  914. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  915. }
  916. return false;
  917. }
  918. get levelTargetDuration() {
  919. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  920. }
  921. get drift() {
  922. const runTime = this.driftEndTime - this.driftStartTime;
  923. if (runTime > 0) {
  924. const runDuration = this.driftEnd - this.driftStart;
  925. return runDuration * 1000 / runTime;
  926. }
  927. return 1;
  928. }
  929. get edge() {
  930. return this.partEnd || this.fragmentEnd;
  931. }
  932. get partEnd() {
  933. var _this$partList;
  934. if ((_this$partList = this.partList) != null && _this$partList.length) {
  935. return this.partList[this.partList.length - 1].end;
  936. }
  937. return this.fragmentEnd;
  938. }
  939. get fragmentEnd() {
  940. var _this$fragments;
  941. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  942. return this.fragments[this.fragments.length - 1].end;
  943. }
  944. return 0;
  945. }
  946. get age() {
  947. if (this.advancedDateTime) {
  948. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  949. }
  950. return 0;
  951. }
  952. get lastPartIndex() {
  953. var _this$partList2;
  954. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  955. return this.partList[this.partList.length - 1].index;
  956. }
  957. return -1;
  958. }
  959. get lastPartSn() {
  960. var _this$partList3;
  961. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  962. return this.partList[this.partList.length - 1].fragment.sn;
  963. }
  964. return this.endSN;
  965. }
  966. }
  967. function base64Decode(base64encodedStr) {
  968. return Uint8Array.from(atob(base64encodedStr), c => c.charCodeAt(0));
  969. }
  970. function getKeyIdBytes(str) {
  971. const keyIdbytes = strToUtf8array(str).subarray(0, 16);
  972. const paddedkeyIdbytes = new Uint8Array(16);
  973. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  974. return paddedkeyIdbytes;
  975. }
  976. function changeEndianness(keyId) {
  977. const swap = function swap(array, from, to) {
  978. const cur = array[from];
  979. array[from] = array[to];
  980. array[to] = cur;
  981. };
  982. swap(keyId, 0, 3);
  983. swap(keyId, 1, 2);
  984. swap(keyId, 4, 5);
  985. swap(keyId, 6, 7);
  986. }
  987. function convertDataUriToArrayBytes(uri) {
  988. // data:[<media type][;attribute=value][;base64],<data>
  989. const colonsplit = uri.split(':');
  990. let keydata = null;
  991. if (colonsplit[0] === 'data' && colonsplit.length === 2) {
  992. const semicolonsplit = colonsplit[1].split(';');
  993. const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');
  994. if (commasplit.length === 2) {
  995. const isbase64 = commasplit[0] === 'base64';
  996. const data = commasplit[1];
  997. if (isbase64) {
  998. semicolonsplit.splice(-1, 1); // remove from processing
  999. keydata = base64Decode(data);
  1000. } else {
  1001. keydata = getKeyIdBytes(data);
  1002. }
  1003. }
  1004. }
  1005. return keydata;
  1006. }
  1007. function strToUtf8array(str) {
  1008. return Uint8Array.from(unescape(encodeURIComponent(str)), c => c.charCodeAt(0));
  1009. }
  1010. /** returns `undefined` is `self` is missing, e.g. in node */
  1011. const optionalSelf = typeof self !== 'undefined' ? self : undefined;
  1012. /**
  1013. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  1014. */
  1015. var KeySystems = {
  1016. CLEARKEY: "org.w3.clearkey",
  1017. FAIRPLAY: "com.apple.fps",
  1018. PLAYREADY: "com.microsoft.playready",
  1019. WIDEVINE: "com.widevine.alpha"
  1020. };
  1021. // Playlist #EXT-X-KEY KEYFORMAT values
  1022. var KeySystemFormats = {
  1023. CLEARKEY: "org.w3.clearkey",
  1024. FAIRPLAY: "com.apple.streamingkeydelivery",
  1025. PLAYREADY: "com.microsoft.playready",
  1026. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  1027. };
  1028. function keySystemFormatToKeySystemDomain(format) {
  1029. switch (format) {
  1030. case KeySystemFormats.FAIRPLAY:
  1031. return KeySystems.FAIRPLAY;
  1032. case KeySystemFormats.PLAYREADY:
  1033. return KeySystems.PLAYREADY;
  1034. case KeySystemFormats.WIDEVINE:
  1035. return KeySystems.WIDEVINE;
  1036. case KeySystemFormats.CLEARKEY:
  1037. return KeySystems.CLEARKEY;
  1038. }
  1039. }
  1040. // System IDs for which we can extract a key ID from "encrypted" event PSSH
  1041. var KeySystemIds = {
  1042. CENC: "1077efecc0b24d02ace33c1e52e2fb4b",
  1043. CLEARKEY: "e2719d58a985b3c9781ab030af78d30e",
  1044. FAIRPLAY: "94ce86fb07ff4f43adb893d2fa968ca2",
  1045. PLAYREADY: "9a04f07998404286ab92e65be0885f95",
  1046. WIDEVINE: "edef8ba979d64acea3c827dcd51d21ed"
  1047. };
  1048. function keySystemIdToKeySystemDomain(systemId) {
  1049. if (systemId === KeySystemIds.WIDEVINE) {
  1050. return KeySystems.WIDEVINE;
  1051. } else if (systemId === KeySystemIds.PLAYREADY) {
  1052. return KeySystems.PLAYREADY;
  1053. } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {
  1054. return KeySystems.CLEARKEY;
  1055. }
  1056. }
  1057. function keySystemDomainToKeySystemFormat(keySystem) {
  1058. switch (keySystem) {
  1059. case KeySystems.FAIRPLAY:
  1060. return KeySystemFormats.FAIRPLAY;
  1061. case KeySystems.PLAYREADY:
  1062. return KeySystemFormats.PLAYREADY;
  1063. case KeySystems.WIDEVINE:
  1064. return KeySystemFormats.WIDEVINE;
  1065. case KeySystems.CLEARKEY:
  1066. return KeySystemFormats.CLEARKEY;
  1067. }
  1068. }
  1069. function getKeySystemsForConfig(config) {
  1070. const {
  1071. drmSystems,
  1072. widevineLicenseUrl
  1073. } = config;
  1074. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter(keySystem => !!drmSystems[keySystem]) : [];
  1075. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  1076. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  1077. }
  1078. return keySystemsToAttempt;
  1079. }
  1080. const requestMediaKeySystemAccess = function (_optionalSelf$navigat) {
  1081. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  1082. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  1083. } else {
  1084. return null;
  1085. }
  1086. }();
  1087. /**
  1088. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  1089. */
  1090. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  1091. let initDataTypes;
  1092. switch (keySystem) {
  1093. case KeySystems.FAIRPLAY:
  1094. initDataTypes = ['cenc', 'sinf'];
  1095. break;
  1096. case KeySystems.WIDEVINE:
  1097. case KeySystems.PLAYREADY:
  1098. initDataTypes = ['cenc'];
  1099. break;
  1100. case KeySystems.CLEARKEY:
  1101. initDataTypes = ['cenc', 'keyids'];
  1102. break;
  1103. default:
  1104. throw new Error(`Unknown key-system: ${keySystem}`);
  1105. }
  1106. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  1107. }
  1108. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  1109. const baseConfig = {
  1110. initDataTypes: initDataTypes,
  1111. persistentState: drmSystemOptions.persistentState || 'optional',
  1112. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',
  1113. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || 'temporary'],
  1114. audioCapabilities: audioCodecs.map(codec => ({
  1115. contentType: `audio/mp4; codecs="${codec}"`,
  1116. robustness: drmSystemOptions.audioRobustness || '',
  1117. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  1118. })),
  1119. videoCapabilities: videoCodecs.map(codec => ({
  1120. contentType: `video/mp4; codecs="${codec}"`,
  1121. robustness: drmSystemOptions.videoRobustness || '',
  1122. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  1123. }))
  1124. };
  1125. return [baseConfig];
  1126. }
  1127. function sliceUint8(array, start, end) {
  1128. // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
  1129. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
  1130. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
  1131. }
  1132. // breaking up those two types in order to clarify what is happening in the decoding path.
  1133. /**
  1134. * Returns true if an ID3 header can be found at offset in data
  1135. * @param data - The data to search
  1136. * @param offset - The offset at which to start searching
  1137. */
  1138. const isHeader$2 = (data, offset) => {
  1139. /*
  1140. * http://id3.org/id3v2.3.0
  1141. * [0] = 'I'
  1142. * [1] = 'D'
  1143. * [2] = '3'
  1144. * [3,4] = {Version}
  1145. * [5] = {Flags}
  1146. * [6-9] = {ID3 Size}
  1147. *
  1148. * An ID3v2 tag can be detected with the following pattern:
  1149. * $49 44 33 yy yy xx zz zz zz zz
  1150. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  1151. */
  1152. if (offset + 10 <= data.length) {
  1153. // look for 'ID3' identifier
  1154. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  1155. // check version is within range
  1156. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1157. // check size is within range
  1158. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1159. return true;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. return false;
  1165. };
  1166. /**
  1167. * Returns true if an ID3 footer can be found at offset in data
  1168. * @param data - The data to search
  1169. * @param offset - The offset at which to start searching
  1170. */
  1171. const isFooter = (data, offset) => {
  1172. /*
  1173. * The footer is a copy of the header, but with a different identifier
  1174. */
  1175. if (offset + 10 <= data.length) {
  1176. // look for '3DI' identifier
  1177. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  1178. // check version is within range
  1179. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1180. // check size is within range
  1181. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1182. return true;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. return false;
  1188. };
  1189. /**
  1190. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  1191. * @param data - The data to search in
  1192. * @param offset - The offset at which to start searching
  1193. * @returns the block of data containing any ID3 tags found
  1194. * or *undefined* if no header is found at the starting offset
  1195. */
  1196. const getID3Data = (data, offset) => {
  1197. const front = offset;
  1198. let length = 0;
  1199. while (isHeader$2(data, offset)) {
  1200. // ID3 header is 10 bytes
  1201. length += 10;
  1202. const size = readSize(data, offset + 6);
  1203. length += size;
  1204. if (isFooter(data, offset + 10)) {
  1205. // ID3 footer is 10 bytes
  1206. length += 10;
  1207. }
  1208. offset += length;
  1209. }
  1210. if (length > 0) {
  1211. return data.subarray(front, front + length);
  1212. }
  1213. return undefined;
  1214. };
  1215. const readSize = (data, offset) => {
  1216. let size = 0;
  1217. size = (data[offset] & 0x7f) << 21;
  1218. size |= (data[offset + 1] & 0x7f) << 14;
  1219. size |= (data[offset + 2] & 0x7f) << 7;
  1220. size |= data[offset + 3] & 0x7f;
  1221. return size;
  1222. };
  1223. const canParse$2 = (data, offset) => {
  1224. return isHeader$2(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
  1225. };
  1226. /**
  1227. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  1228. * @param data - Block of data containing one or more ID3 tags
  1229. */
  1230. const getTimeStamp = data => {
  1231. const frames = getID3Frames(data);
  1232. for (let i = 0; i < frames.length; i++) {
  1233. const frame = frames[i];
  1234. if (isTimeStampFrame(frame)) {
  1235. return readTimeStamp(frame);
  1236. }
  1237. }
  1238. return undefined;
  1239. };
  1240. /**
  1241. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  1242. */
  1243. const isTimeStampFrame = frame => {
  1244. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  1245. };
  1246. const getFrameData = data => {
  1247. /*
  1248. Frame ID $xx xx xx xx (four characters)
  1249. Size $xx xx xx xx
  1250. Flags $xx xx
  1251. */
  1252. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  1253. const size = readSize(data, 4);
  1254. // skip frame id, size, and flags
  1255. const offset = 10;
  1256. return {
  1257. type,
  1258. size,
  1259. data: data.subarray(offset, offset + size)
  1260. };
  1261. };
  1262. /**
  1263. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  1264. * @param id3Data - The ID3 data containing one or more ID3 tags
  1265. */
  1266. const getID3Frames = id3Data => {
  1267. let offset = 0;
  1268. const frames = [];
  1269. while (isHeader$2(id3Data, offset)) {
  1270. const size = readSize(id3Data, offset + 6);
  1271. // skip past ID3 header
  1272. offset += 10;
  1273. const end = offset + size;
  1274. // loop through frames in the ID3 tag
  1275. while (offset + 8 < end) {
  1276. const frameData = getFrameData(id3Data.subarray(offset));
  1277. const frame = decodeFrame(frameData);
  1278. if (frame) {
  1279. frames.push(frame);
  1280. }
  1281. // skip frame header and frame data
  1282. offset += frameData.size + 10;
  1283. }
  1284. if (isFooter(id3Data, offset)) {
  1285. offset += 10;
  1286. }
  1287. }
  1288. return frames;
  1289. };
  1290. const decodeFrame = frame => {
  1291. if (frame.type === 'PRIV') {
  1292. return decodePrivFrame(frame);
  1293. } else if (frame.type[0] === 'W') {
  1294. return decodeURLFrame(frame);
  1295. }
  1296. return decodeTextFrame(frame);
  1297. };
  1298. const decodePrivFrame = frame => {
  1299. /*
  1300. Format: <text string>\0<binary data>
  1301. */
  1302. if (frame.size < 2) {
  1303. return undefined;
  1304. }
  1305. const owner = utf8ArrayToStr(frame.data, true);
  1306. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  1307. return {
  1308. key: frame.type,
  1309. info: owner,
  1310. data: privateData.buffer
  1311. };
  1312. };
  1313. const decodeTextFrame = frame => {
  1314. if (frame.size < 2) {
  1315. return undefined;
  1316. }
  1317. if (frame.type === 'TXXX') {
  1318. /*
  1319. Format:
  1320. [0] = {Text Encoding}
  1321. [1-?] = {Description}\0{Value}
  1322. */
  1323. let index = 1;
  1324. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1325. index += description.length + 1;
  1326. const value = utf8ArrayToStr(frame.data.subarray(index));
  1327. return {
  1328. key: frame.type,
  1329. info: description,
  1330. data: value
  1331. };
  1332. }
  1333. /*
  1334. Format:
  1335. [0] = {Text Encoding}
  1336. [1-?] = {Value}
  1337. */
  1338. const text = utf8ArrayToStr(frame.data.subarray(1));
  1339. return {
  1340. key: frame.type,
  1341. data: text
  1342. };
  1343. };
  1344. const decodeURLFrame = frame => {
  1345. if (frame.type === 'WXXX') {
  1346. /*
  1347. Format:
  1348. [0] = {Text Encoding}
  1349. [1-?] = {Description}\0{URL}
  1350. */
  1351. if (frame.size < 2) {
  1352. return undefined;
  1353. }
  1354. let index = 1;
  1355. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1356. index += description.length + 1;
  1357. const value = utf8ArrayToStr(frame.data.subarray(index));
  1358. return {
  1359. key: frame.type,
  1360. info: description,
  1361. data: value
  1362. };
  1363. }
  1364. /*
  1365. Format:
  1366. [0-?] = {URL}
  1367. */
  1368. const url = utf8ArrayToStr(frame.data);
  1369. return {
  1370. key: frame.type,
  1371. data: url
  1372. };
  1373. };
  1374. const readTimeStamp = timeStampFrame => {
  1375. if (timeStampFrame.data.byteLength === 8) {
  1376. const data = new Uint8Array(timeStampFrame.data);
  1377. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  1378. // with the upper 31 bits set to zero.
  1379. const pts33Bit = data[3] & 0x1;
  1380. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  1381. timestamp /= 45;
  1382. if (pts33Bit) {
  1383. timestamp += 47721858.84;
  1384. } // 2^32 / 90
  1385. return Math.round(timestamp);
  1386. }
  1387. return undefined;
  1388. };
  1389. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1390. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1391. /* utf.js - UTF-8 <=> UTF-16 convertion
  1392. *
  1393. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1394. * Version: 1.0
  1395. * LastModified: Dec 25 1999
  1396. * This library is free. You can redistribute it and/or modify it.
  1397. */
  1398. const utf8ArrayToStr = (array, exitOnNull = false) => {
  1399. const decoder = getTextDecoder();
  1400. if (decoder) {
  1401. const decoded = decoder.decode(array);
  1402. if (exitOnNull) {
  1403. // grab up to the first null
  1404. const idx = decoded.indexOf('\0');
  1405. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1406. }
  1407. // remove any null characters
  1408. return decoded.replace(/\0/g, '');
  1409. }
  1410. const len = array.length;
  1411. let c;
  1412. let char2;
  1413. let char3;
  1414. let out = '';
  1415. let i = 0;
  1416. while (i < len) {
  1417. c = array[i++];
  1418. if (c === 0x00 && exitOnNull) {
  1419. return out;
  1420. } else if (c === 0x00 || c === 0x03) {
  1421. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1422. continue;
  1423. }
  1424. switch (c >> 4) {
  1425. case 0:
  1426. case 1:
  1427. case 2:
  1428. case 3:
  1429. case 4:
  1430. case 5:
  1431. case 6:
  1432. case 7:
  1433. // 0xxxxxxx
  1434. out += String.fromCharCode(c);
  1435. break;
  1436. case 12:
  1437. case 13:
  1438. // 110x xxxx 10xx xxxx
  1439. char2 = array[i++];
  1440. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1441. break;
  1442. case 14:
  1443. // 1110 xxxx 10xx xxxx 10xx xxxx
  1444. char2 = array[i++];
  1445. char3 = array[i++];
  1446. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1447. break;
  1448. }
  1449. }
  1450. return out;
  1451. };
  1452. let decoder;
  1453. function getTextDecoder() {
  1454. // On Play Station 4, TextDecoder is defined but partially implemented.
  1455. // Manual decoding option is preferable
  1456. if (navigator.userAgent.includes('PlayStation 4')) {
  1457. return;
  1458. }
  1459. if (!decoder && typeof self.TextDecoder !== 'undefined') {
  1460. decoder = new self.TextDecoder('utf-8');
  1461. }
  1462. return decoder;
  1463. }
  1464. /**
  1465. * hex dump helper class
  1466. */
  1467. const Hex = {
  1468. hexDump: function (array) {
  1469. let str = '';
  1470. for (let i = 0; i < array.length; i++) {
  1471. let h = array[i].toString(16);
  1472. if (h.length < 2) {
  1473. h = '0' + h;
  1474. }
  1475. str += h;
  1476. }
  1477. return str;
  1478. }
  1479. };
  1480. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1481. const push = [].push;
  1482. // We are using fixed track IDs for driving the MP4 remuxer
  1483. // instead of following the TS PIDs.
  1484. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1485. // may not like if there are TrackID "switches"
  1486. // See https://github.com/video-dev/hls.js/issues/1331
  1487. // Here we are mapping our internal track types to constant MP4 track IDs
  1488. // With MSE currently one can only have one track of each, and we are muxing
  1489. // whatever video/audio rendition in them.
  1490. const RemuxerTrackIdConfig = {
  1491. video: 1,
  1492. audio: 2,
  1493. id3: 3,
  1494. text: 4
  1495. };
  1496. function bin2str(data) {
  1497. return String.fromCharCode.apply(null, data);
  1498. }
  1499. function readUint16(buffer, offset) {
  1500. const val = buffer[offset] << 8 | buffer[offset + 1];
  1501. return val < 0 ? 65536 + val : val;
  1502. }
  1503. function readUint32(buffer, offset) {
  1504. const val = readSint32(buffer, offset);
  1505. return val < 0 ? 4294967296 + val : val;
  1506. }
  1507. function readUint64(buffer, offset) {
  1508. let result = readUint32(buffer, offset);
  1509. result *= Math.pow(2, 32);
  1510. result += readUint32(buffer, offset + 4);
  1511. return result;
  1512. }
  1513. function readSint32(buffer, offset) {
  1514. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1515. }
  1516. function writeUint32(buffer, offset, value) {
  1517. buffer[offset] = value >> 24;
  1518. buffer[offset + 1] = value >> 16 & 0xff;
  1519. buffer[offset + 2] = value >> 8 & 0xff;
  1520. buffer[offset + 3] = value & 0xff;
  1521. }
  1522. // Find "moof" box
  1523. function hasMoofData(data) {
  1524. const end = data.byteLength;
  1525. for (let i = 0; i < end;) {
  1526. const size = readUint32(data, i);
  1527. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1528. return true;
  1529. }
  1530. i = size > 1 ? i + size : end;
  1531. }
  1532. return false;
  1533. }
  1534. // Find the data for a box specified by its path
  1535. function findBox(data, path) {
  1536. const results = [];
  1537. if (!path.length) {
  1538. // short-circuit the search for empty paths
  1539. return results;
  1540. }
  1541. const end = data.byteLength;
  1542. for (let i = 0; i < end;) {
  1543. const size = readUint32(data, i);
  1544. const type = bin2str(data.subarray(i + 4, i + 8));
  1545. const endbox = size > 1 ? i + size : end;
  1546. if (type === path[0]) {
  1547. if (path.length === 1) {
  1548. // this is the end of the path and we've found the box we were
  1549. // looking for
  1550. results.push(data.subarray(i + 8, endbox));
  1551. } else {
  1552. // recursively search for the next box along the path
  1553. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1554. if (subresults.length) {
  1555. push.apply(results, subresults);
  1556. }
  1557. }
  1558. }
  1559. i = endbox;
  1560. }
  1561. // we've finished searching all of data
  1562. return results;
  1563. }
  1564. function parseSegmentIndex(sidx) {
  1565. const references = [];
  1566. const version = sidx[0];
  1567. // set initial offset, we skip the reference ID (not needed)
  1568. let index = 8;
  1569. const timescale = readUint32(sidx, index);
  1570. index += 4;
  1571. let earliestPresentationTime = 0;
  1572. let firstOffset = 0;
  1573. if (version === 0) {
  1574. earliestPresentationTime = readUint32(sidx, index);
  1575. firstOffset = readUint32(sidx, index + 4);
  1576. index += 8;
  1577. } else {
  1578. earliestPresentationTime = readUint64(sidx, index);
  1579. firstOffset = readUint64(sidx, index + 8);
  1580. index += 16;
  1581. }
  1582. // skip reserved
  1583. index += 2;
  1584. let startByte = sidx.length + firstOffset;
  1585. const referencesCount = readUint16(sidx, index);
  1586. index += 2;
  1587. for (let i = 0; i < referencesCount; i++) {
  1588. let referenceIndex = index;
  1589. const referenceInfo = readUint32(sidx, referenceIndex);
  1590. referenceIndex += 4;
  1591. const referenceSize = referenceInfo & 0x7fffffff;
  1592. const referenceType = (referenceInfo & 0x80000000) >>> 31;
  1593. if (referenceType === 1) {
  1594. logger.warn('SIDX has hierarchical references (not supported)');
  1595. return null;
  1596. }
  1597. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1598. referenceIndex += 4;
  1599. references.push({
  1600. referenceSize,
  1601. subsegmentDuration,
  1602. // unscaled
  1603. info: {
  1604. duration: subsegmentDuration / timescale,
  1605. start: startByte,
  1606. end: startByte + referenceSize - 1
  1607. }
  1608. });
  1609. startByte += referenceSize;
  1610. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1611. // for |sapDelta|.
  1612. referenceIndex += 4;
  1613. // skip to next ref
  1614. index = referenceIndex;
  1615. }
  1616. return {
  1617. earliestPresentationTime,
  1618. timescale,
  1619. version,
  1620. referencesCount,
  1621. references
  1622. };
  1623. }
  1624. /**
  1625. * Parses an MP4 initialization segment and extracts stream type and
  1626. * timescale values for any declared tracks. Timescale values indicate the
  1627. * number of clock ticks per second to assume for time-based values
  1628. * elsewhere in the MP4.
  1629. *
  1630. * To determine the start time of an MP4, you need two pieces of
  1631. * information: the timescale unit and the earliest base media decode
  1632. * time. Multiple timescales can be specified within an MP4 but the
  1633. * base media decode time is always expressed in the timescale from
  1634. * the media header box for the track:
  1635. * ```
  1636. * moov > trak > mdia > mdhd.timescale
  1637. * moov > trak > mdia > hdlr
  1638. * ```
  1639. * @param initSegment the bytes of the init segment
  1640. * @returns a hash of track type to timescale values or null if
  1641. * the init segment is malformed.
  1642. */
  1643. function parseInitSegment(initSegment) {
  1644. const result = [];
  1645. const traks = findBox(initSegment, ['moov', 'trak']);
  1646. for (let i = 0; i < traks.length; i++) {
  1647. const trak = traks[i];
  1648. const tkhd = findBox(trak, ['tkhd'])[0];
  1649. if (tkhd) {
  1650. let version = tkhd[0];
  1651. const trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1652. const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1653. if (mdhd) {
  1654. version = mdhd[0];
  1655. const timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1656. const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1657. if (hdlr) {
  1658. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1659. const type = {
  1660. soun: ElementaryStreamTypes.AUDIO,
  1661. vide: ElementaryStreamTypes.VIDEO
  1662. }[hdlrType];
  1663. if (type) {
  1664. // Parse codec details
  1665. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1666. const stsdData = parseStsd(stsd);
  1667. result[trackId] = {
  1668. timescale,
  1669. type
  1670. };
  1671. result[type] = _objectSpread2({
  1672. timescale,
  1673. id: trackId
  1674. }, stsdData);
  1675. }
  1676. }
  1677. }
  1678. }
  1679. }
  1680. const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1681. trex.forEach(trex => {
  1682. const trackId = readUint32(trex, 4);
  1683. const track = result[trackId];
  1684. if (track) {
  1685. track.default = {
  1686. duration: readUint32(trex, 12),
  1687. flags: readUint32(trex, 20)
  1688. };
  1689. }
  1690. });
  1691. return result;
  1692. }
  1693. function parseStsd(stsd) {
  1694. const sampleEntries = stsd.subarray(8);
  1695. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1696. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1697. let codec = fourCC;
  1698. const encrypted = fourCC === 'enca' || fourCC === 'encv';
  1699. if (encrypted) {
  1700. const encBox = findBox(sampleEntries, [fourCC])[0];
  1701. const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1702. const sinfs = findBox(encBoxChildren, ['sinf']);
  1703. sinfs.forEach(sinf => {
  1704. const schm = findBox(sinf, ['schm'])[0];
  1705. if (schm) {
  1706. const scheme = bin2str(schm.subarray(4, 8));
  1707. if (scheme === 'cbcs' || scheme === 'cenc') {
  1708. const frma = findBox(sinf, ['frma'])[0];
  1709. if (frma) {
  1710. // for encrypted content codec fourCC will be in frma
  1711. codec = bin2str(frma);
  1712. }
  1713. }
  1714. }
  1715. });
  1716. }
  1717. switch (codec) {
  1718. case 'avc1':
  1719. case 'avc2':
  1720. case 'avc3':
  1721. case 'avc4':
  1722. {
  1723. // extract profile + compatibility + level out of avcC box
  1724. const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1725. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1726. break;
  1727. }
  1728. case 'mp4a':
  1729. {
  1730. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1731. const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1732. if (esdsBox && esdsBox.length > 12) {
  1733. let i = 4;
  1734. // ES Descriptor tag
  1735. if (esdsBox[i++] !== 0x03) {
  1736. break;
  1737. }
  1738. i = skipBERInteger(esdsBox, i);
  1739. i += 2; // skip es_id;
  1740. const flags = esdsBox[i++];
  1741. if (flags & 0x80) {
  1742. i += 2; // skip dependency es_id
  1743. }
  1744. if (flags & 0x40) {
  1745. i += esdsBox[i++]; // skip URL
  1746. }
  1747. // Decoder config descriptor
  1748. if (esdsBox[i++] !== 0x04) {
  1749. break;
  1750. }
  1751. i = skipBERInteger(esdsBox, i);
  1752. const objectType = esdsBox[i++];
  1753. if (objectType === 0x40) {
  1754. codec += '.' + toHex(objectType);
  1755. } else {
  1756. break;
  1757. }
  1758. i += 12;
  1759. // Decoder specific info
  1760. if (esdsBox[i++] !== 0x05) {
  1761. break;
  1762. }
  1763. i = skipBERInteger(esdsBox, i);
  1764. const firstByte = esdsBox[i++];
  1765. let audioObjectType = (firstByte & 0xf8) >> 3;
  1766. if (audioObjectType === 31) {
  1767. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1768. }
  1769. codec += '.' + audioObjectType;
  1770. }
  1771. break;
  1772. }
  1773. case 'hvc1':
  1774. case 'hev1':
  1775. {
  1776. const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1777. const profileByte = hvcCBox[1];
  1778. const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1779. const generalProfileIdc = profileByte & 0x1f;
  1780. const profileCompat = readUint32(hvcCBox, 2);
  1781. const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1782. const levelIDC = hvcCBox[12];
  1783. const constraintIndicator = hvcCBox.subarray(6, 12);
  1784. codec += '.' + profileSpace + generalProfileIdc;
  1785. codec += '.' + profileCompat.toString(16).toUpperCase();
  1786. codec += '.' + tierFlag + levelIDC;
  1787. let constraintString = '';
  1788. for (let i = constraintIndicator.length; i--;) {
  1789. const byte = constraintIndicator[i];
  1790. if (byte || constraintString) {
  1791. const encodedByte = byte.toString(16).toUpperCase();
  1792. constraintString = '.' + encodedByte + constraintString;
  1793. }
  1794. }
  1795. codec += constraintString;
  1796. break;
  1797. }
  1798. case 'dvh1':
  1799. case 'dvhe':
  1800. {
  1801. const dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];
  1802. const profile = dvcCBox[2] >> 1 & 0x7f;
  1803. const level = dvcCBox[2] << 5 & 0x20 | dvcCBox[3] >> 3 & 0x1f;
  1804. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);
  1805. break;
  1806. }
  1807. case 'vp09':
  1808. {
  1809. const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1810. const profile = vpcCBox[4];
  1811. const level = vpcCBox[5];
  1812. const bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1813. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  1814. break;
  1815. }
  1816. case 'av01':
  1817. {
  1818. const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1819. const profile = av1CBox[1] >>> 5;
  1820. const level = av1CBox[1] & 0x1f;
  1821. const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1822. const highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1823. const twelveBit = (av1CBox[2] & 0x20) >> 5;
  1824. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1825. const monochrome = (av1CBox[2] & 0x10) >> 4;
  1826. const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1827. const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1828. const chromaSamplePosition = av1CBox[2] & 0x03;
  1829. // TODO: parse color_description_present_flag
  1830. // default it to BT.709/limited range for now
  1831. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1832. const colorPrimaries = 1;
  1833. const transferCharacteristics = 1;
  1834. const matrixCoefficients = 1;
  1835. const videoFullRangeFlag = 0;
  1836. codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1837. break;
  1838. }
  1839. }
  1840. return {
  1841. codec,
  1842. encrypted
  1843. };
  1844. }
  1845. function skipBERInteger(bytes, i) {
  1846. const limit = i + 5;
  1847. while (bytes[i++] & 0x80 && i < limit) {}
  1848. return i;
  1849. }
  1850. function toHex(x) {
  1851. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1852. }
  1853. function addLeadingZero(num) {
  1854. return (num < 10 ? '0' : '') + num;
  1855. }
  1856. function patchEncyptionData(initSegment, decryptdata) {
  1857. if (!initSegment || !decryptdata) {
  1858. return initSegment;
  1859. }
  1860. const keyId = decryptdata.keyId;
  1861. if (keyId && decryptdata.isCommonEncryption) {
  1862. const traks = findBox(initSegment, ['moov', 'trak']);
  1863. traks.forEach(trak => {
  1864. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1865. // skip the sample entry count
  1866. const sampleEntries = stsd.subarray(8);
  1867. let encBoxes = findBox(sampleEntries, ['enca']);
  1868. const isAudio = encBoxes.length > 0;
  1869. if (!isAudio) {
  1870. encBoxes = findBox(sampleEntries, ['encv']);
  1871. }
  1872. encBoxes.forEach(enc => {
  1873. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1874. const sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1875. sinfBoxes.forEach(sinf => {
  1876. const tenc = parseSinf(sinf);
  1877. if (tenc) {
  1878. // Look for default key id (keyID offset is always 8 within the tenc box):
  1879. const tencKeyId = tenc.subarray(8, 24);
  1880. if (!tencKeyId.some(b => b !== 0)) {
  1881. logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1882. tenc.set(keyId, 8);
  1883. }
  1884. }
  1885. });
  1886. });
  1887. });
  1888. }
  1889. return initSegment;
  1890. }
  1891. function parseSinf(sinf) {
  1892. const schm = findBox(sinf, ['schm'])[0];
  1893. if (schm) {
  1894. const scheme = bin2str(schm.subarray(4, 8));
  1895. if (scheme === 'cbcs' || scheme === 'cenc') {
  1896. return findBox(sinf, ['schi', 'tenc'])[0];
  1897. }
  1898. }
  1899. return null;
  1900. }
  1901. /**
  1902. * Determine the base media decode start time, in seconds, for an MP4
  1903. * fragment. If multiple fragments are specified, the earliest time is
  1904. * returned.
  1905. *
  1906. * The base media decode time can be parsed from track fragment
  1907. * metadata:
  1908. * ```
  1909. * moof > traf > tfdt.baseMediaDecodeTime
  1910. * ```
  1911. * It requires the timescale value from the mdhd to interpret.
  1912. *
  1913. * @param initData - a hash of track type to timescale values
  1914. * @param fmp4 - the bytes of the mp4 fragment
  1915. * @returns the earliest base media decode start time for the
  1916. * fragment, in seconds
  1917. */
  1918. function getStartDTS(initData, fmp4) {
  1919. // we need info from two children of each track fragment box
  1920. return findBox(fmp4, ['moof', 'traf']).reduce((result, traf) => {
  1921. const tfdt = findBox(traf, ['tfdt'])[0];
  1922. const version = tfdt[0];
  1923. const start = findBox(traf, ['tfhd']).reduce((result, tfhd) => {
  1924. // get the track id from the tfhd
  1925. const id = readUint32(tfhd, 4);
  1926. const track = initData[id];
  1927. if (track) {
  1928. let baseTime = readUint32(tfdt, 4);
  1929. if (version === 1) {
  1930. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1931. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1932. // https://github.com/video-dev/hls.js/issues/5303
  1933. if (baseTime === UINT32_MAX$1) {
  1934. logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1935. return result;
  1936. }
  1937. baseTime *= UINT32_MAX$1 + 1;
  1938. baseTime += readUint32(tfdt, 8);
  1939. }
  1940. // assume a 90kHz clock if no timescale was specified
  1941. const scale = track.timescale || 90e3;
  1942. // convert base time to seconds
  1943. const startTime = baseTime / scale;
  1944. if (isFiniteNumber(startTime) && (result === null || startTime < result)) {
  1945. return startTime;
  1946. }
  1947. }
  1948. return result;
  1949. }, null);
  1950. if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {
  1951. return start;
  1952. }
  1953. return result;
  1954. }, null);
  1955. }
  1956. /*
  1957. For Reference:
  1958. aligned(8) class TrackFragmentHeaderBox
  1959. extends FullBox(‘tfhd’, 0, tf_flags){
  1960. unsigned int(32) track_ID;
  1961. // all the following are optional fields
  1962. unsigned int(64) base_data_offset;
  1963. unsigned int(32) sample_description_index;
  1964. unsigned int(32) default_sample_duration;
  1965. unsigned int(32) default_sample_size;
  1966. unsigned int(32) default_sample_flags
  1967. }
  1968. */
  1969. function getDuration(data, initData) {
  1970. let rawDuration = 0;
  1971. let videoDuration = 0;
  1972. let audioDuration = 0;
  1973. const trafs = findBox(data, ['moof', 'traf']);
  1974. for (let i = 0; i < trafs.length; i++) {
  1975. const traf = trafs[i];
  1976. // There is only one tfhd & trun per traf
  1977. // This is true for CMAF style content, and we should perhaps check the ftyp
  1978. // and only look for a single trun then, but for ISOBMFF we should check
  1979. // for multiple track runs.
  1980. const tfhd = findBox(traf, ['tfhd'])[0];
  1981. // get the track id from the tfhd
  1982. const id = readUint32(tfhd, 4);
  1983. const track = initData[id];
  1984. if (!track) {
  1985. continue;
  1986. }
  1987. const trackDefault = track.default;
  1988. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1989. let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
  1990. if (tfhdFlags & 0x000008) {
  1991. // 0x000008 indicates the presence of the default_sample_duration field
  1992. if (tfhdFlags & 0x000002) {
  1993. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  1994. // If present, the default_sample_duration exists at byte offset 12
  1995. sampleDuration = readUint32(tfhd, 12);
  1996. } else {
  1997. // Otherwise, the duration is at byte offset 8
  1998. sampleDuration = readUint32(tfhd, 8);
  1999. }
  2000. }
  2001. // assume a 90kHz clock if no timescale was specified
  2002. const timescale = track.timescale || 90e3;
  2003. const truns = findBox(traf, ['trun']);
  2004. for (let j = 0; j < truns.length; j++) {
  2005. rawDuration = computeRawDurationFromSamples(truns[j]);
  2006. if (!rawDuration && sampleDuration) {
  2007. const sampleCount = readUint32(truns[j], 4);
  2008. rawDuration = sampleDuration * sampleCount;
  2009. }
  2010. if (track.type === ElementaryStreamTypes.VIDEO) {
  2011. videoDuration += rawDuration / timescale;
  2012. } else if (track.type === ElementaryStreamTypes.AUDIO) {
  2013. audioDuration += rawDuration / timescale;
  2014. }
  2015. }
  2016. }
  2017. if (videoDuration === 0 && audioDuration === 0) {
  2018. // If duration samples are not available in the traf use sidx subsegment_duration
  2019. let sidxMinStart = Infinity;
  2020. let sidxMaxEnd = 0;
  2021. let sidxDuration = 0;
  2022. const sidxs = findBox(data, ['sidx']);
  2023. for (let i = 0; i < sidxs.length; i++) {
  2024. const sidx = parseSegmentIndex(sidxs[i]);
  2025. if (sidx != null && sidx.references) {
  2026. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2027. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  2028. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2029. sidxDuration = sidxMaxEnd - sidxMinStart;
  2030. }
  2031. }
  2032. if (sidxDuration && isFiniteNumber(sidxDuration)) {
  2033. return sidxDuration;
  2034. }
  2035. }
  2036. if (videoDuration) {
  2037. return videoDuration;
  2038. }
  2039. return audioDuration;
  2040. }
  2041. /*
  2042. For Reference:
  2043. aligned(8) class TrackRunBox
  2044. extends FullBox(‘trun’, version, tr_flags) {
  2045. unsigned int(32) sample_count;
  2046. // the following are optional fields
  2047. signed int(32) data_offset;
  2048. unsigned int(32) first_sample_flags;
  2049. // all fields in the following array are optional
  2050. {
  2051. unsigned int(32) sample_duration;
  2052. unsigned int(32) sample_size;
  2053. unsigned int(32) sample_flags
  2054. if (version == 0)
  2055. { unsigned int(32)
  2056. else
  2057. { signed int(32)
  2058. }[ sample_count ]
  2059. }
  2060. */
  2061. function computeRawDurationFromSamples(trun) {
  2062. const flags = readUint32(trun, 0);
  2063. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  2064. // Each field is an int32, which is 4 bytes
  2065. let offset = 8;
  2066. // data-offset-present flag
  2067. if (flags & 0x000001) {
  2068. offset += 4;
  2069. }
  2070. // first-sample-flags-present flag
  2071. if (flags & 0x000004) {
  2072. offset += 4;
  2073. }
  2074. let duration = 0;
  2075. const sampleCount = readUint32(trun, 4);
  2076. for (let i = 0; i < sampleCount; i++) {
  2077. // sample-duration-present flag
  2078. if (flags & 0x000100) {
  2079. const sampleDuration = readUint32(trun, offset);
  2080. duration += sampleDuration;
  2081. offset += 4;
  2082. }
  2083. // sample-size-present flag
  2084. if (flags & 0x000200) {
  2085. offset += 4;
  2086. }
  2087. // sample-flags-present flag
  2088. if (flags & 0x000400) {
  2089. offset += 4;
  2090. }
  2091. // sample-composition-time-offsets-present flag
  2092. if (flags & 0x000800) {
  2093. offset += 4;
  2094. }
  2095. }
  2096. return duration;
  2097. }
  2098. function offsetStartDTS(initData, fmp4, timeOffset) {
  2099. findBox(fmp4, ['moof', 'traf']).forEach(traf => {
  2100. findBox(traf, ['tfhd']).forEach(tfhd => {
  2101. // get the track id from the tfhd
  2102. const id = readUint32(tfhd, 4);
  2103. const track = initData[id];
  2104. if (!track) {
  2105. return;
  2106. }
  2107. // assume a 90kHz clock if no timescale was specified
  2108. const timescale = track.timescale || 90e3;
  2109. // get the base media decode time from the tfdt
  2110. findBox(traf, ['tfdt']).forEach(tfdt => {
  2111. const version = tfdt[0];
  2112. const offset = timeOffset * timescale;
  2113. if (offset) {
  2114. let baseMediaDecodeTime = readUint32(tfdt, 4);
  2115. if (version === 0) {
  2116. baseMediaDecodeTime -= offset;
  2117. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2118. writeUint32(tfdt, 4, baseMediaDecodeTime);
  2119. } else {
  2120. baseMediaDecodeTime *= Math.pow(2, 32);
  2121. baseMediaDecodeTime += readUint32(tfdt, 8);
  2122. baseMediaDecodeTime -= offset;
  2123. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2124. const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
  2125. const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
  2126. writeUint32(tfdt, 4, upper);
  2127. writeUint32(tfdt, 8, lower);
  2128. }
  2129. }
  2130. });
  2131. });
  2132. });
  2133. }
  2134. // TODO: Check if the last moof+mdat pair is part of the valid range
  2135. function segmentValidRange(data) {
  2136. const segmentedRange = {
  2137. valid: null,
  2138. remainder: null
  2139. };
  2140. const moofs = findBox(data, ['moof']);
  2141. if (moofs.length < 2) {
  2142. segmentedRange.remainder = data;
  2143. return segmentedRange;
  2144. }
  2145. const last = moofs[moofs.length - 1];
  2146. // Offset by 8 bytes; findBox offsets the start by as much
  2147. segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);
  2148. segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);
  2149. return segmentedRange;
  2150. }
  2151. function appendUint8Array(data1, data2) {
  2152. const temp = new Uint8Array(data1.length + data2.length);
  2153. temp.set(data1);
  2154. temp.set(data2, data1.length);
  2155. return temp;
  2156. }
  2157. function parseSamples(timeOffset, track) {
  2158. const seiSamples = [];
  2159. const videoData = track.samples;
  2160. const timescale = track.timescale;
  2161. const trackId = track.id;
  2162. let isHEVCFlavor = false;
  2163. const moofs = findBox(videoData, ['moof']);
  2164. moofs.map(moof => {
  2165. const moofOffset = moof.byteOffset - 8;
  2166. const trafs = findBox(moof, ['traf']);
  2167. trafs.map(traf => {
  2168. // get the base media decode time from the tfdt
  2169. const baseTime = findBox(traf, ['tfdt']).map(tfdt => {
  2170. const version = tfdt[0];
  2171. let result = readUint32(tfdt, 4);
  2172. if (version === 1) {
  2173. result *= Math.pow(2, 32);
  2174. result += readUint32(tfdt, 8);
  2175. }
  2176. return result / timescale;
  2177. })[0];
  2178. if (baseTime !== undefined) {
  2179. timeOffset = baseTime;
  2180. }
  2181. return findBox(traf, ['tfhd']).map(tfhd => {
  2182. const id = readUint32(tfhd, 4);
  2183. const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2184. const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2185. const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2186. const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2187. let defaultSampleDuration = 0;
  2188. const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2189. let defaultSampleSize = 0;
  2190. const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2191. let tfhdOffset = 8;
  2192. if (id === trackId) {
  2193. if (baseDataOffsetPresent) {
  2194. tfhdOffset += 8;
  2195. }
  2196. if (sampleDescriptionIndexPresent) {
  2197. tfhdOffset += 4;
  2198. }
  2199. if (defaultSampleDurationPresent) {
  2200. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2201. tfhdOffset += 4;
  2202. }
  2203. if (defaultSampleSizePresent) {
  2204. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2205. tfhdOffset += 4;
  2206. }
  2207. if (defaultSampleFlagsPresent) {
  2208. tfhdOffset += 4;
  2209. }
  2210. if (track.type === 'video') {
  2211. isHEVCFlavor = isHEVC(track.codec);
  2212. }
  2213. findBox(traf, ['trun']).map(trun => {
  2214. const version = trun[0];
  2215. const flags = readUint32(trun, 0) & 0xffffff;
  2216. const dataOffsetPresent = (flags & 0x000001) !== 0;
  2217. let dataOffset = 0;
  2218. const firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2219. const sampleDurationPresent = (flags & 0x000100) !== 0;
  2220. let sampleDuration = 0;
  2221. const sampleSizePresent = (flags & 0x000200) !== 0;
  2222. let sampleSize = 0;
  2223. const sampleFlagsPresent = (flags & 0x000400) !== 0;
  2224. const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2225. let compositionOffset = 0;
  2226. const sampleCount = readUint32(trun, 4);
  2227. let trunOffset = 8; // past version, flags, and sample count
  2228. if (dataOffsetPresent) {
  2229. dataOffset = readUint32(trun, trunOffset);
  2230. trunOffset += 4;
  2231. }
  2232. if (firstSampleFlagsPresent) {
  2233. trunOffset += 4;
  2234. }
  2235. let sampleOffset = dataOffset + moofOffset;
  2236. for (let ix = 0; ix < sampleCount; ix++) {
  2237. if (sampleDurationPresent) {
  2238. sampleDuration = readUint32(trun, trunOffset);
  2239. trunOffset += 4;
  2240. } else {
  2241. sampleDuration = defaultSampleDuration;
  2242. }
  2243. if (sampleSizePresent) {
  2244. sampleSize = readUint32(trun, trunOffset);
  2245. trunOffset += 4;
  2246. } else {
  2247. sampleSize = defaultSampleSize;
  2248. }
  2249. if (sampleFlagsPresent) {
  2250. trunOffset += 4;
  2251. }
  2252. if (sampleCompositionOffsetsPresent) {
  2253. if (version === 0) {
  2254. compositionOffset = readUint32(trun, trunOffset);
  2255. } else {
  2256. compositionOffset = readSint32(trun, trunOffset);
  2257. }
  2258. trunOffset += 4;
  2259. }
  2260. if (track.type === ElementaryStreamTypes.VIDEO) {
  2261. let naluTotalSize = 0;
  2262. while (naluTotalSize < sampleSize) {
  2263. const naluSize = readUint32(videoData, sampleOffset);
  2264. sampleOffset += 4;
  2265. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2266. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2267. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2268. }
  2269. sampleOffset += naluSize;
  2270. naluTotalSize += naluSize + 4;
  2271. }
  2272. }
  2273. timeOffset += sampleDuration / timescale;
  2274. }
  2275. });
  2276. }
  2277. });
  2278. });
  2279. });
  2280. return seiSamples;
  2281. }
  2282. function isHEVC(codec) {
  2283. if (!codec) {
  2284. return false;
  2285. }
  2286. const delimit = codec.indexOf('.');
  2287. const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  2288. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2289. // Dolby Vision
  2290. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2291. }
  2292. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2293. if (isHEVCFlavor) {
  2294. const naluType = naluHeader >> 1 & 0x3f;
  2295. return naluType === 39 || naluType === 40;
  2296. } else {
  2297. const naluType = naluHeader & 0x1f;
  2298. return naluType === 6;
  2299. }
  2300. }
  2301. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2302. const data = discardEPB(unescapedData);
  2303. let seiPtr = 0;
  2304. // skip nal header
  2305. seiPtr += headerSize;
  2306. let payloadType = 0;
  2307. let payloadSize = 0;
  2308. let b = 0;
  2309. while (seiPtr < data.length) {
  2310. payloadType = 0;
  2311. do {
  2312. if (seiPtr >= data.length) {
  2313. break;
  2314. }
  2315. b = data[seiPtr++];
  2316. payloadType += b;
  2317. } while (b === 0xff);
  2318. // Parse payload size.
  2319. payloadSize = 0;
  2320. do {
  2321. if (seiPtr >= data.length) {
  2322. break;
  2323. }
  2324. b = data[seiPtr++];
  2325. payloadSize += b;
  2326. } while (b === 0xff);
  2327. const leftOver = data.length - seiPtr;
  2328. // Create a variable to process the payload
  2329. let payPtr = seiPtr;
  2330. // Increment the seiPtr to the end of the payload
  2331. if (payloadSize < leftOver) {
  2332. seiPtr += payloadSize;
  2333. } else if (payloadSize > leftOver) {
  2334. // Some type of corruption has happened?
  2335. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  2336. // We might be able to parse some data, but let's be safe and ignore it.
  2337. break;
  2338. }
  2339. if (payloadType === 4) {
  2340. const countryCode = data[payPtr++];
  2341. if (countryCode === 181) {
  2342. const providerCode = readUint16(data, payPtr);
  2343. payPtr += 2;
  2344. if (providerCode === 49) {
  2345. const userStructure = readUint32(data, payPtr);
  2346. payPtr += 4;
  2347. if (userStructure === 0x47413934) {
  2348. const userDataType = data[payPtr++];
  2349. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2350. if (userDataType === 3) {
  2351. const firstByte = data[payPtr++];
  2352. const totalCCs = 0x1f & firstByte;
  2353. const enabled = 0x40 & firstByte;
  2354. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2355. const byteArray = new Uint8Array(totalBytes);
  2356. if (enabled) {
  2357. byteArray[0] = firstByte;
  2358. for (let i = 1; i < totalBytes; i++) {
  2359. byteArray[i] = data[payPtr++];
  2360. }
  2361. }
  2362. samples.push({
  2363. type: userDataType,
  2364. payloadType,
  2365. pts,
  2366. bytes: byteArray
  2367. });
  2368. }
  2369. }
  2370. }
  2371. }
  2372. } else if (payloadType === 5) {
  2373. if (payloadSize > 16) {
  2374. const uuidStrArray = [];
  2375. for (let i = 0; i < 16; i++) {
  2376. const _b = data[payPtr++].toString(16);
  2377. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2378. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2379. uuidStrArray.push('-');
  2380. }
  2381. }
  2382. const length = payloadSize - 16;
  2383. const userDataBytes = new Uint8Array(length);
  2384. for (let i = 0; i < length; i++) {
  2385. userDataBytes[i] = data[payPtr++];
  2386. }
  2387. samples.push({
  2388. payloadType,
  2389. pts,
  2390. uuid: uuidStrArray.join(''),
  2391. userData: utf8ArrayToStr(userDataBytes),
  2392. userDataBytes
  2393. });
  2394. }
  2395. }
  2396. }
  2397. }
  2398. /**
  2399. * remove Emulation Prevention bytes from a RBSP
  2400. */
  2401. function discardEPB(data) {
  2402. const length = data.byteLength;
  2403. const EPBPositions = [];
  2404. let i = 1;
  2405. // Find all `Emulation Prevention Bytes`
  2406. while (i < length - 2) {
  2407. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2408. EPBPositions.push(i + 2);
  2409. i += 2;
  2410. } else {
  2411. i++;
  2412. }
  2413. }
  2414. // If no Emulation Prevention Bytes were found just return the original
  2415. // array
  2416. if (EPBPositions.length === 0) {
  2417. return data;
  2418. }
  2419. // Create a new array to hold the NAL unit data
  2420. const newLength = length - EPBPositions.length;
  2421. const newData = new Uint8Array(newLength);
  2422. let sourceIndex = 0;
  2423. for (i = 0; i < newLength; sourceIndex++, i++) {
  2424. if (sourceIndex === EPBPositions[0]) {
  2425. // Skip this byte
  2426. sourceIndex++;
  2427. // Remove this position index
  2428. EPBPositions.shift();
  2429. }
  2430. newData[i] = data[sourceIndex];
  2431. }
  2432. return newData;
  2433. }
  2434. function parseEmsg(data) {
  2435. const version = data[0];
  2436. let schemeIdUri = '';
  2437. let value = '';
  2438. let timeScale = 0;
  2439. let presentationTimeDelta = 0;
  2440. let presentationTime = 0;
  2441. let eventDuration = 0;
  2442. let id = 0;
  2443. let offset = 0;
  2444. if (version === 0) {
  2445. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2446. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2447. offset += 1;
  2448. }
  2449. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2450. offset += 1;
  2451. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2452. value += bin2str(data.subarray(offset, offset + 1));
  2453. offset += 1;
  2454. }
  2455. value += bin2str(data.subarray(offset, offset + 1));
  2456. offset += 1;
  2457. timeScale = readUint32(data, 12);
  2458. presentationTimeDelta = readUint32(data, 16);
  2459. eventDuration = readUint32(data, 20);
  2460. id = readUint32(data, 24);
  2461. offset = 28;
  2462. } else if (version === 1) {
  2463. offset += 4;
  2464. timeScale = readUint32(data, offset);
  2465. offset += 4;
  2466. const leftPresentationTime = readUint32(data, offset);
  2467. offset += 4;
  2468. const rightPresentationTime = readUint32(data, offset);
  2469. offset += 4;
  2470. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  2471. if (!isSafeInteger(presentationTime)) {
  2472. presentationTime = Number.MAX_SAFE_INTEGER;
  2473. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2474. }
  2475. eventDuration = readUint32(data, offset);
  2476. offset += 4;
  2477. id = readUint32(data, offset);
  2478. offset += 4;
  2479. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2480. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2481. offset += 1;
  2482. }
  2483. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2484. offset += 1;
  2485. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2486. value += bin2str(data.subarray(offset, offset + 1));
  2487. offset += 1;
  2488. }
  2489. value += bin2str(data.subarray(offset, offset + 1));
  2490. offset += 1;
  2491. }
  2492. const payload = data.subarray(offset, data.byteLength);
  2493. return {
  2494. schemeIdUri,
  2495. value,
  2496. timeScale,
  2497. presentationTime,
  2498. presentationTimeDelta,
  2499. eventDuration,
  2500. id,
  2501. payload
  2502. };
  2503. }
  2504. function mp4Box(type, ...payload) {
  2505. const len = payload.length;
  2506. let size = 8;
  2507. let i = len;
  2508. while (i--) {
  2509. size += payload[i].byteLength;
  2510. }
  2511. const result = new Uint8Array(size);
  2512. result[0] = size >> 24 & 0xff;
  2513. result[1] = size >> 16 & 0xff;
  2514. result[2] = size >> 8 & 0xff;
  2515. result[3] = size & 0xff;
  2516. result.set(type, 4);
  2517. for (i = 0, size = 8; i < len; i++) {
  2518. result.set(payload[i], size);
  2519. size += payload[i].byteLength;
  2520. }
  2521. return result;
  2522. }
  2523. function mp4pssh(systemId, keyids, data) {
  2524. if (systemId.byteLength !== 16) {
  2525. throw new RangeError('Invalid system id');
  2526. }
  2527. let version;
  2528. let kids;
  2529. if (keyids) {
  2530. version = 1;
  2531. kids = new Uint8Array(keyids.length * 16);
  2532. for (let ix = 0; ix < keyids.length; ix++) {
  2533. const k = keyids[ix]; // uint8array
  2534. if (k.byteLength !== 16) {
  2535. throw new RangeError('Invalid key');
  2536. }
  2537. kids.set(k, ix * 16);
  2538. }
  2539. } else {
  2540. version = 0;
  2541. kids = new Uint8Array();
  2542. }
  2543. let kidCount;
  2544. if (version > 0) {
  2545. kidCount = new Uint8Array(4);
  2546. if (keyids.length > 0) {
  2547. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  2548. }
  2549. } else {
  2550. kidCount = new Uint8Array();
  2551. }
  2552. const dataSize = new Uint8Array(4);
  2553. if (data && data.byteLength > 0) {
  2554. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  2555. }
  2556. return mp4Box([112, 115, 115, 104], new Uint8Array([version, 0x00, 0x00, 0x00 // Flags
  2557. ]), systemId,
  2558. // 16 bytes
  2559. kidCount, kids, dataSize, data || new Uint8Array());
  2560. }
  2561. function parseMultiPssh(initData) {
  2562. const results = [];
  2563. if (initData instanceof ArrayBuffer) {
  2564. const length = initData.byteLength;
  2565. let offset = 0;
  2566. while (offset + 32 < length) {
  2567. const view = new DataView(initData, offset);
  2568. const pssh = parsePssh(view);
  2569. results.push(pssh);
  2570. offset += pssh.size;
  2571. }
  2572. }
  2573. return results;
  2574. }
  2575. function parsePssh(view) {
  2576. const size = view.getUint32(0);
  2577. const offset = view.byteOffset;
  2578. const length = view.byteLength;
  2579. if (length < size) {
  2580. return {
  2581. offset,
  2582. size: length
  2583. };
  2584. }
  2585. const type = view.getUint32(4);
  2586. if (type !== 0x70737368) {
  2587. return {
  2588. offset,
  2589. size
  2590. };
  2591. }
  2592. const version = view.getUint32(8) >>> 24;
  2593. if (version !== 0 && version !== 1) {
  2594. return {
  2595. offset,
  2596. size
  2597. };
  2598. }
  2599. const buffer = view.buffer;
  2600. const systemId = Hex.hexDump(new Uint8Array(buffer, offset + 12, 16));
  2601. const dataSizeOrKidCount = view.getUint32(28);
  2602. let kids = null;
  2603. let data = null;
  2604. if (version === 0) {
  2605. if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) {
  2606. return {
  2607. offset,
  2608. size
  2609. };
  2610. }
  2611. data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount);
  2612. } else if (version === 1) {
  2613. if (!dataSizeOrKidCount || length < offset + 32 + dataSizeOrKidCount * 16 + 16) {
  2614. return {
  2615. offset,
  2616. size
  2617. };
  2618. }
  2619. kids = [];
  2620. for (let i = 0; i < dataSizeOrKidCount; i++) {
  2621. kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));
  2622. }
  2623. }
  2624. return {
  2625. version,
  2626. systemId,
  2627. kids,
  2628. data,
  2629. offset,
  2630. size
  2631. };
  2632. }
  2633. let keyUriToKeyIdMap = {};
  2634. class LevelKey {
  2635. static clearKeyUriToKeyIdMap() {
  2636. keyUriToKeyIdMap = {};
  2637. }
  2638. constructor(method, uri, format, formatversions = [1], iv = null) {
  2639. this.uri = void 0;
  2640. this.method = void 0;
  2641. this.keyFormat = void 0;
  2642. this.keyFormatVersions = void 0;
  2643. this.encrypted = void 0;
  2644. this.isCommonEncryption = void 0;
  2645. this.iv = null;
  2646. this.key = null;
  2647. this.keyId = null;
  2648. this.pssh = null;
  2649. this.method = method;
  2650. this.uri = uri;
  2651. this.keyFormat = format;
  2652. this.keyFormatVersions = formatversions;
  2653. this.iv = iv;
  2654. this.encrypted = method ? method !== 'NONE' : false;
  2655. this.isCommonEncryption = this.encrypted && method !== 'AES-128';
  2656. }
  2657. isSupported() {
  2658. // If it's Segment encryption or No encryption, just select that key system
  2659. if (this.method) {
  2660. if (this.method === 'AES-128' || this.method === 'NONE') {
  2661. return true;
  2662. }
  2663. if (this.keyFormat === 'identity') {
  2664. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  2665. return this.method === 'SAMPLE-AES';
  2666. } else {
  2667. switch (this.keyFormat) {
  2668. case KeySystemFormats.FAIRPLAY:
  2669. case KeySystemFormats.WIDEVINE:
  2670. case KeySystemFormats.PLAYREADY:
  2671. case KeySystemFormats.CLEARKEY:
  2672. return ['ISO-23001-7', 'SAMPLE-AES', 'SAMPLE-AES-CENC', 'SAMPLE-AES-CTR'].indexOf(this.method) !== -1;
  2673. }
  2674. }
  2675. }
  2676. return false;
  2677. }
  2678. getDecryptData(sn) {
  2679. if (!this.encrypted || !this.uri) {
  2680. return null;
  2681. }
  2682. if (this.method === 'AES-128' && this.uri && !this.iv) {
  2683. if (typeof sn !== 'number') {
  2684. // We are fetching decryption data for a initialization segment
  2685. // If the segment was encrypted with AES-128
  2686. // It must have an IV defined. We cannot substitute the Segment Number in.
  2687. if (this.method === 'AES-128' && !this.iv) {
  2688. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  2689. }
  2690. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  2691. sn = 0;
  2692. }
  2693. const iv = createInitializationVector(sn);
  2694. const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  2695. return decryptdata;
  2696. }
  2697. // Initialize keyId if possible
  2698. const keyBytes = convertDataUriToArrayBytes(this.uri);
  2699. if (keyBytes) {
  2700. switch (this.keyFormat) {
  2701. case KeySystemFormats.WIDEVINE:
  2702. this.pssh = keyBytes;
  2703. // In case of widevine keyID is embedded in PSSH box. Read Key ID.
  2704. if (keyBytes.length >= 22) {
  2705. this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6);
  2706. }
  2707. break;
  2708. case KeySystemFormats.PLAYREADY:
  2709. {
  2710. const PlayReadyKeySystemUUID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);
  2711. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  2712. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  2713. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  2714. // Parse Playready WRMHeader XML
  2715. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);
  2716. const parser = new DOMParser();
  2717. const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');
  2718. const keyData = xmlDoc.getElementsByTagName('KID')[0];
  2719. if (keyData) {
  2720. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute('VALUE');
  2721. if (keyId) {
  2722. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  2723. // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID
  2724. // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID
  2725. changeEndianness(keyIdArray);
  2726. this.keyId = keyIdArray;
  2727. }
  2728. }
  2729. break;
  2730. }
  2731. default:
  2732. {
  2733. let keydata = keyBytes.subarray(0, 16);
  2734. if (keydata.length !== 16) {
  2735. const padded = new Uint8Array(16);
  2736. padded.set(keydata, 16 - keydata.length);
  2737. keydata = padded;
  2738. }
  2739. this.keyId = keydata;
  2740. break;
  2741. }
  2742. }
  2743. }
  2744. // Default behavior: assign a new keyId for each uri
  2745. if (!this.keyId || this.keyId.byteLength !== 16) {
  2746. let keyId = keyUriToKeyIdMap[this.uri];
  2747. if (!keyId) {
  2748. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  2749. keyId = new Uint8Array(16);
  2750. const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes
  2751. dv.setUint32(0, val);
  2752. keyUriToKeyIdMap[this.uri] = keyId;
  2753. }
  2754. this.keyId = keyId;
  2755. }
  2756. return this;
  2757. }
  2758. }
  2759. function createInitializationVector(segmentNumber) {
  2760. const uint8View = new Uint8Array(16);
  2761. for (let i = 12; i < 16; i++) {
  2762. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2763. }
  2764. return uint8View;
  2765. }
  2766. const VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  2767. function hasVariableReferences(str) {
  2768. return VARIABLE_REPLACEMENT_REGEX.test(str);
  2769. }
  2770. function substituteVariablesInAttributes(parsed, attr, attributeNames) {
  2771. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  2772. for (let i = attributeNames.length; i--;) {
  2773. const name = attributeNames[i];
  2774. const value = attr[name];
  2775. if (value) {
  2776. attr[name] = substituteVariables(parsed, value);
  2777. }
  2778. }
  2779. }
  2780. }
  2781. function substituteVariables(parsed, value) {
  2782. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  2783. const variableList = parsed.variableList;
  2784. return value.replace(VARIABLE_REPLACEMENT_REGEX, variableReference => {
  2785. const variableName = variableReference.substring(2, variableReference.length - 1);
  2786. const variableValue = variableList == null ? void 0 : variableList[variableName];
  2787. if (variableValue === undefined) {
  2788. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  2789. return variableReference;
  2790. }
  2791. return variableValue;
  2792. });
  2793. }
  2794. return value;
  2795. }
  2796. function addVariableDefinition(parsed, attr, parentUrl) {
  2797. let variableList = parsed.variableList;
  2798. if (!variableList) {
  2799. parsed.variableList = variableList = {};
  2800. }
  2801. let NAME;
  2802. let VALUE;
  2803. if ('QUERYPARAM' in attr) {
  2804. NAME = attr.QUERYPARAM;
  2805. try {
  2806. const searchParams = new self.URL(parentUrl).searchParams;
  2807. if (searchParams.has(NAME)) {
  2808. VALUE = searchParams.get(NAME);
  2809. } else {
  2810. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  2811. }
  2812. } catch (error) {
  2813. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  2814. }
  2815. } else {
  2816. NAME = attr.NAME;
  2817. VALUE = attr.VALUE;
  2818. }
  2819. if (NAME in variableList) {
  2820. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  2821. } else {
  2822. variableList[NAME] = VALUE || '';
  2823. }
  2824. }
  2825. function importVariableDefinition(parsed, attr, sourceVariableList) {
  2826. const IMPORT = attr.IMPORT;
  2827. if (sourceVariableList && IMPORT in sourceVariableList) {
  2828. let variableList = parsed.variableList;
  2829. if (!variableList) {
  2830. parsed.variableList = variableList = {};
  2831. }
  2832. variableList[IMPORT] = sourceVariableList[IMPORT];
  2833. } else {
  2834. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  2835. }
  2836. }
  2837. /**
  2838. * MediaSource helper
  2839. */
  2840. function getMediaSource(preferManagedMediaSource = true) {
  2841. if (typeof self === 'undefined') return undefined;
  2842. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  2843. return mms || self.MediaSource || self.WebKitMediaSource;
  2844. }
  2845. function isManagedMediaSource(source) {
  2846. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  2847. }
  2848. // from http://mp4ra.org/codecs.html
  2849. // values indicate codec selection preference (lower is higher priority)
  2850. const sampleEntryCodesISO = {
  2851. audio: {
  2852. a3ds: 1,
  2853. 'ac-3': 0.95,
  2854. 'ac-4': 1,
  2855. alac: 0.9,
  2856. alaw: 1,
  2857. dra1: 1,
  2858. 'dts+': 1,
  2859. 'dts-': 1,
  2860. dtsc: 1,
  2861. dtse: 1,
  2862. dtsh: 1,
  2863. 'ec-3': 0.9,
  2864. enca: 1,
  2865. fLaC: 0.9,
  2866. // MP4-RA listed codec entry for FLAC
  2867. flac: 0.9,
  2868. // legacy browser codec name for FLAC
  2869. FLAC: 0.9,
  2870. // some manifests may list "FLAC" with Apple's tools
  2871. g719: 1,
  2872. g726: 1,
  2873. m4ae: 1,
  2874. mha1: 1,
  2875. mha2: 1,
  2876. mhm1: 1,
  2877. mhm2: 1,
  2878. mlpa: 1,
  2879. mp4a: 1,
  2880. 'raw ': 1,
  2881. Opus: 1,
  2882. opus: 1,
  2883. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2884. samr: 1,
  2885. sawb: 1,
  2886. sawp: 1,
  2887. sevc: 1,
  2888. sqcp: 1,
  2889. ssmv: 1,
  2890. twos: 1,
  2891. ulaw: 1
  2892. },
  2893. video: {
  2894. avc1: 1,
  2895. avc2: 1,
  2896. avc3: 1,
  2897. avc4: 1,
  2898. avcp: 1,
  2899. av01: 0.8,
  2900. drac: 1,
  2901. dva1: 1,
  2902. dvav: 1,
  2903. dvh1: 0.7,
  2904. dvhe: 0.7,
  2905. encv: 1,
  2906. hev1: 0.75,
  2907. hvc1: 0.75,
  2908. mjp2: 1,
  2909. mp4v: 1,
  2910. mvc1: 1,
  2911. mvc2: 1,
  2912. mvc3: 1,
  2913. mvc4: 1,
  2914. resv: 1,
  2915. rv60: 1,
  2916. s263: 1,
  2917. svc1: 1,
  2918. svc2: 1,
  2919. 'vc-1': 1,
  2920. vp08: 1,
  2921. vp09: 0.9
  2922. },
  2923. text: {
  2924. stpp: 1,
  2925. wvtt: 1
  2926. }
  2927. };
  2928. function isCodecType(codec, type) {
  2929. const typeCodes = sampleEntryCodesISO[type];
  2930. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2931. }
  2932. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2933. return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2934. }
  2935. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2936. var _MediaSource$isTypeSu;
  2937. const MediaSource = getMediaSource(preferManagedMediaSource);
  2938. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2939. }
  2940. function mimeTypeForCodec(codec, type) {
  2941. return `${type}/mp4;codecs="${codec}"`;
  2942. }
  2943. function videoCodecPreferenceValue(videoCodec) {
  2944. if (videoCodec) {
  2945. const fourCC = videoCodec.substring(0, 4);
  2946. return sampleEntryCodesISO.video[fourCC];
  2947. }
  2948. return 2;
  2949. }
  2950. function codecsSetSelectionPreferenceValue(codecSet) {
  2951. return codecSet.split(',').reduce((num, fourCC) => {
  2952. const preferenceValue = sampleEntryCodesISO.video[fourCC];
  2953. if (preferenceValue) {
  2954. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2955. }
  2956. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2957. }, 0);
  2958. }
  2959. const CODEC_COMPATIBLE_NAMES = {};
  2960. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2961. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2962. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2963. }
  2964. // Idealy fLaC and Opus would be first (spec-compliant) but
  2965. // some browsers will report that fLaC is supported then fail.
  2966. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2967. const codecsToCheck = {
  2968. flac: ['flac', 'fLaC', 'FLAC'],
  2969. opus: ['opus', 'Opus']
  2970. }[lowerCaseCodec];
  2971. for (let i = 0; i < codecsToCheck.length; i++) {
  2972. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2973. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2974. return codecsToCheck[i];
  2975. }
  2976. }
  2977. return lowerCaseCodec;
  2978. }
  2979. const AUDIO_CODEC_REGEXP = /flac|opus/i;
  2980. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2981. return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2982. }
  2983. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2984. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2985. // so use level codec is parsed codec is unavailable or incomplete
  2986. if (parsedCodec && parsedCodec !== 'mp4a') {
  2987. return parsedCodec;
  2988. }
  2989. return levelCodec ? levelCodec.split(',')[0] : levelCodec;
  2990. }
  2991. function convertAVC1ToAVCOTI(codec) {
  2992. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2993. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2994. const codecs = codec.split(',');
  2995. for (let i = 0; i < codecs.length; i++) {
  2996. const avcdata = codecs[i].split('.');
  2997. if (avcdata.length > 2) {
  2998. let result = avcdata.shift() + '.';
  2999. result += parseInt(avcdata.shift()).toString(16);
  3000. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  3001. codecs[i] = result;
  3002. }
  3003. }
  3004. return codecs.join(',');
  3005. }
  3006. 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;
  3007. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  3008. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  3009. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  3010. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  3011. /(?!#) *(\S[^\r\n]*)/.source,
  3012. // segment URI, group 3 => the URI (note newline is not eaten)
  3013. /#EXT-X-BYTERANGE:*(.+)/.source,
  3014. // next segment's byterange, group 4 => range spec (x@y)
  3015. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  3016. // next segment's program date/time group 5 => the datetime spec
  3017. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  3018. ].join('|'), 'g');
  3019. const LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
  3020. class M3U8Parser {
  3021. static findGroup(groups, mediaGroupId) {
  3022. for (let i = 0; i < groups.length; i++) {
  3023. const group = groups[i];
  3024. if (group.id === mediaGroupId) {
  3025. return group;
  3026. }
  3027. }
  3028. }
  3029. static resolve(url, baseUrl) {
  3030. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  3031. alwaysNormalize: true
  3032. });
  3033. }
  3034. static isMediaPlaylist(str) {
  3035. return IS_MEDIA_PLAYLIST.test(str);
  3036. }
  3037. static parseMasterPlaylist(string, baseurl) {
  3038. const hasVariableRefs = hasVariableReferences(string) ;
  3039. const parsed = {
  3040. contentSteering: null,
  3041. levels: [],
  3042. playlistParsingError: null,
  3043. sessionData: null,
  3044. sessionKeys: null,
  3045. startTimeOffset: null,
  3046. variableList: null,
  3047. hasVariableRefs
  3048. };
  3049. const levelsWithKnownCodecs = [];
  3050. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  3051. let result;
  3052. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  3053. if (result[1]) {
  3054. var _level$unknownCodecs;
  3055. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  3056. const attrs = new AttrList(result[1]);
  3057. {
  3058. substituteVariablesInAttributes(parsed, attrs, ['CODECS', 'SUPPLEMENTAL-CODECS', 'ALLOWED-CPC', 'PATHWAY-ID', 'STABLE-VARIANT-ID', 'AUDIO', 'VIDEO', 'SUBTITLES', 'CLOSED-CAPTIONS', 'NAME']);
  3059. }
  3060. const uri = substituteVariables(parsed, result[2]) ;
  3061. const level = {
  3062. attrs,
  3063. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  3064. name: attrs.NAME,
  3065. url: M3U8Parser.resolve(uri, baseurl)
  3066. };
  3067. const resolution = attrs.decimalResolution('RESOLUTION');
  3068. if (resolution) {
  3069. level.width = resolution.width;
  3070. level.height = resolution.height;
  3071. }
  3072. setCodecs(attrs.CODECS, level);
  3073. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  3074. levelsWithKnownCodecs.push(level);
  3075. }
  3076. parsed.levels.push(level);
  3077. } else if (result[3]) {
  3078. const tag = result[3];
  3079. const attributes = result[4];
  3080. switch (tag) {
  3081. case 'SESSION-DATA':
  3082. {
  3083. // #EXT-X-SESSION-DATA
  3084. const sessionAttrs = new AttrList(attributes);
  3085. {
  3086. substituteVariablesInAttributes(parsed, sessionAttrs, ['DATA-ID', 'LANGUAGE', 'VALUE', 'URI']);
  3087. }
  3088. const dataId = sessionAttrs['DATA-ID'];
  3089. if (dataId) {
  3090. if (parsed.sessionData === null) {
  3091. parsed.sessionData = {};
  3092. }
  3093. parsed.sessionData[dataId] = sessionAttrs;
  3094. }
  3095. break;
  3096. }
  3097. case 'SESSION-KEY':
  3098. {
  3099. // #EXT-X-SESSION-KEY
  3100. const sessionKey = parseKey(attributes, baseurl, parsed);
  3101. if (sessionKey.encrypted && sessionKey.isSupported()) {
  3102. if (parsed.sessionKeys === null) {
  3103. parsed.sessionKeys = [];
  3104. }
  3105. parsed.sessionKeys.push(sessionKey);
  3106. } else {
  3107. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  3108. }
  3109. break;
  3110. }
  3111. case 'DEFINE':
  3112. {
  3113. // #EXT-X-DEFINE
  3114. {
  3115. const variableAttributes = new AttrList(attributes);
  3116. substituteVariablesInAttributes(parsed, variableAttributes, ['NAME', 'VALUE', 'QUERYPARAM']);
  3117. addVariableDefinition(parsed, variableAttributes, baseurl);
  3118. }
  3119. break;
  3120. }
  3121. case 'CONTENT-STEERING':
  3122. {
  3123. // #EXT-X-CONTENT-STEERING
  3124. const contentSteeringAttributes = new AttrList(attributes);
  3125. {
  3126. substituteVariablesInAttributes(parsed, contentSteeringAttributes, ['SERVER-URI', 'PATHWAY-ID']);
  3127. }
  3128. parsed.contentSteering = {
  3129. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  3130. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  3131. };
  3132. break;
  3133. }
  3134. case 'START':
  3135. {
  3136. // #EXT-X-START
  3137. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  3138. break;
  3139. }
  3140. }
  3141. }
  3142. }
  3143. // Filter out levels with unknown codecs if it does not remove all levels
  3144. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  3145. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  3146. if (parsed.levels.length === 0) {
  3147. parsed.playlistParsingError = new Error('no levels found in manifest');
  3148. }
  3149. return parsed;
  3150. }
  3151. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  3152. let result;
  3153. const results = {};
  3154. const levels = parsed.levels;
  3155. const groupsByType = {
  3156. AUDIO: levels.map(level => ({
  3157. id: level.attrs.AUDIO,
  3158. audioCodec: level.audioCodec
  3159. })),
  3160. SUBTITLES: levels.map(level => ({
  3161. id: level.attrs.SUBTITLES,
  3162. textCodec: level.textCodec
  3163. })),
  3164. 'CLOSED-CAPTIONS': []
  3165. };
  3166. let id = 0;
  3167. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  3168. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  3169. const attrs = new AttrList(result[1]);
  3170. const type = attrs.TYPE;
  3171. if (type) {
  3172. const groups = groupsByType[type];
  3173. const medias = results[type] || [];
  3174. results[type] = medias;
  3175. {
  3176. substituteVariablesInAttributes(parsed, attrs, ['URI', 'GROUP-ID', 'LANGUAGE', 'ASSOC-LANGUAGE', 'STABLE-RENDITION-ID', 'NAME', 'INSTREAM-ID', 'CHARACTERISTICS', 'CHANNELS']);
  3177. }
  3178. const lang = attrs.LANGUAGE;
  3179. const assocLang = attrs['ASSOC-LANGUAGE'];
  3180. const channels = attrs.CHANNELS;
  3181. const characteristics = attrs.CHARACTERISTICS;
  3182. const instreamId = attrs['INSTREAM-ID'];
  3183. const media = {
  3184. attrs,
  3185. bitrate: 0,
  3186. id: id++,
  3187. groupId: attrs['GROUP-ID'] || '',
  3188. name: attrs.NAME || lang || '',
  3189. type,
  3190. default: attrs.bool('DEFAULT'),
  3191. autoselect: attrs.bool('AUTOSELECT'),
  3192. forced: attrs.bool('FORCED'),
  3193. lang,
  3194. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  3195. };
  3196. if (assocLang) {
  3197. media.assocLang = assocLang;
  3198. }
  3199. if (channels) {
  3200. media.channels = channels;
  3201. }
  3202. if (characteristics) {
  3203. media.characteristics = characteristics;
  3204. }
  3205. if (instreamId) {
  3206. media.instreamId = instreamId;
  3207. }
  3208. if (groups != null && groups.length) {
  3209. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  3210. // If we don't find the track signalled, lets use the first audio groups codec we have
  3211. // Acting as a best guess
  3212. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  3213. assignCodec(media, groupCodec, 'audioCodec');
  3214. assignCodec(media, groupCodec, 'textCodec');
  3215. }
  3216. medias.push(media);
  3217. }
  3218. }
  3219. return results;
  3220. }
  3221. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  3222. const level = new LevelDetails(baseurl);
  3223. const fragments = level.fragments;
  3224. // The most recent init segment seen (applies to all subsequent segments)
  3225. let currentInitSegment = null;
  3226. let currentSN = 0;
  3227. let currentPart = 0;
  3228. let totalduration = 0;
  3229. let discontinuityCounter = 0;
  3230. let prevFrag = null;
  3231. let frag = new Fragment(type, baseurl);
  3232. let result;
  3233. let i;
  3234. let levelkeys;
  3235. let firstPdtIndex = -1;
  3236. let createNextFrag = false;
  3237. let nextByteRange = null;
  3238. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  3239. level.m3u8 = string;
  3240. level.hasVariableRefs = hasVariableReferences(string) ;
  3241. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  3242. if (createNextFrag) {
  3243. createNextFrag = false;
  3244. frag = new Fragment(type, baseurl);
  3245. // setup the next fragment for part loading
  3246. frag.start = totalduration;
  3247. frag.sn = currentSN;
  3248. frag.cc = discontinuityCounter;
  3249. frag.level = id;
  3250. if (currentInitSegment) {
  3251. frag.initSegment = currentInitSegment;
  3252. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3253. currentInitSegment.rawProgramDateTime = null;
  3254. if (nextByteRange) {
  3255. frag.setByteRange(nextByteRange);
  3256. nextByteRange = null;
  3257. }
  3258. }
  3259. }
  3260. const duration = result[1];
  3261. if (duration) {
  3262. // INF
  3263. frag.duration = parseFloat(duration);
  3264. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3265. const title = (' ' + result[2]).slice(1);
  3266. frag.title = title || null;
  3267. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  3268. } else if (result[3]) {
  3269. // url
  3270. if (isFiniteNumber(frag.duration)) {
  3271. frag.start = totalduration;
  3272. if (levelkeys) {
  3273. setFragLevelKeys(frag, levelkeys, level);
  3274. }
  3275. frag.sn = currentSN;
  3276. frag.level = id;
  3277. frag.cc = discontinuityCounter;
  3278. fragments.push(frag);
  3279. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3280. const uri = (' ' + result[3]).slice(1);
  3281. frag.relurl = substituteVariables(level, uri) ;
  3282. assignProgramDateTime(frag, prevFrag);
  3283. prevFrag = frag;
  3284. totalduration += frag.duration;
  3285. currentSN++;
  3286. currentPart = 0;
  3287. createNextFrag = true;
  3288. }
  3289. } else if (result[4]) {
  3290. // X-BYTERANGE
  3291. const data = (' ' + result[4]).slice(1);
  3292. if (prevFrag) {
  3293. frag.setByteRange(data, prevFrag);
  3294. } else {
  3295. frag.setByteRange(data);
  3296. }
  3297. } else if (result[5]) {
  3298. // PROGRAM-DATE-TIME
  3299. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3300. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  3301. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  3302. if (firstPdtIndex === -1) {
  3303. firstPdtIndex = fragments.length;
  3304. }
  3305. } else {
  3306. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  3307. if (!result) {
  3308. logger.warn('No matches on slow regex match for level playlist!');
  3309. continue;
  3310. }
  3311. for (i = 1; i < result.length; i++) {
  3312. if (typeof result[i] !== 'undefined') {
  3313. break;
  3314. }
  3315. }
  3316. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3317. const tag = (' ' + result[i]).slice(1);
  3318. const value1 = (' ' + result[i + 1]).slice(1);
  3319. const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  3320. switch (tag) {
  3321. case 'PLAYLIST-TYPE':
  3322. level.type = value1.toUpperCase();
  3323. break;
  3324. case 'MEDIA-SEQUENCE':
  3325. currentSN = level.startSN = parseInt(value1);
  3326. break;
  3327. case 'SKIP':
  3328. {
  3329. const skipAttrs = new AttrList(value1);
  3330. {
  3331. substituteVariablesInAttributes(level, skipAttrs, ['RECENTLY-REMOVED-DATERANGES']);
  3332. }
  3333. const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  3334. if (isFiniteNumber(skippedSegments)) {
  3335. level.skippedSegments = skippedSegments;
  3336. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  3337. for (let _i = skippedSegments; _i--;) {
  3338. fragments.unshift(null);
  3339. }
  3340. currentSN += skippedSegments;
  3341. }
  3342. const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  3343. if (recentlyRemovedDateranges) {
  3344. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  3345. }
  3346. break;
  3347. }
  3348. case 'TARGETDURATION':
  3349. level.targetduration = Math.max(parseInt(value1), 1);
  3350. break;
  3351. case 'VERSION':
  3352. level.version = parseInt(value1);
  3353. break;
  3354. case 'INDEPENDENT-SEGMENTS':
  3355. case 'EXTM3U':
  3356. break;
  3357. case 'ENDLIST':
  3358. level.live = false;
  3359. break;
  3360. case '#':
  3361. if (value1 || value2) {
  3362. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  3363. }
  3364. break;
  3365. case 'DISCONTINUITY':
  3366. discontinuityCounter++;
  3367. frag.tagList.push(['DIS']);
  3368. break;
  3369. case 'GAP':
  3370. frag.gap = true;
  3371. frag.tagList.push([tag]);
  3372. break;
  3373. case 'BITRATE':
  3374. frag.tagList.push([tag, value1]);
  3375. break;
  3376. case 'DATERANGE':
  3377. {
  3378. const dateRangeAttr = new AttrList(value1);
  3379. {
  3380. substituteVariablesInAttributes(level, dateRangeAttr, ['ID', 'CLASS', 'START-DATE', 'END-DATE', 'SCTE35-CMD', 'SCTE35-OUT', 'SCTE35-IN']);
  3381. substituteVariablesInAttributes(level, dateRangeAttr, dateRangeAttr.clientAttrs);
  3382. }
  3383. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  3384. if (dateRange.isValid || level.skippedSegments) {
  3385. level.dateRanges[dateRange.id] = dateRange;
  3386. } else {
  3387. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  3388. }
  3389. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  3390. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  3391. break;
  3392. }
  3393. case 'DEFINE':
  3394. {
  3395. {
  3396. const variableAttributes = new AttrList(value1);
  3397. substituteVariablesInAttributes(level, variableAttributes, ['NAME', 'VALUE', 'IMPORT', 'QUERYPARAM']);
  3398. if ('IMPORT' in variableAttributes) {
  3399. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  3400. } else {
  3401. addVariableDefinition(level, variableAttributes, baseurl);
  3402. }
  3403. }
  3404. break;
  3405. }
  3406. case 'DISCONTINUITY-SEQUENCE':
  3407. discontinuityCounter = parseInt(value1);
  3408. break;
  3409. case 'KEY':
  3410. {
  3411. const levelKey = parseKey(value1, baseurl, level);
  3412. if (levelKey.isSupported()) {
  3413. if (levelKey.method === 'NONE') {
  3414. levelkeys = undefined;
  3415. break;
  3416. }
  3417. if (!levelkeys) {
  3418. levelkeys = {};
  3419. }
  3420. if (levelkeys[levelKey.keyFormat]) {
  3421. levelkeys = _extends({}, levelkeys);
  3422. }
  3423. levelkeys[levelKey.keyFormat] = levelKey;
  3424. } else {
  3425. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  3426. }
  3427. break;
  3428. }
  3429. case 'START':
  3430. level.startTimeOffset = parseStartTimeOffset(value1);
  3431. break;
  3432. case 'MAP':
  3433. {
  3434. const mapAttrs = new AttrList(value1);
  3435. {
  3436. substituteVariablesInAttributes(level, mapAttrs, ['BYTERANGE', 'URI']);
  3437. }
  3438. if (frag.duration) {
  3439. // Initial segment tag is after segment duration tag.
  3440. // #EXTINF: 6.0
  3441. // #EXT-X-MAP:URI="init.mp4
  3442. const init = new Fragment(type, baseurl);
  3443. setInitSegment(init, mapAttrs, id, levelkeys);
  3444. currentInitSegment = init;
  3445. frag.initSegment = currentInitSegment;
  3446. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  3447. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3448. }
  3449. } else {
  3450. // Initial segment tag is before segment duration tag
  3451. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  3452. const end = frag.byteRangeEndOffset;
  3453. if (end) {
  3454. const start = frag.byteRangeStartOffset;
  3455. nextByteRange = `${end - start}@${start}`;
  3456. } else {
  3457. nextByteRange = null;
  3458. }
  3459. setInitSegment(frag, mapAttrs, id, levelkeys);
  3460. currentInitSegment = frag;
  3461. createNextFrag = true;
  3462. }
  3463. break;
  3464. }
  3465. case 'SERVER-CONTROL':
  3466. {
  3467. const serverControlAttrs = new AttrList(value1);
  3468. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  3469. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  3470. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  3471. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  3472. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  3473. break;
  3474. }
  3475. case 'PART-INF':
  3476. {
  3477. const partInfAttrs = new AttrList(value1);
  3478. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  3479. break;
  3480. }
  3481. case 'PART':
  3482. {
  3483. let partList = level.partList;
  3484. if (!partList) {
  3485. partList = level.partList = [];
  3486. }
  3487. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  3488. const index = currentPart++;
  3489. const partAttrs = new AttrList(value1);
  3490. {
  3491. substituteVariablesInAttributes(level, partAttrs, ['BYTERANGE', 'URI']);
  3492. }
  3493. const part = new Part(partAttrs, frag, baseurl, index, previousFragmentPart);
  3494. partList.push(part);
  3495. frag.duration += part.duration;
  3496. break;
  3497. }
  3498. case 'PRELOAD-HINT':
  3499. {
  3500. const preloadHintAttrs = new AttrList(value1);
  3501. {
  3502. substituteVariablesInAttributes(level, preloadHintAttrs, ['URI']);
  3503. }
  3504. level.preloadHint = preloadHintAttrs;
  3505. break;
  3506. }
  3507. case 'RENDITION-REPORT':
  3508. {
  3509. const renditionReportAttrs = new AttrList(value1);
  3510. {
  3511. substituteVariablesInAttributes(level, renditionReportAttrs, ['URI']);
  3512. }
  3513. level.renditionReports = level.renditionReports || [];
  3514. level.renditionReports.push(renditionReportAttrs);
  3515. break;
  3516. }
  3517. default:
  3518. logger.warn(`line parsed but not handled: ${result}`);
  3519. break;
  3520. }
  3521. }
  3522. }
  3523. if (prevFrag && !prevFrag.relurl) {
  3524. fragments.pop();
  3525. totalduration -= prevFrag.duration;
  3526. if (level.partList) {
  3527. level.fragmentHint = prevFrag;
  3528. }
  3529. } else if (level.partList) {
  3530. assignProgramDateTime(frag, prevFrag);
  3531. frag.cc = discontinuityCounter;
  3532. level.fragmentHint = frag;
  3533. if (levelkeys) {
  3534. setFragLevelKeys(frag, levelkeys, level);
  3535. }
  3536. }
  3537. const fragmentLength = fragments.length;
  3538. const firstFragment = fragments[0];
  3539. const lastFragment = fragments[fragmentLength - 1];
  3540. totalduration += level.skippedSegments * level.targetduration;
  3541. if (totalduration > 0 && fragmentLength && lastFragment) {
  3542. level.averagetargetduration = totalduration / fragmentLength;
  3543. const lastSn = lastFragment.sn;
  3544. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  3545. if (!level.live) {
  3546. lastFragment.endList = true;
  3547. }
  3548. if (firstFragment) {
  3549. level.startCC = firstFragment.cc;
  3550. }
  3551. } else {
  3552. level.endSN = 0;
  3553. level.startCC = 0;
  3554. }
  3555. if (level.fragmentHint) {
  3556. totalduration += level.fragmentHint.duration;
  3557. }
  3558. level.totalduration = totalduration;
  3559. level.endCC = discontinuityCounter;
  3560. /**
  3561. * Backfill any missing PDT values
  3562. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  3563. * one or more Media Segment URIs, the client SHOULD extrapolate
  3564. * backward from that tag (using EXTINF durations and/or media
  3565. * timestamps) to associate dates with those segments."
  3566. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  3567. * computed.
  3568. */
  3569. if (firstPdtIndex > 0) {
  3570. backfillProgramDateTimes(fragments, firstPdtIndex);
  3571. }
  3572. return level;
  3573. }
  3574. }
  3575. function parseKey(keyTagAttributes, baseurl, parsed) {
  3576. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  3577. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  3578. const keyAttrs = new AttrList(keyTagAttributes);
  3579. {
  3580. substituteVariablesInAttributes(parsed, keyAttrs, ['KEYFORMAT', 'KEYFORMATVERSIONS', 'URI', 'IV', 'URI']);
  3581. }
  3582. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  3583. const decrypturi = keyAttrs.URI;
  3584. const decryptiv = keyAttrs.hexadecimalInteger('IV');
  3585. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  3586. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  3587. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  3588. if (decrypturi && keyAttrs.IV && !decryptiv) {
  3589. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  3590. }
  3591. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  3592. // No uri is allowed when METHOD is NONE
  3593. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  3594. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  3595. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
  3596. }
  3597. function parseStartTimeOffset(startAttributes) {
  3598. const startAttrs = new AttrList(startAttributes);
  3599. const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  3600. if (isFiniteNumber(startTimeOffset)) {
  3601. return startTimeOffset;
  3602. }
  3603. return null;
  3604. }
  3605. function setCodecs(codecsAttributeValue, level) {
  3606. let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);
  3607. ['video', 'audio', 'text'].forEach(type => {
  3608. const filtered = codecs.filter(codec => isCodecType(codec, type));
  3609. if (filtered.length) {
  3610. // Comma separated list of all codecs for type
  3611. level[`${type}Codec`] = filtered.join(',');
  3612. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  3613. codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);
  3614. }
  3615. });
  3616. level.unknownCodecs = codecs;
  3617. }
  3618. function assignCodec(media, groupItem, codecProperty) {
  3619. const codecValue = groupItem[codecProperty];
  3620. if (codecValue) {
  3621. media[codecProperty] = codecValue;
  3622. }
  3623. }
  3624. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  3625. let fragPrev = fragments[firstPdtIndex];
  3626. for (let i = firstPdtIndex; i--;) {
  3627. const frag = fragments[i];
  3628. // Exit on delta-playlist skipped segments
  3629. if (!frag) {
  3630. return;
  3631. }
  3632. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  3633. fragPrev = frag;
  3634. }
  3635. }
  3636. function assignProgramDateTime(frag, prevFrag) {
  3637. if (frag.rawProgramDateTime) {
  3638. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  3639. } else if (prevFrag != null && prevFrag.programDateTime) {
  3640. frag.programDateTime = prevFrag.endProgramDateTime;
  3641. }
  3642. if (!isFiniteNumber(frag.programDateTime)) {
  3643. frag.programDateTime = null;
  3644. frag.rawProgramDateTime = null;
  3645. }
  3646. }
  3647. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  3648. frag.relurl = mapAttrs.URI;
  3649. if (mapAttrs.BYTERANGE) {
  3650. frag.setByteRange(mapAttrs.BYTERANGE);
  3651. }
  3652. frag.level = id;
  3653. frag.sn = 'initSegment';
  3654. if (levelkeys) {
  3655. frag.levelkeys = levelkeys;
  3656. }
  3657. frag.initSegment = null;
  3658. }
  3659. function setFragLevelKeys(frag, levelkeys, level) {
  3660. frag.levelkeys = levelkeys;
  3661. const {
  3662. encryptedFragments
  3663. } = level;
  3664. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {
  3665. encryptedFragments.push(frag);
  3666. }
  3667. }
  3668. var PlaylistContextType = {
  3669. MANIFEST: "manifest",
  3670. LEVEL: "level",
  3671. AUDIO_TRACK: "audioTrack",
  3672. SUBTITLE_TRACK: "subtitleTrack"
  3673. };
  3674. var PlaylistLevelType = {
  3675. MAIN: "main",
  3676. AUDIO: "audio",
  3677. SUBTITLE: "subtitle"
  3678. };
  3679. function mapContextToLevelType(context) {
  3680. const {
  3681. type
  3682. } = context;
  3683. switch (type) {
  3684. case PlaylistContextType.AUDIO_TRACK:
  3685. return PlaylistLevelType.AUDIO;
  3686. case PlaylistContextType.SUBTITLE_TRACK:
  3687. return PlaylistLevelType.SUBTITLE;
  3688. default:
  3689. return PlaylistLevelType.MAIN;
  3690. }
  3691. }
  3692. function getResponseUrl(response, context) {
  3693. let url = response.url;
  3694. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3695. // data-uri mode also not supported (but no need to detect redirection)
  3696. if (url === undefined || url.indexOf('data:') === 0) {
  3697. // fallback to initial URL
  3698. url = context.url;
  3699. }
  3700. return url;
  3701. }
  3702. class PlaylistLoader {
  3703. constructor(hls) {
  3704. this.hls = void 0;
  3705. this.loaders = Object.create(null);
  3706. this.variableList = null;
  3707. this.hls = hls;
  3708. this.registerListeners();
  3709. }
  3710. startLoad(startPosition) {}
  3711. stopLoad() {
  3712. this.destroyInternalLoaders();
  3713. }
  3714. registerListeners() {
  3715. const {
  3716. hls
  3717. } = this;
  3718. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3719. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3720. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3721. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3722. }
  3723. unregisterListeners() {
  3724. const {
  3725. hls
  3726. } = this;
  3727. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3728. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3729. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3730. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3731. }
  3732. /**
  3733. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  3734. */
  3735. createInternalLoader(context) {
  3736. const config = this.hls.config;
  3737. const PLoader = config.pLoader;
  3738. const Loader = config.loader;
  3739. const InternalLoader = PLoader || Loader;
  3740. const loader = new InternalLoader(config);
  3741. this.loaders[context.type] = loader;
  3742. return loader;
  3743. }
  3744. getInternalLoader(context) {
  3745. return this.loaders[context.type];
  3746. }
  3747. resetInternalLoader(contextType) {
  3748. if (this.loaders[contextType]) {
  3749. delete this.loaders[contextType];
  3750. }
  3751. }
  3752. /**
  3753. * Call `destroy` on all internal loader instances mapped (one per context type)
  3754. */
  3755. destroyInternalLoaders() {
  3756. for (const contextType in this.loaders) {
  3757. const loader = this.loaders[contextType];
  3758. if (loader) {
  3759. loader.destroy();
  3760. }
  3761. this.resetInternalLoader(contextType);
  3762. }
  3763. }
  3764. destroy() {
  3765. this.variableList = null;
  3766. this.unregisterListeners();
  3767. this.destroyInternalLoaders();
  3768. }
  3769. onManifestLoading(event, data) {
  3770. const {
  3771. url
  3772. } = data;
  3773. this.variableList = null;
  3774. this.load({
  3775. id: null,
  3776. level: 0,
  3777. responseType: 'text',
  3778. type: PlaylistContextType.MANIFEST,
  3779. url,
  3780. deliveryDirectives: null
  3781. });
  3782. }
  3783. onLevelLoading(event, data) {
  3784. const {
  3785. id,
  3786. level,
  3787. pathwayId,
  3788. url,
  3789. deliveryDirectives
  3790. } = data;
  3791. this.load({
  3792. id,
  3793. level,
  3794. pathwayId,
  3795. responseType: 'text',
  3796. type: PlaylistContextType.LEVEL,
  3797. url,
  3798. deliveryDirectives
  3799. });
  3800. }
  3801. onAudioTrackLoading(event, data) {
  3802. const {
  3803. id,
  3804. groupId,
  3805. url,
  3806. deliveryDirectives
  3807. } = data;
  3808. this.load({
  3809. id,
  3810. groupId,
  3811. level: null,
  3812. responseType: 'text',
  3813. type: PlaylistContextType.AUDIO_TRACK,
  3814. url,
  3815. deliveryDirectives
  3816. });
  3817. }
  3818. onSubtitleTrackLoading(event, data) {
  3819. const {
  3820. id,
  3821. groupId,
  3822. url,
  3823. deliveryDirectives
  3824. } = data;
  3825. this.load({
  3826. id,
  3827. groupId,
  3828. level: null,
  3829. responseType: 'text',
  3830. type: PlaylistContextType.SUBTITLE_TRACK,
  3831. url,
  3832. deliveryDirectives
  3833. });
  3834. }
  3835. load(context) {
  3836. var _context$deliveryDire;
  3837. const config = this.hls.config;
  3838. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  3839. // Check if a loader for this context already exists
  3840. let loader = this.getInternalLoader(context);
  3841. if (loader) {
  3842. const loaderContext = loader.context;
  3843. if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) {
  3844. // same URL can't overlap
  3845. logger.trace('[playlist-loader]: playlist request ongoing');
  3846. return;
  3847. }
  3848. logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  3849. loader.abort();
  3850. }
  3851. // apply different configs for retries depending on
  3852. // context (manifest, level, audio/subs playlist)
  3853. let loadPolicy;
  3854. if (context.type === PlaylistContextType.MANIFEST) {
  3855. loadPolicy = config.manifestLoadPolicy.default;
  3856. } else {
  3857. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  3858. timeoutRetry: null,
  3859. errorRetry: null
  3860. });
  3861. }
  3862. loader = this.createInternalLoader(context);
  3863. // Override level/track timeout for LL-HLS requests
  3864. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  3865. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  3866. let levelDetails;
  3867. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  3868. levelDetails = this.hls.levels[context.level].details;
  3869. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  3870. levelDetails = this.hls.audioTracks[context.id].details;
  3871. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  3872. levelDetails = this.hls.subtitleTracks[context.id].details;
  3873. }
  3874. if (levelDetails) {
  3875. const partTarget = levelDetails.partTarget;
  3876. const targetDuration = levelDetails.targetduration;
  3877. if (partTarget && targetDuration) {
  3878. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  3879. loadPolicy = _extends({}, loadPolicy, {
  3880. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  3881. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  3882. });
  3883. }
  3884. }
  3885. }
  3886. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  3887. const loaderConfig = {
  3888. loadPolicy,
  3889. timeout: loadPolicy.maxLoadTimeMs,
  3890. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  3891. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  3892. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  3893. };
  3894. const loaderCallbacks = {
  3895. onSuccess: (response, stats, context, networkDetails) => {
  3896. const loader = this.getInternalLoader(context);
  3897. this.resetInternalLoader(context.type);
  3898. const string = response.data;
  3899. // Validate if it is an M3U8 at all
  3900. if (string.indexOf('#EXTM3U') !== 0) {
  3901. this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  3902. return;
  3903. }
  3904. stats.parsing.start = performance.now();
  3905. if (M3U8Parser.isMediaPlaylist(string)) {
  3906. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  3907. } else {
  3908. this.handleMasterPlaylist(response, stats, context, networkDetails);
  3909. }
  3910. },
  3911. onError: (response, context, networkDetails, stats) => {
  3912. this.handleNetworkError(context, networkDetails, false, response, stats);
  3913. },
  3914. onTimeout: (stats, context, networkDetails) => {
  3915. this.handleNetworkError(context, networkDetails, true, undefined, stats);
  3916. }
  3917. };
  3918. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  3919. loader.load(context, loaderConfig, loaderCallbacks);
  3920. }
  3921. handleMasterPlaylist(response, stats, context, networkDetails) {
  3922. const hls = this.hls;
  3923. const string = response.data;
  3924. const url = getResponseUrl(response, context);
  3925. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  3926. if (parsedResult.playlistParsingError) {
  3927. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  3928. return;
  3929. }
  3930. const {
  3931. contentSteering,
  3932. levels,
  3933. sessionData,
  3934. sessionKeys,
  3935. startTimeOffset,
  3936. variableList
  3937. } = parsedResult;
  3938. this.variableList = variableList;
  3939. const {
  3940. AUDIO: audioTracks = [],
  3941. SUBTITLES: subtitles,
  3942. 'CLOSED-CAPTIONS': captions
  3943. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  3944. if (audioTracks.length) {
  3945. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3946. const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);
  3947. // if no embedded audio track defined, but audio codec signaled in quality level,
  3948. // we need to signal this main audio track this could happen with playlists with
  3949. // alt audio rendition in which quality levels (main)
  3950. // contains both audio+video. but with mixed audio track not signaled
  3951. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3952. logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3953. audioTracks.unshift({
  3954. type: 'main',
  3955. name: 'main',
  3956. groupId: 'main',
  3957. default: false,
  3958. autoselect: false,
  3959. forced: false,
  3960. id: -1,
  3961. attrs: new AttrList({}),
  3962. bitrate: 0,
  3963. url: ''
  3964. });
  3965. }
  3966. }
  3967. hls.trigger(Events.MANIFEST_LOADED, {
  3968. levels,
  3969. audioTracks,
  3970. subtitles,
  3971. captions,
  3972. contentSteering,
  3973. url,
  3974. stats,
  3975. networkDetails,
  3976. sessionData,
  3977. sessionKeys,
  3978. startTimeOffset,
  3979. variableList
  3980. });
  3981. }
  3982. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  3983. const hls = this.hls;
  3984. const {
  3985. id,
  3986. level,
  3987. type
  3988. } = context;
  3989. const url = getResponseUrl(response, context);
  3990. const levelUrlId = 0;
  3991. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  3992. const levelType = mapContextToLevelType(context);
  3993. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList);
  3994. // We have done our first request (Manifest-type) and receive
  3995. // not a master playlist but a chunk-list (track/level)
  3996. // We fire the manifest-loaded event anyway with the parsed level-details
  3997. // by creating a single-level structure for it.
  3998. if (type === PlaylistContextType.MANIFEST) {
  3999. const singleLevel = {
  4000. attrs: new AttrList({}),
  4001. bitrate: 0,
  4002. details: levelDetails,
  4003. name: '',
  4004. url
  4005. };
  4006. hls.trigger(Events.MANIFEST_LOADED, {
  4007. levels: [singleLevel],
  4008. audioTracks: [],
  4009. url,
  4010. stats,
  4011. networkDetails,
  4012. sessionData: null,
  4013. sessionKeys: null,
  4014. contentSteering: null,
  4015. startTimeOffset: null,
  4016. variableList: null
  4017. });
  4018. }
  4019. // save parsing time
  4020. stats.parsing.end = performance.now();
  4021. // extend the context with the new levelDetails property
  4022. context.levelDetails = levelDetails;
  4023. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  4024. }
  4025. handleManifestParsingError(response, context, error, networkDetails, stats) {
  4026. this.hls.trigger(Events.ERROR, {
  4027. type: ErrorTypes.NETWORK_ERROR,
  4028. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  4029. fatal: context.type === PlaylistContextType.MANIFEST,
  4030. url: response.url,
  4031. err: error,
  4032. error,
  4033. reason: error.message,
  4034. response,
  4035. context,
  4036. networkDetails,
  4037. stats
  4038. });
  4039. }
  4040. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  4041. let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;
  4042. if (context.type === PlaylistContextType.LEVEL) {
  4043. message += `: ${context.level} id: ${context.id}`;
  4044. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  4045. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  4046. }
  4047. const error = new Error(message);
  4048. logger.warn(`[playlist-loader]: ${message}`);
  4049. let details = ErrorDetails.UNKNOWN;
  4050. let fatal = false;
  4051. const loader = this.getInternalLoader(context);
  4052. switch (context.type) {
  4053. case PlaylistContextType.MANIFEST:
  4054. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  4055. fatal = true;
  4056. break;
  4057. case PlaylistContextType.LEVEL:
  4058. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  4059. fatal = false;
  4060. break;
  4061. case PlaylistContextType.AUDIO_TRACK:
  4062. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  4063. fatal = false;
  4064. break;
  4065. case PlaylistContextType.SUBTITLE_TRACK:
  4066. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  4067. fatal = false;
  4068. break;
  4069. }
  4070. if (loader) {
  4071. this.resetInternalLoader(context.type);
  4072. }
  4073. const errorData = {
  4074. type: ErrorTypes.NETWORK_ERROR,
  4075. details,
  4076. fatal,
  4077. url: context.url,
  4078. loader,
  4079. context,
  4080. error,
  4081. networkDetails,
  4082. stats
  4083. };
  4084. if (response) {
  4085. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  4086. errorData.response = _objectSpread2({
  4087. url,
  4088. data: undefined
  4089. }, response);
  4090. }
  4091. this.hls.trigger(Events.ERROR, errorData);
  4092. }
  4093. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  4094. const hls = this.hls;
  4095. const {
  4096. type,
  4097. level,
  4098. id,
  4099. groupId,
  4100. deliveryDirectives
  4101. } = context;
  4102. const url = getResponseUrl(response, context);
  4103. const parent = mapContextToLevelType(context);
  4104. const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  4105. if (!levelDetails.fragments.length) {
  4106. const _error = new Error('No Segments found in Playlist');
  4107. hls.trigger(Events.ERROR, {
  4108. type: ErrorTypes.NETWORK_ERROR,
  4109. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  4110. fatal: false,
  4111. url,
  4112. error: _error,
  4113. reason: _error.message,
  4114. response,
  4115. context,
  4116. level: levelIndex,
  4117. parent,
  4118. networkDetails,
  4119. stats
  4120. });
  4121. return;
  4122. }
  4123. if (!levelDetails.targetduration) {
  4124. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  4125. }
  4126. const error = levelDetails.playlistParsingError;
  4127. if (error) {
  4128. hls.trigger(Events.ERROR, {
  4129. type: ErrorTypes.NETWORK_ERROR,
  4130. details: ErrorDetails.LEVEL_PARSING_ERROR,
  4131. fatal: false,
  4132. url,
  4133. error,
  4134. reason: error.message,
  4135. response,
  4136. context,
  4137. level: levelIndex,
  4138. parent,
  4139. networkDetails,
  4140. stats
  4141. });
  4142. return;
  4143. }
  4144. if (levelDetails.live && loader) {
  4145. if (loader.getCacheAge) {
  4146. levelDetails.ageHeader = loader.getCacheAge() || 0;
  4147. }
  4148. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  4149. levelDetails.ageHeader = 0;
  4150. }
  4151. }
  4152. switch (type) {
  4153. case PlaylistContextType.MANIFEST:
  4154. case PlaylistContextType.LEVEL:
  4155. hls.trigger(Events.LEVEL_LOADED, {
  4156. details: levelDetails,
  4157. level: levelIndex || 0,
  4158. id: id || 0,
  4159. stats,
  4160. networkDetails,
  4161. deliveryDirectives
  4162. });
  4163. break;
  4164. case PlaylistContextType.AUDIO_TRACK:
  4165. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  4166. details: levelDetails,
  4167. id: id || 0,
  4168. groupId: groupId || '',
  4169. stats,
  4170. networkDetails,
  4171. deliveryDirectives
  4172. });
  4173. break;
  4174. case PlaylistContextType.SUBTITLE_TRACK:
  4175. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  4176. details: levelDetails,
  4177. id: id || 0,
  4178. groupId: groupId || '',
  4179. stats,
  4180. networkDetails,
  4181. deliveryDirectives
  4182. });
  4183. break;
  4184. }
  4185. }
  4186. }
  4187. function sendAddTrackEvent(track, videoEl) {
  4188. let event;
  4189. try {
  4190. event = new Event('addtrack');
  4191. } catch (err) {
  4192. // for IE11
  4193. event = document.createEvent('Event');
  4194. event.initEvent('addtrack', false, false);
  4195. }
  4196. event.track = track;
  4197. videoEl.dispatchEvent(event);
  4198. }
  4199. function addCueToTrack(track, cue) {
  4200. // Sometimes there are cue overlaps on segmented vtts so the same
  4201. // cue can appear more than once in different vtt files.
  4202. // This avoid showing duplicated cues with same timecode and text.
  4203. const mode = track.mode;
  4204. if (mode === 'disabled') {
  4205. track.mode = 'hidden';
  4206. }
  4207. if (track.cues && !track.cues.getCueById(cue.id)) {
  4208. try {
  4209. track.addCue(cue);
  4210. if (!track.cues.getCueById(cue.id)) {
  4211. throw new Error(`addCue is failed for: ${cue}`);
  4212. }
  4213. } catch (err) {
  4214. logger.debug(`[texttrack-utils]: ${err}`);
  4215. try {
  4216. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  4217. textTrackCue.id = cue.id;
  4218. track.addCue(textTrackCue);
  4219. } catch (err2) {
  4220. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  4221. }
  4222. }
  4223. }
  4224. if (mode === 'disabled') {
  4225. track.mode = mode;
  4226. }
  4227. }
  4228. function clearCurrentCues(track) {
  4229. // When track.mode is disabled, track.cues will be null.
  4230. // To guarantee the removal of cues, we need to temporarily
  4231. // change the mode to hidden
  4232. const mode = track.mode;
  4233. if (mode === 'disabled') {
  4234. track.mode = 'hidden';
  4235. }
  4236. if (track.cues) {
  4237. for (let i = track.cues.length; i--;) {
  4238. track.removeCue(track.cues[i]);
  4239. }
  4240. }
  4241. if (mode === 'disabled') {
  4242. track.mode = mode;
  4243. }
  4244. }
  4245. function removeCuesInRange(track, start, end, predicate) {
  4246. const mode = track.mode;
  4247. if (mode === 'disabled') {
  4248. track.mode = 'hidden';
  4249. }
  4250. if (track.cues && track.cues.length > 0) {
  4251. const cues = getCuesInRange(track.cues, start, end);
  4252. for (let i = 0; i < cues.length; i++) {
  4253. if (!predicate || predicate(cues[i])) {
  4254. track.removeCue(cues[i]);
  4255. }
  4256. }
  4257. }
  4258. if (mode === 'disabled') {
  4259. track.mode = mode;
  4260. }
  4261. }
  4262. // Find first cue starting after given time.
  4263. // Modified version of binary search O(log(n)).
  4264. function getFirstCueIndexAfterTime(cues, time) {
  4265. // If first cue starts after time, start there
  4266. if (time < cues[0].startTime) {
  4267. return 0;
  4268. }
  4269. // If the last cue ends before time there is no overlap
  4270. const len = cues.length - 1;
  4271. if (time > cues[len].endTime) {
  4272. return -1;
  4273. }
  4274. let left = 0;
  4275. let right = len;
  4276. while (left <= right) {
  4277. const mid = Math.floor((right + left) / 2);
  4278. if (time < cues[mid].startTime) {
  4279. right = mid - 1;
  4280. } else if (time > cues[mid].startTime && left < len) {
  4281. left = mid + 1;
  4282. } else {
  4283. // If it's not lower or higher, it must be equal.
  4284. return mid;
  4285. }
  4286. }
  4287. // At this point, left and right have swapped.
  4288. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  4289. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  4290. }
  4291. function getCuesInRange(cues, start, end) {
  4292. const cuesFound = [];
  4293. const firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  4294. if (firstCueInRange > -1) {
  4295. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  4296. const cue = cues[i];
  4297. if (cue.startTime >= start && cue.endTime <= end) {
  4298. cuesFound.push(cue);
  4299. } else if (cue.startTime > end) {
  4300. return cuesFound;
  4301. }
  4302. }
  4303. }
  4304. return cuesFound;
  4305. }
  4306. function filterSubtitleTracks(textTrackList) {
  4307. const tracks = [];
  4308. for (let i = 0; i < textTrackList.length; i++) {
  4309. const track = textTrackList[i];
  4310. // Edge adds a track without a label; we don't want to use it
  4311. if ((track.kind === 'subtitles' || track.kind === 'captions') && track.label) {
  4312. tracks.push(textTrackList[i]);
  4313. }
  4314. }
  4315. return tracks;
  4316. }
  4317. var MetadataSchema = {
  4318. audioId3: "org.id3",
  4319. dateRange: "com.apple.quicktime.HLS",
  4320. emsg: "https://aomedia.org/emsg/ID3"
  4321. };
  4322. const MIN_CUE_DURATION = 0.25;
  4323. function getCueClass() {
  4324. if (typeof self === 'undefined') return undefined;
  4325. return self.VTTCue || self.TextTrackCue;
  4326. }
  4327. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  4328. let cue = new Cue(startTime, endTime, '');
  4329. try {
  4330. cue.value = data;
  4331. if (type) {
  4332. cue.type = type;
  4333. }
  4334. } catch (e) {
  4335. cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread2({
  4336. type
  4337. }, data) : data));
  4338. }
  4339. return cue;
  4340. }
  4341. // VTTCue latest draft allows an infinite duration, fallback
  4342. // to MAX_VALUE if necessary
  4343. const MAX_CUE_ENDTIME = (() => {
  4344. const Cue = getCueClass();
  4345. try {
  4346. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  4347. } catch (e) {
  4348. return Number.MAX_VALUE;
  4349. }
  4350. return Number.POSITIVE_INFINITY;
  4351. })();
  4352. function dateRangeDateToTimelineSeconds(date, offset) {
  4353. return date.getTime() / 1000 - offset;
  4354. }
  4355. function hexToArrayBuffer(str) {
  4356. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  4357. }
  4358. class ID3TrackController {
  4359. constructor(hls) {
  4360. this.hls = void 0;
  4361. this.id3Track = null;
  4362. this.media = null;
  4363. this.dateRangeCuesAppended = {};
  4364. this.hls = hls;
  4365. this._registerListeners();
  4366. }
  4367. destroy() {
  4368. this._unregisterListeners();
  4369. this.id3Track = null;
  4370. this.media = null;
  4371. this.dateRangeCuesAppended = {};
  4372. // @ts-ignore
  4373. this.hls = null;
  4374. }
  4375. _registerListeners() {
  4376. const {
  4377. hls
  4378. } = this;
  4379. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4380. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4381. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4382. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4383. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4384. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4385. }
  4386. _unregisterListeners() {
  4387. const {
  4388. hls
  4389. } = this;
  4390. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4391. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4392. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4393. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4394. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4395. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4396. }
  4397. // Add ID3 metatadata text track.
  4398. onMediaAttached(event, data) {
  4399. this.media = data.media;
  4400. }
  4401. onMediaDetaching() {
  4402. if (!this.id3Track) {
  4403. return;
  4404. }
  4405. clearCurrentCues(this.id3Track);
  4406. this.id3Track = null;
  4407. this.media = null;
  4408. this.dateRangeCuesAppended = {};
  4409. }
  4410. onManifestLoading() {
  4411. this.dateRangeCuesAppended = {};
  4412. }
  4413. createTrack(media) {
  4414. const track = this.getID3Track(media.textTracks);
  4415. track.mode = 'hidden';
  4416. return track;
  4417. }
  4418. getID3Track(textTracks) {
  4419. if (!this.media) {
  4420. return;
  4421. }
  4422. for (let i = 0; i < textTracks.length; i++) {
  4423. const textTrack = textTracks[i];
  4424. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  4425. // send 'addtrack' when reusing the textTrack for metadata,
  4426. // same as what we do for captions
  4427. sendAddTrackEvent(textTrack, this.media);
  4428. return textTrack;
  4429. }
  4430. }
  4431. return this.media.addTextTrack('metadata', 'id3');
  4432. }
  4433. onFragParsingMetadata(event, data) {
  4434. if (!this.media) {
  4435. return;
  4436. }
  4437. const {
  4438. hls: {
  4439. config: {
  4440. enableEmsgMetadataCues,
  4441. enableID3MetadataCues
  4442. }
  4443. }
  4444. } = this;
  4445. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  4446. return;
  4447. }
  4448. const {
  4449. samples
  4450. } = data;
  4451. // create track dynamically
  4452. if (!this.id3Track) {
  4453. this.id3Track = this.createTrack(this.media);
  4454. }
  4455. const Cue = getCueClass();
  4456. if (!Cue) {
  4457. return;
  4458. }
  4459. for (let i = 0; i < samples.length; i++) {
  4460. const type = samples[i].type;
  4461. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  4462. continue;
  4463. }
  4464. const frames = getID3Frames(samples[i].data);
  4465. if (frames) {
  4466. const startTime = samples[i].pts;
  4467. let endTime = startTime + samples[i].duration;
  4468. if (endTime > MAX_CUE_ENDTIME) {
  4469. endTime = MAX_CUE_ENDTIME;
  4470. }
  4471. const timeDiff = endTime - startTime;
  4472. if (timeDiff <= 0) {
  4473. endTime = startTime + MIN_CUE_DURATION;
  4474. }
  4475. for (let j = 0; j < frames.length; j++) {
  4476. const frame = frames[j];
  4477. // Safari doesn't put the timestamp frame in the TextTrack
  4478. if (!isTimeStampFrame(frame)) {
  4479. // add a bounds to any unbounded cues
  4480. this.updateId3CueEnds(startTime, type);
  4481. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  4482. if (cue) {
  4483. this.id3Track.addCue(cue);
  4484. }
  4485. }
  4486. }
  4487. }
  4488. }
  4489. }
  4490. updateId3CueEnds(startTime, type) {
  4491. var _this$id3Track;
  4492. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  4493. if (cues) {
  4494. for (let i = cues.length; i--;) {
  4495. const cue = cues[i];
  4496. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  4497. cue.endTime = startTime;
  4498. }
  4499. }
  4500. }
  4501. }
  4502. onBufferFlushing(event, {
  4503. startOffset,
  4504. endOffset,
  4505. type
  4506. }) {
  4507. const {
  4508. id3Track,
  4509. hls
  4510. } = this;
  4511. if (!hls) {
  4512. return;
  4513. }
  4514. const {
  4515. config: {
  4516. enableEmsgMetadataCues,
  4517. enableID3MetadataCues
  4518. }
  4519. } = hls;
  4520. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4521. let predicate;
  4522. if (type === 'audio') {
  4523. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  4524. } else if (type === 'video') {
  4525. predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4526. } else {
  4527. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4528. }
  4529. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  4530. }
  4531. }
  4532. onLevelUpdated(event, {
  4533. details
  4534. }) {
  4535. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4536. return;
  4537. }
  4538. const {
  4539. dateRangeCuesAppended,
  4540. id3Track
  4541. } = this;
  4542. const {
  4543. dateRanges
  4544. } = details;
  4545. const ids = Object.keys(dateRanges);
  4546. // Remove cues from track not found in details.dateRanges
  4547. if (id3Track) {
  4548. const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));
  4549. for (let i = idsToRemove.length; i--;) {
  4550. const id = idsToRemove[i];
  4551. Object.keys(dateRangeCuesAppended[id].cues).forEach(key => {
  4552. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4553. });
  4554. delete dateRangeCuesAppended[id];
  4555. }
  4556. }
  4557. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4558. const lastFragment = details.fragments[details.fragments.length - 1];
  4559. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  4560. return;
  4561. }
  4562. if (!this.id3Track) {
  4563. this.id3Track = this.createTrack(this.media);
  4564. }
  4565. const dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4566. const Cue = getCueClass();
  4567. for (let i = 0; i < ids.length; i++) {
  4568. const id = ids[i];
  4569. const dateRange = dateRanges[id];
  4570. const startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4571. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  4572. const appendedDateRangeCues = dateRangeCuesAppended[id];
  4573. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  4574. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4575. let endTime = MAX_CUE_ENDTIME;
  4576. const endDate = dateRange.endDate;
  4577. if (endDate) {
  4578. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4579. durationKnown = true;
  4580. } else if (dateRange.endOnNext && !durationKnown) {
  4581. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {
  4582. if (id !== dateRange.id) {
  4583. const otherDateRange = dateRanges[id];
  4584. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  4585. return otherDateRange;
  4586. }
  4587. }
  4588. return candidateDateRange;
  4589. }, null);
  4590. if (nextDateRangeWithSameClass) {
  4591. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4592. durationKnown = true;
  4593. }
  4594. }
  4595. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  4596. // This is to emulate Safari HLS playback handling of DateRange tags
  4597. const attributes = Object.keys(dateRange.attr);
  4598. for (let j = 0; j < attributes.length; j++) {
  4599. const key = attributes[j];
  4600. if (!isDateRangeCueAttribute(key)) {
  4601. continue;
  4602. }
  4603. const cue = cues[key];
  4604. if (cue) {
  4605. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4606. cue.endTime = endTime;
  4607. }
  4608. } else if (Cue) {
  4609. let data = dateRange.attr[key];
  4610. if (isSCTE35Attribute(key)) {
  4611. data = hexToArrayBuffer(data);
  4612. }
  4613. const _cue = createCueWithDataFields(Cue, startTime, endTime, {
  4614. key,
  4615. data
  4616. }, MetadataSchema.dateRange);
  4617. if (_cue) {
  4618. _cue.id = id;
  4619. this.id3Track.addCue(_cue);
  4620. cues[key] = _cue;
  4621. }
  4622. }
  4623. }
  4624. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  4625. dateRangeCuesAppended[id] = {
  4626. cues,
  4627. dateRange,
  4628. durationKnown
  4629. };
  4630. }
  4631. }
  4632. }
  4633. class LatencyController {
  4634. constructor(hls) {
  4635. this.hls = void 0;
  4636. this.config = void 0;
  4637. this.media = null;
  4638. this.levelDetails = null;
  4639. this.currentTime = 0;
  4640. this.stallCount = 0;
  4641. this._latency = null;
  4642. this.timeupdateHandler = () => this.timeupdate();
  4643. this.hls = hls;
  4644. this.config = hls.config;
  4645. this.registerListeners();
  4646. }
  4647. get latency() {
  4648. return this._latency || 0;
  4649. }
  4650. get maxLatency() {
  4651. const {
  4652. config,
  4653. levelDetails
  4654. } = this;
  4655. if (config.liveMaxLatencyDuration !== undefined) {
  4656. return config.liveMaxLatencyDuration;
  4657. }
  4658. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4659. }
  4660. get targetLatency() {
  4661. const {
  4662. levelDetails
  4663. } = this;
  4664. if (levelDetails === null) {
  4665. return null;
  4666. }
  4667. const {
  4668. holdBack,
  4669. partHoldBack,
  4670. targetduration
  4671. } = levelDetails;
  4672. const {
  4673. liveSyncDuration,
  4674. liveSyncDurationCount,
  4675. lowLatencyMode
  4676. } = this.config;
  4677. const userConfig = this.hls.userConfig;
  4678. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4679. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4680. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4681. }
  4682. const maxLiveSyncOnStallIncrease = targetduration;
  4683. const liveSyncOnStallIncrease = 1.0;
  4684. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4685. }
  4686. get liveSyncPosition() {
  4687. const liveEdge = this.estimateLiveEdge();
  4688. const targetLatency = this.targetLatency;
  4689. const levelDetails = this.levelDetails;
  4690. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4691. return null;
  4692. }
  4693. const edge = levelDetails.edge;
  4694. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4695. const min = edge - levelDetails.totalduration;
  4696. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4697. return Math.min(Math.max(min, syncPosition), max);
  4698. }
  4699. get drift() {
  4700. const {
  4701. levelDetails
  4702. } = this;
  4703. if (levelDetails === null) {
  4704. return 1;
  4705. }
  4706. return levelDetails.drift;
  4707. }
  4708. get edgeStalled() {
  4709. const {
  4710. levelDetails
  4711. } = this;
  4712. if (levelDetails === null) {
  4713. return 0;
  4714. }
  4715. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4716. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4717. }
  4718. get forwardBufferLength() {
  4719. const {
  4720. media,
  4721. levelDetails
  4722. } = this;
  4723. if (!media || !levelDetails) {
  4724. return 0;
  4725. }
  4726. const bufferedRanges = media.buffered.length;
  4727. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4728. }
  4729. destroy() {
  4730. this.unregisterListeners();
  4731. this.onMediaDetaching();
  4732. this.levelDetails = null;
  4733. // @ts-ignore
  4734. this.hls = this.timeupdateHandler = null;
  4735. }
  4736. registerListeners() {
  4737. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4738. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4739. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4740. this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4741. this.hls.on(Events.ERROR, this.onError, this);
  4742. }
  4743. unregisterListeners() {
  4744. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4745. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4746. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4747. this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4748. this.hls.off(Events.ERROR, this.onError, this);
  4749. }
  4750. onMediaAttached(event, data) {
  4751. this.media = data.media;
  4752. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4753. }
  4754. onMediaDetaching() {
  4755. if (this.media) {
  4756. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4757. this.media = null;
  4758. }
  4759. }
  4760. onManifestLoading() {
  4761. this.levelDetails = null;
  4762. this._latency = null;
  4763. this.stallCount = 0;
  4764. }
  4765. onLevelUpdated(event, {
  4766. details
  4767. }) {
  4768. this.levelDetails = details;
  4769. if (details.advanced) {
  4770. this.timeupdate();
  4771. }
  4772. if (!details.live && this.media) {
  4773. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4774. }
  4775. }
  4776. onError(event, data) {
  4777. var _this$levelDetails;
  4778. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  4779. return;
  4780. }
  4781. this.stallCount++;
  4782. if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  4783. logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4784. }
  4785. }
  4786. timeupdate() {
  4787. const {
  4788. media,
  4789. levelDetails
  4790. } = this;
  4791. if (!media || !levelDetails) {
  4792. return;
  4793. }
  4794. this.currentTime = media.currentTime;
  4795. const latency = this.computeLatency();
  4796. if (latency === null) {
  4797. return;
  4798. }
  4799. this._latency = latency;
  4800. // Adapt playbackRate to meet target latency in low-latency mode
  4801. const {
  4802. lowLatencyMode,
  4803. maxLiveSyncPlaybackRate
  4804. } = this.config;
  4805. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  4806. return;
  4807. }
  4808. const targetLatency = this.targetLatency;
  4809. if (targetLatency === null) {
  4810. return;
  4811. }
  4812. const distanceFromTarget = latency - targetLatency;
  4813. // Only adjust playbackRate when within one target duration of targetLatency
  4814. // and more than one second from under-buffering.
  4815. // Playback further than one target duration from target can be considered DVR playback.
  4816. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4817. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4818. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4819. const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4820. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4821. media.playbackRate = Math.min(max, Math.max(1, rate));
  4822. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4823. media.playbackRate = 1;
  4824. }
  4825. }
  4826. estimateLiveEdge() {
  4827. const {
  4828. levelDetails
  4829. } = this;
  4830. if (levelDetails === null) {
  4831. return null;
  4832. }
  4833. return levelDetails.edge + levelDetails.age;
  4834. }
  4835. computeLatency() {
  4836. const liveEdge = this.estimateLiveEdge();
  4837. if (liveEdge === null) {
  4838. return null;
  4839. }
  4840. return liveEdge - this.currentTime;
  4841. }
  4842. }
  4843. const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  4844. function isHdcpLevel(value) {
  4845. return HdcpLevels.indexOf(value) > -1;
  4846. }
  4847. const VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  4848. function isVideoRange(value) {
  4849. return !!value && VideoRangeValues.indexOf(value) > -1;
  4850. }
  4851. var HlsSkip = {
  4852. No: "",
  4853. Yes: "YES",
  4854. v2: "v2"
  4855. };
  4856. function getSkipValue(details) {
  4857. const {
  4858. canSkipUntil,
  4859. canSkipDateRanges,
  4860. age
  4861. } = details;
  4862. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  4863. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  4864. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  4865. const playlistRecentEnough = age < canSkipUntil / 2;
  4866. if (canSkipUntil && playlistRecentEnough) {
  4867. if (canSkipDateRanges) {
  4868. return HlsSkip.v2;
  4869. }
  4870. return HlsSkip.Yes;
  4871. }
  4872. return HlsSkip.No;
  4873. }
  4874. class HlsUrlParameters {
  4875. constructor(msn, part, skip) {
  4876. this.msn = void 0;
  4877. this.part = void 0;
  4878. this.skip = void 0;
  4879. this.msn = msn;
  4880. this.part = part;
  4881. this.skip = skip;
  4882. }
  4883. addDirectives(uri) {
  4884. const url = new self.URL(uri);
  4885. if (this.msn !== undefined) {
  4886. url.searchParams.set('_HLS_msn', this.msn.toString());
  4887. }
  4888. if (this.part !== undefined) {
  4889. url.searchParams.set('_HLS_part', this.part.toString());
  4890. }
  4891. if (this.skip) {
  4892. url.searchParams.set('_HLS_skip', this.skip);
  4893. }
  4894. return url.href;
  4895. }
  4896. }
  4897. class Level {
  4898. constructor(data) {
  4899. this._attrs = void 0;
  4900. this.audioCodec = void 0;
  4901. this.bitrate = void 0;
  4902. this.codecSet = void 0;
  4903. this.url = void 0;
  4904. this.frameRate = void 0;
  4905. this.height = void 0;
  4906. this.id = void 0;
  4907. this.name = void 0;
  4908. this.videoCodec = void 0;
  4909. this.width = void 0;
  4910. this.details = void 0;
  4911. this.fragmentError = 0;
  4912. this.loadError = 0;
  4913. this.loaded = void 0;
  4914. this.realBitrate = 0;
  4915. this.supportedPromise = void 0;
  4916. this.supportedResult = void 0;
  4917. this._avgBitrate = 0;
  4918. this._audioGroups = void 0;
  4919. this._subtitleGroups = void 0;
  4920. // Deprecated (retained for backwards compatibility)
  4921. this._urlId = 0;
  4922. this.url = [data.url];
  4923. this._attrs = [data.attrs];
  4924. this.bitrate = data.bitrate;
  4925. if (data.details) {
  4926. this.details = data.details;
  4927. }
  4928. this.id = data.id || 0;
  4929. this.name = data.name;
  4930. this.width = data.width || 0;
  4931. this.height = data.height || 0;
  4932. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  4933. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  4934. this.audioCodec = data.audioCodec;
  4935. this.videoCodec = data.videoCodec;
  4936. this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');
  4937. this.addGroupId('audio', data.attrs.AUDIO);
  4938. this.addGroupId('text', data.attrs.SUBTITLES);
  4939. }
  4940. get maxBitrate() {
  4941. return Math.max(this.realBitrate, this.bitrate);
  4942. }
  4943. get averageBitrate() {
  4944. return this._avgBitrate || this.realBitrate || this.bitrate;
  4945. }
  4946. get attrs() {
  4947. return this._attrs[0];
  4948. }
  4949. get codecs() {
  4950. return this.attrs.CODECS || '';
  4951. }
  4952. get pathwayId() {
  4953. return this.attrs['PATHWAY-ID'] || '.';
  4954. }
  4955. get videoRange() {
  4956. return this.attrs['VIDEO-RANGE'] || 'SDR';
  4957. }
  4958. get score() {
  4959. return this.attrs.optionalFloat('SCORE', 0);
  4960. }
  4961. get uri() {
  4962. return this.url[0] || '';
  4963. }
  4964. hasAudioGroup(groupId) {
  4965. return hasGroup(this._audioGroups, groupId);
  4966. }
  4967. hasSubtitleGroup(groupId) {
  4968. return hasGroup(this._subtitleGroups, groupId);
  4969. }
  4970. get audioGroups() {
  4971. return this._audioGroups;
  4972. }
  4973. get subtitleGroups() {
  4974. return this._subtitleGroups;
  4975. }
  4976. addGroupId(type, groupId) {
  4977. if (!groupId) {
  4978. return;
  4979. }
  4980. if (type === 'audio') {
  4981. let audioGroups = this._audioGroups;
  4982. if (!audioGroups) {
  4983. audioGroups = this._audioGroups = [];
  4984. }
  4985. if (audioGroups.indexOf(groupId) === -1) {
  4986. audioGroups.push(groupId);
  4987. }
  4988. } else if (type === 'text') {
  4989. let subtitleGroups = this._subtitleGroups;
  4990. if (!subtitleGroups) {
  4991. subtitleGroups = this._subtitleGroups = [];
  4992. }
  4993. if (subtitleGroups.indexOf(groupId) === -1) {
  4994. subtitleGroups.push(groupId);
  4995. }
  4996. }
  4997. }
  4998. // Deprecated methods (retained for backwards compatibility)
  4999. get urlId() {
  5000. return 0;
  5001. }
  5002. set urlId(value) {}
  5003. get audioGroupIds() {
  5004. return this.audioGroups ? [this.audioGroupId] : undefined;
  5005. }
  5006. get textGroupIds() {
  5007. return this.subtitleGroups ? [this.textGroupId] : undefined;
  5008. }
  5009. get audioGroupId() {
  5010. var _this$audioGroups;
  5011. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  5012. }
  5013. get textGroupId() {
  5014. var _this$subtitleGroups;
  5015. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  5016. }
  5017. addFallback() {}
  5018. }
  5019. function hasGroup(groups, groupId) {
  5020. if (!groupId || !groups) {
  5021. return false;
  5022. }
  5023. return groups.indexOf(groupId) !== -1;
  5024. }
  5025. function updateFromToPTS(fragFrom, fragTo) {
  5026. const fragToPTS = fragTo.startPTS;
  5027. // if we know startPTS[toIdx]
  5028. if (isFiniteNumber(fragToPTS)) {
  5029. // update fragment duration.
  5030. // it helps to fix drifts between playlist reported duration and fragment real duration
  5031. let duration = 0;
  5032. let frag;
  5033. if (fragTo.sn > fragFrom.sn) {
  5034. duration = fragToPTS - fragFrom.start;
  5035. frag = fragFrom;
  5036. } else {
  5037. duration = fragFrom.start - fragToPTS;
  5038. frag = fragTo;
  5039. }
  5040. if (frag.duration !== duration) {
  5041. frag.duration = duration;
  5042. }
  5043. // we dont know startPTS[toIdx]
  5044. } else if (fragTo.sn > fragFrom.sn) {
  5045. const contiguous = fragFrom.cc === fragTo.cc;
  5046. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  5047. if (contiguous && fragFrom.minEndPTS) {
  5048. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  5049. } else {
  5050. fragTo.start = fragFrom.start + fragFrom.duration;
  5051. }
  5052. } else {
  5053. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  5054. }
  5055. }
  5056. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  5057. const parsedMediaDuration = endPTS - startPTS;
  5058. if (parsedMediaDuration <= 0) {
  5059. logger.warn('Fragment should have a positive duration', frag);
  5060. endPTS = startPTS + frag.duration;
  5061. endDTS = startDTS + frag.duration;
  5062. }
  5063. let maxStartPTS = startPTS;
  5064. let minEndPTS = endPTS;
  5065. const fragStartPts = frag.startPTS;
  5066. const fragEndPts = frag.endPTS;
  5067. if (isFiniteNumber(fragStartPts)) {
  5068. // delta PTS between audio and video
  5069. const deltaPTS = Math.abs(fragStartPts - startPTS);
  5070. if (!isFiniteNumber(frag.deltaPTS)) {
  5071. frag.deltaPTS = deltaPTS;
  5072. } else {
  5073. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  5074. }
  5075. maxStartPTS = Math.max(startPTS, fragStartPts);
  5076. startPTS = Math.min(startPTS, fragStartPts);
  5077. startDTS = Math.min(startDTS, frag.startDTS);
  5078. minEndPTS = Math.min(endPTS, fragEndPts);
  5079. endPTS = Math.max(endPTS, fragEndPts);
  5080. endDTS = Math.max(endDTS, frag.endDTS);
  5081. }
  5082. const drift = startPTS - frag.start;
  5083. if (frag.start !== 0) {
  5084. frag.start = startPTS;
  5085. }
  5086. frag.duration = endPTS - frag.start;
  5087. frag.startPTS = startPTS;
  5088. frag.maxStartPTS = maxStartPTS;
  5089. frag.startDTS = startDTS;
  5090. frag.endPTS = endPTS;
  5091. frag.minEndPTS = minEndPTS;
  5092. frag.endDTS = endDTS;
  5093. const sn = frag.sn; // 'initSegment'
  5094. // exit if sn out of range
  5095. if (!details || sn < details.startSN || sn > details.endSN) {
  5096. return 0;
  5097. }
  5098. let i;
  5099. const fragIdx = sn - details.startSN;
  5100. const fragments = details.fragments;
  5101. // update frag reference in fragments array
  5102. // rationale is that fragments array might not contain this frag object.
  5103. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  5104. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  5105. // resulting in invalid sliding computation
  5106. fragments[fragIdx] = frag;
  5107. // adjust fragment PTS/duration from seqnum-1 to frag 0
  5108. for (i = fragIdx; i > 0; i--) {
  5109. updateFromToPTS(fragments[i], fragments[i - 1]);
  5110. }
  5111. // adjust fragment PTS/duration from seqnum to last frag
  5112. for (i = fragIdx; i < fragments.length - 1; i++) {
  5113. updateFromToPTS(fragments[i], fragments[i + 1]);
  5114. }
  5115. if (details.fragmentHint) {
  5116. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  5117. }
  5118. details.PTSKnown = details.alignedSliding = true;
  5119. return drift;
  5120. }
  5121. function mergeDetails(oldDetails, newDetails) {
  5122. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  5123. let currentInitSegment = null;
  5124. const oldFragments = oldDetails.fragments;
  5125. for (let i = oldFragments.length - 1; i >= 0; i--) {
  5126. const oldInit = oldFragments[i].initSegment;
  5127. if (oldInit) {
  5128. currentInitSegment = oldInit;
  5129. break;
  5130. }
  5131. }
  5132. if (oldDetails.fragmentHint) {
  5133. // prevent PTS and duration from being adjusted on the next hint
  5134. delete oldDetails.fragmentHint.endPTS;
  5135. }
  5136. // check if old/new playlists have fragments in common
  5137. // loop through overlapping SN and update startPTS , cc, and duration if any found
  5138. let ccOffset = 0;
  5139. let PTSFrag;
  5140. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {
  5141. if (oldFrag.relurl) {
  5142. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  5143. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  5144. // of the playlist.
  5145. ccOffset = oldFrag.cc - newFrag.cc;
  5146. }
  5147. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  5148. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  5149. newFrag.startDTS = oldFrag.startDTS;
  5150. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  5151. newFrag.endPTS = oldFrag.endPTS;
  5152. newFrag.endDTS = oldFrag.endDTS;
  5153. newFrag.minEndPTS = oldFrag.minEndPTS;
  5154. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  5155. if (newFrag.duration) {
  5156. PTSFrag = newFrag;
  5157. }
  5158. // PTS is known when any segment has startPTS and endPTS
  5159. newDetails.PTSKnown = newDetails.alignedSliding = true;
  5160. }
  5161. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  5162. newFrag.loader = oldFrag.loader;
  5163. newFrag.stats = oldFrag.stats;
  5164. if (oldFrag.initSegment) {
  5165. newFrag.initSegment = oldFrag.initSegment;
  5166. currentInitSegment = oldFrag.initSegment;
  5167. }
  5168. });
  5169. if (currentInitSegment) {
  5170. const fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5171. fragmentsToCheck.forEach(frag => {
  5172. var _currentInitSegment;
  5173. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  5174. frag.initSegment = currentInitSegment;
  5175. }
  5176. });
  5177. }
  5178. if (newDetails.skippedSegments) {
  5179. newDetails.deltaUpdateFailed = newDetails.fragments.some(frag => !frag);
  5180. if (newDetails.deltaUpdateFailed) {
  5181. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  5182. for (let i = newDetails.skippedSegments; i--;) {
  5183. newDetails.fragments.shift();
  5184. }
  5185. newDetails.startSN = newDetails.fragments[0].sn;
  5186. newDetails.startCC = newDetails.fragments[0].cc;
  5187. } else if (newDetails.canSkipDateRanges) {
  5188. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  5189. }
  5190. }
  5191. const newFragments = newDetails.fragments;
  5192. if (ccOffset) {
  5193. logger.warn('discontinuity sliding from playlist, take drift into account');
  5194. for (let i = 0; i < newFragments.length; i++) {
  5195. newFragments[i].cc += ccOffset;
  5196. }
  5197. }
  5198. if (newDetails.skippedSegments) {
  5199. newDetails.startCC = newDetails.fragments[0].cc;
  5200. }
  5201. // Merge parts
  5202. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  5203. newPart.elementaryStreams = oldPart.elementaryStreams;
  5204. newPart.stats = oldPart.stats;
  5205. });
  5206. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  5207. if (PTSFrag) {
  5208. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  5209. } else {
  5210. // ensure that delta is within oldFragments range
  5211. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  5212. // in that case we also need to adjust start offset of all fragments
  5213. adjustSliding(oldDetails, newDetails);
  5214. }
  5215. if (newFragments.length) {
  5216. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  5217. }
  5218. newDetails.driftStartTime = oldDetails.driftStartTime;
  5219. newDetails.driftStart = oldDetails.driftStart;
  5220. const advancedDateTime = newDetails.advancedDateTime;
  5221. if (newDetails.advanced && advancedDateTime) {
  5222. const edge = newDetails.edge;
  5223. if (!newDetails.driftStart) {
  5224. newDetails.driftStartTime = advancedDateTime;
  5225. newDetails.driftStart = edge;
  5226. }
  5227. newDetails.driftEndTime = advancedDateTime;
  5228. newDetails.driftEnd = edge;
  5229. } else {
  5230. newDetails.driftEndTime = oldDetails.driftEndTime;
  5231. newDetails.driftEnd = oldDetails.driftEnd;
  5232. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  5233. }
  5234. }
  5235. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  5236. const dateRanges = _extends({}, oldDateRanges);
  5237. if (recentlyRemovedDateranges) {
  5238. recentlyRemovedDateranges.forEach(id => {
  5239. delete dateRanges[id];
  5240. });
  5241. }
  5242. Object.keys(deltaDateRanges).forEach(id => {
  5243. const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  5244. if (dateRange.isValid) {
  5245. dateRanges[id] = dateRange;
  5246. } else {
  5247. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(deltaDateRanges[id].attr)}"`);
  5248. }
  5249. });
  5250. return dateRanges;
  5251. }
  5252. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  5253. if (oldParts && newParts) {
  5254. let delta = 0;
  5255. for (let i = 0, len = oldParts.length; i <= len; i++) {
  5256. const oldPart = oldParts[i];
  5257. const newPart = newParts[i + delta];
  5258. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  5259. intersectionFn(oldPart, newPart);
  5260. } else {
  5261. delta--;
  5262. }
  5263. }
  5264. }
  5265. }
  5266. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5267. const skippedSegments = newDetails.skippedSegments;
  5268. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5269. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5270. const delta = newDetails.startSN - oldDetails.startSN;
  5271. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5272. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5273. for (let i = start; i <= end; i++) {
  5274. const oldFrag = oldFrags[delta + i];
  5275. let newFrag = newFrags[i];
  5276. if (skippedSegments && !newFrag && i < skippedSegments) {
  5277. // Fill in skipped segments in delta playlist
  5278. newFrag = newDetails.fragments[i] = oldFrag;
  5279. }
  5280. if (oldFrag && newFrag) {
  5281. intersectionFn(oldFrag, newFrag);
  5282. }
  5283. }
  5284. }
  5285. function adjustSliding(oldDetails, newDetails) {
  5286. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5287. const oldFragments = oldDetails.fragments;
  5288. if (delta < 0 || delta >= oldFragments.length) {
  5289. return;
  5290. }
  5291. addSliding(newDetails, oldFragments[delta].start);
  5292. }
  5293. function addSliding(details, start) {
  5294. if (start) {
  5295. const fragments = details.fragments;
  5296. for (let i = details.skippedSegments; i < fragments.length; i++) {
  5297. fragments[i].start += start;
  5298. }
  5299. if (details.fragmentHint) {
  5300. details.fragmentHint.start += start;
  5301. }
  5302. }
  5303. }
  5304. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  5305. let reloadInterval = 1000 * newDetails.targetduration;
  5306. if (newDetails.updated) {
  5307. // Use last segment duration when shorter than target duration and near live edge
  5308. const fragments = newDetails.fragments;
  5309. const liveEdgeMaxTargetDurations = 4;
  5310. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5311. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5312. if (lastSegmentDuration < reloadInterval) {
  5313. reloadInterval = lastSegmentDuration;
  5314. }
  5315. }
  5316. } else {
  5317. // estimate = 'miss half average';
  5318. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5319. // changed then it MUST wait for a period of one-half the target
  5320. // duration before retrying.
  5321. reloadInterval /= 2;
  5322. }
  5323. return Math.round(reloadInterval);
  5324. }
  5325. function getFragmentWithSN(level, sn, fragCurrent) {
  5326. if (!(level != null && level.details)) {
  5327. return null;
  5328. }
  5329. const levelDetails = level.details;
  5330. let fragment = levelDetails.fragments[sn - levelDetails.startSN];
  5331. if (fragment) {
  5332. return fragment;
  5333. }
  5334. fragment = levelDetails.fragmentHint;
  5335. if (fragment && fragment.sn === sn) {
  5336. return fragment;
  5337. }
  5338. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  5339. return fragCurrent;
  5340. }
  5341. return null;
  5342. }
  5343. function getPartWith(level, sn, partIndex) {
  5344. var _level$details;
  5345. if (!(level != null && level.details)) {
  5346. return null;
  5347. }
  5348. return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex);
  5349. }
  5350. function findPart(partList, sn, partIndex) {
  5351. if (partList) {
  5352. for (let i = partList.length; i--;) {
  5353. const part = partList[i];
  5354. if (part.index === partIndex && part.fragment.sn === sn) {
  5355. return part;
  5356. }
  5357. }
  5358. }
  5359. return null;
  5360. }
  5361. function reassignFragmentLevelIndexes(levels) {
  5362. levels.forEach((level, index) => {
  5363. const {
  5364. details
  5365. } = level;
  5366. if (details != null && details.fragments) {
  5367. details.fragments.forEach(fragment => {
  5368. fragment.level = index;
  5369. });
  5370. }
  5371. });
  5372. }
  5373. function isTimeoutError(error) {
  5374. switch (error.details) {
  5375. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5376. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5377. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5378. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  5379. return true;
  5380. }
  5381. return false;
  5382. }
  5383. function getRetryConfig(loadPolicy, error) {
  5384. const isTimeout = isTimeoutError(error);
  5385. return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];
  5386. }
  5387. function getRetryDelay(retryConfig, retryCount) {
  5388. // exponential backoff capped to max retry delay
  5389. const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  5390. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  5391. }
  5392. function getLoaderConfigWithoutReties(loderConfig) {
  5393. return _objectSpread2(_objectSpread2({}, loderConfig), {
  5394. errorRetry: null,
  5395. timeoutRetry: null
  5396. });
  5397. }
  5398. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  5399. if (!retryConfig) {
  5400. return false;
  5401. }
  5402. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  5403. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  5404. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  5405. }
  5406. function retryForHttpStatus(httpStatus) {
  5407. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  5408. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  5409. }
  5410. const BinarySearch = {
  5411. /**
  5412. * Searches for an item in an array which matches a certain condition.
  5413. * This requires the condition to only match one item in the array,
  5414. * and for the array to be ordered.
  5415. *
  5416. * @param list The array to search.
  5417. * @param comparisonFn
  5418. * Called and provided a candidate item as the first argument.
  5419. * Should return:
  5420. * > -1 if the item should be located at a lower index than the provided item.
  5421. * > 1 if the item should be located at a higher index than the provided item.
  5422. * > 0 if the item is the item you're looking for.
  5423. *
  5424. * @returns the object if found, otherwise returns null
  5425. */
  5426. search: function (list, comparisonFn) {
  5427. let minIndex = 0;
  5428. let maxIndex = list.length - 1;
  5429. let currentIndex = null;
  5430. let currentElement = null;
  5431. while (minIndex <= maxIndex) {
  5432. currentIndex = (minIndex + maxIndex) / 2 | 0;
  5433. currentElement = list[currentIndex];
  5434. const comparisonResult = comparisonFn(currentElement);
  5435. if (comparisonResult > 0) {
  5436. minIndex = currentIndex + 1;
  5437. } else if (comparisonResult < 0) {
  5438. maxIndex = currentIndex - 1;
  5439. } else {
  5440. return currentElement;
  5441. }
  5442. }
  5443. return null;
  5444. }
  5445. };
  5446. /**
  5447. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  5448. * @param fragments - The array of candidate fragments
  5449. * @param PDTValue - The PDT value which must be exceeded
  5450. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5451. */
  5452. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5453. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  5454. return null;
  5455. }
  5456. // if less than start
  5457. const startPDT = fragments[0].programDateTime;
  5458. if (PDTValue < (startPDT || 0)) {
  5459. return null;
  5460. }
  5461. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  5462. if (PDTValue >= (endPDT || 0)) {
  5463. return null;
  5464. }
  5465. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5466. for (let seg = 0; seg < fragments.length; ++seg) {
  5467. const frag = fragments[seg];
  5468. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5469. return frag;
  5470. }
  5471. }
  5472. return null;
  5473. }
  5474. /**
  5475. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5476. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5477. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5478. * @param fragPrevious - The last frag successfully appended
  5479. * @param fragments - The array of candidate fragments
  5480. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  5481. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5482. * @returns a matching fragment or null
  5483. */
  5484. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {
  5485. let fragNext = null;
  5486. if (fragPrevious) {
  5487. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  5488. // check for buffer-end rounding error
  5489. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  5490. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  5491. bufferEnd += 0.0000015;
  5492. }
  5493. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  5494. fragNext = fragments[0];
  5495. }
  5496. // Prefer the next fragment if it's within tolerance
  5497. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  5498. return fragNext;
  5499. }
  5500. // We might be seeking past the tolerance so find the best match
  5501. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5502. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  5503. return foundFragment;
  5504. }
  5505. // If no match was found return the next fragment after fragPrevious, or null
  5506. return fragNext;
  5507. }
  5508. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  5509. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  5510. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  5511. if (tag[0] === 'INF') {
  5512. duration += parseFloat(tag[1]);
  5513. }
  5514. return duration;
  5515. }, nextFragLookupTolerance);
  5516. return fragNext.start <= firstDuration;
  5517. }
  5518. return false;
  5519. }
  5520. /**
  5521. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5522. * @param candidate - The fragment to test
  5523. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  5524. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5525. * @returns 0 if it matches, 1 if too low, -1 if too high
  5526. */
  5527. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  5528. // eagerly accept an accurate match (no tolerance)
  5529. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  5530. return 0;
  5531. }
  5532. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5533. // this is to cope with situations like
  5534. // bufferEnd = 9.991
  5535. // frag[Ø] : [0,10]
  5536. // frag[1] : [10,20]
  5537. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5538. // frag start frag start+duration
  5539. // |-----------------------------|
  5540. // <---> <--->
  5541. // ...--------><-----------------------------><---------....
  5542. // previous frag matching fragment next frag
  5543. // return -1 return 0 return 1
  5544. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5545. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5546. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5547. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5548. return 1;
  5549. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5550. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5551. return -1;
  5552. }
  5553. return 0;
  5554. }
  5555. /**
  5556. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5557. * This function tests the candidate's program date time values, as represented in Unix time
  5558. * @param candidate - The fragment to test
  5559. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  5560. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5561. * @returns true if contiguous, false otherwise
  5562. */
  5563. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5564. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5565. // endProgramDateTime can be null, default to zero
  5566. const endProgramDateTime = candidate.endProgramDateTime || 0;
  5567. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5568. }
  5569. function findFragWithCC(fragments, cc) {
  5570. return BinarySearch.search(fragments, candidate => {
  5571. if (candidate.cc < cc) {
  5572. return 1;
  5573. } else if (candidate.cc > cc) {
  5574. return -1;
  5575. } else {
  5576. return 0;
  5577. }
  5578. });
  5579. }
  5580. var NetworkErrorAction = {
  5581. DoNothing: 0,
  5582. SendEndCallback: 1,
  5583. SendAlternateToPenaltyBox: 2,
  5584. RemoveAlternatePermanently: 3,
  5585. InsertDiscontinuity: 4,
  5586. RetryRequest: 5
  5587. };
  5588. var ErrorActionFlags = {
  5589. None: 0,
  5590. MoveAllAlternatesMatchingHost: 1,
  5591. MoveAllAlternatesMatchingHDCP: 2,
  5592. SwitchToSDR: 4
  5593. }; // Reserved for future use
  5594. class ErrorController {
  5595. constructor(hls) {
  5596. this.hls = void 0;
  5597. this.playlistError = 0;
  5598. this.penalizedRenditions = {};
  5599. this.log = void 0;
  5600. this.warn = void 0;
  5601. this.error = void 0;
  5602. this.hls = hls;
  5603. this.log = logger.log.bind(logger, `[info]:`);
  5604. this.warn = logger.warn.bind(logger, `[warning]:`);
  5605. this.error = logger.error.bind(logger, `[error]:`);
  5606. this.registerListeners();
  5607. }
  5608. registerListeners() {
  5609. const hls = this.hls;
  5610. hls.on(Events.ERROR, this.onError, this);
  5611. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5612. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5613. }
  5614. unregisterListeners() {
  5615. const hls = this.hls;
  5616. if (!hls) {
  5617. return;
  5618. }
  5619. hls.off(Events.ERROR, this.onError, this);
  5620. hls.off(Events.ERROR, this.onErrorOut, this);
  5621. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5622. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5623. }
  5624. destroy() {
  5625. this.unregisterListeners();
  5626. // @ts-ignore
  5627. this.hls = null;
  5628. this.penalizedRenditions = {};
  5629. }
  5630. startLoad(startPosition) {}
  5631. stopLoad() {
  5632. this.playlistError = 0;
  5633. }
  5634. getVariantLevelIndex(frag) {
  5635. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  5636. }
  5637. onManifestLoading() {
  5638. this.playlistError = 0;
  5639. this.penalizedRenditions = {};
  5640. }
  5641. onLevelUpdated() {
  5642. this.playlistError = 0;
  5643. }
  5644. onError(event, data) {
  5645. var _data$frag, _data$level;
  5646. if (data.fatal) {
  5647. return;
  5648. }
  5649. const hls = this.hls;
  5650. const context = data.context;
  5651. switch (data.details) {
  5652. case ErrorDetails.FRAG_LOAD_ERROR:
  5653. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5654. case ErrorDetails.KEY_LOAD_ERROR:
  5655. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5656. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5657. return;
  5658. case ErrorDetails.FRAG_PARSING_ERROR:
  5659. // ignore empty segment errors marked as gap
  5660. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  5661. data.errorAction = {
  5662. action: NetworkErrorAction.DoNothing,
  5663. flags: ErrorActionFlags.None
  5664. };
  5665. return;
  5666. }
  5667. // falls through
  5668. case ErrorDetails.FRAG_GAP:
  5669. case ErrorDetails.FRAG_DECRYPT_ERROR:
  5670. {
  5671. // Switch level if possible, otherwise allow retry count to reach max error retries
  5672. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5673. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5674. return;
  5675. }
  5676. case ErrorDetails.LEVEL_EMPTY_ERROR:
  5677. case ErrorDetails.LEVEL_PARSING_ERROR:
  5678. {
  5679. var _data$context, _data$context$levelDe;
  5680. // Only retry when empty and live
  5681. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  5682. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  5683. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  5684. } else {
  5685. // Escalate to fatal if not retrying or switching
  5686. data.levelRetry = false;
  5687. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5688. }
  5689. }
  5690. return;
  5691. case ErrorDetails.LEVEL_LOAD_ERROR:
  5692. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5693. if (typeof (context == null ? void 0 : context.level) === 'number') {
  5694. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  5695. }
  5696. return;
  5697. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  5698. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  5699. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  5700. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  5701. if (context) {
  5702. const level = hls.levels[hls.loadLevel];
  5703. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  5704. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  5705. // otherwise allow playlist retry count to reach max error retries
  5706. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  5707. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5708. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  5709. return;
  5710. }
  5711. }
  5712. return;
  5713. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  5714. {
  5715. const level = hls.levels[hls.loadLevel];
  5716. const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];
  5717. if (restrictedHdcpLevel) {
  5718. data.errorAction = {
  5719. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5720. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  5721. hdcpLevel: restrictedHdcpLevel
  5722. };
  5723. } else {
  5724. this.keySystemError(data);
  5725. }
  5726. }
  5727. return;
  5728. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  5729. case ErrorDetails.REMUX_ALLOC_ERROR:
  5730. case ErrorDetails.BUFFER_APPEND_ERROR:
  5731. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  5732. return;
  5733. case ErrorDetails.INTERNAL_EXCEPTION:
  5734. case ErrorDetails.BUFFER_APPENDING_ERROR:
  5735. case ErrorDetails.BUFFER_FULL_ERROR:
  5736. case ErrorDetails.LEVEL_SWITCH_ERROR:
  5737. case ErrorDetails.BUFFER_STALLED_ERROR:
  5738. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  5739. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  5740. data.errorAction = {
  5741. action: NetworkErrorAction.DoNothing,
  5742. flags: ErrorActionFlags.None
  5743. };
  5744. return;
  5745. }
  5746. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  5747. this.keySystemError(data);
  5748. }
  5749. }
  5750. keySystemError(data) {
  5751. const levelIndex = this.getVariantLevelIndex(data.frag);
  5752. // Do not retry level. Escalate to fatal if switching levels fails.
  5753. data.levelRetry = false;
  5754. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5755. }
  5756. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  5757. const hls = this.hls;
  5758. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  5759. const retryCount = this.playlistError++;
  5760. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  5761. if (retry) {
  5762. return {
  5763. action: NetworkErrorAction.RetryRequest,
  5764. flags: ErrorActionFlags.None,
  5765. retryConfig,
  5766. retryCount
  5767. };
  5768. }
  5769. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  5770. if (retryConfig) {
  5771. errorAction.retryConfig = retryConfig;
  5772. errorAction.retryCount = retryCount;
  5773. }
  5774. return errorAction;
  5775. }
  5776. getFragRetryOrSwitchAction(data) {
  5777. const hls = this.hls;
  5778. // Share fragment error count accross media options (main, audio, subs)
  5779. // This allows for level based rendition switching when media option assets fail
  5780. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  5781. const level = hls.levels[variantLevelIndex];
  5782. const {
  5783. fragLoadPolicy,
  5784. keyLoadPolicy
  5785. } = hls.config;
  5786. const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  5787. const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);
  5788. // Switch levels when out of retried or level index out of bounds
  5789. if (level) {
  5790. if (data.details !== ErrorDetails.FRAG_GAP) {
  5791. level.fragmentError++;
  5792. }
  5793. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  5794. if (retry) {
  5795. return {
  5796. action: NetworkErrorAction.RetryRequest,
  5797. flags: ErrorActionFlags.None,
  5798. retryConfig,
  5799. retryCount: fragmentErrors
  5800. };
  5801. }
  5802. }
  5803. // Reach max retry count, or Missing level reference
  5804. // Switch to valid index
  5805. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  5806. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  5807. if (retryConfig) {
  5808. errorAction.retryConfig = retryConfig;
  5809. errorAction.retryCount = fragmentErrors;
  5810. }
  5811. return errorAction;
  5812. }
  5813. getLevelSwitchAction(data, levelIndex) {
  5814. const hls = this.hls;
  5815. if (levelIndex === null || levelIndex === undefined) {
  5816. levelIndex = hls.loadLevel;
  5817. }
  5818. const level = this.hls.levels[levelIndex];
  5819. if (level) {
  5820. var _data$frag2, _data$context2;
  5821. const errorDetails = data.details;
  5822. level.loadError++;
  5823. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  5824. level.fragmentError++;
  5825. }
  5826. // Search for next level to retry
  5827. let nextLevel = -1;
  5828. const {
  5829. levels,
  5830. loadLevel,
  5831. minAutoLevel,
  5832. maxAutoLevel
  5833. } = hls;
  5834. if (!hls.autoLevelEnabled) {
  5835. hls.loadLevel = -1;
  5836. }
  5837. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  5838. // Find alternate audio codec if available on audio codec error
  5839. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5840. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  5841. audioCodec
  5842. }) => level.audioCodec !== audioCodec);
  5843. // Find alternate video codec if available on video codec error
  5844. const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5845. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  5846. codecSet,
  5847. audioCodec
  5848. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  5849. const {
  5850. type: playlistErrorType,
  5851. groupId: playlistErrorGroupId
  5852. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  5853. for (let i = levels.length; i--;) {
  5854. const candidate = (i + loadLevel) % levels.length;
  5855. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  5856. var _level$audioGroups, _level$subtitleGroups;
  5857. const levelCandidate = levels[candidate];
  5858. // Skip level switch if GAP tag is found in next level at same position
  5859. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  5860. const levelDetails = levels[candidate].details;
  5861. if (levelDetails) {
  5862. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  5863. if (fragCandidate != null && fragCandidate.gap) {
  5864. continue;
  5865. }
  5866. }
  5867. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  5868. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  5869. continue;
  5870. } 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) {
  5871. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  5872. continue;
  5873. }
  5874. nextLevel = candidate;
  5875. break;
  5876. }
  5877. }
  5878. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5879. data.levelRetry = true;
  5880. this.playlistError = 0;
  5881. return {
  5882. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5883. flags: ErrorActionFlags.None,
  5884. nextAutoLevel: nextLevel
  5885. };
  5886. }
  5887. }
  5888. // No levels to switch / Manual level selection / Level not found
  5889. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5890. return {
  5891. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5892. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5893. };
  5894. }
  5895. onErrorOut(event, data) {
  5896. var _data$errorAction;
  5897. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5898. case NetworkErrorAction.DoNothing:
  5899. break;
  5900. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5901. this.sendAlternateToPenaltyBox(data);
  5902. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5903. data.fatal = true;
  5904. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5905. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  5906. this.hls.recoverMediaError();
  5907. }
  5908. break;
  5909. case NetworkErrorAction.RetryRequest:
  5910. // handled by stream and playlist/level controllers
  5911. break;
  5912. }
  5913. if (data.fatal) {
  5914. this.hls.stopLoad();
  5915. return;
  5916. }
  5917. }
  5918. sendAlternateToPenaltyBox(data) {
  5919. const hls = this.hls;
  5920. const errorAction = data.errorAction;
  5921. if (!errorAction) {
  5922. return;
  5923. }
  5924. const {
  5925. flags,
  5926. hdcpLevel,
  5927. nextAutoLevel
  5928. } = errorAction;
  5929. switch (flags) {
  5930. case ErrorActionFlags.None:
  5931. this.switchLevel(data, nextAutoLevel);
  5932. break;
  5933. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5934. if (hdcpLevel) {
  5935. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5936. errorAction.resolved = true;
  5937. }
  5938. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  5939. break;
  5940. }
  5941. // If not resolved by previous actions try to switch to next level
  5942. if (!errorAction.resolved) {
  5943. this.switchLevel(data, nextAutoLevel);
  5944. }
  5945. }
  5946. switchLevel(data, levelIndex) {
  5947. if (levelIndex !== undefined && data.errorAction) {
  5948. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  5949. this.hls.nextAutoLevel = levelIndex;
  5950. data.errorAction.resolved = true;
  5951. // Stream controller is responsible for this but won't switch on false start
  5952. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5953. }
  5954. }
  5955. }
  5956. class BasePlaylistController {
  5957. constructor(hls, logPrefix) {
  5958. this.hls = void 0;
  5959. this.timer = -1;
  5960. this.requestScheduled = -1;
  5961. this.canLoad = false;
  5962. this.log = void 0;
  5963. this.warn = void 0;
  5964. this.log = logger.log.bind(logger, `${logPrefix}:`);
  5965. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  5966. this.hls = hls;
  5967. }
  5968. destroy() {
  5969. this.clearTimer();
  5970. // @ts-ignore
  5971. this.hls = this.log = this.warn = null;
  5972. }
  5973. clearTimer() {
  5974. if (this.timer !== -1) {
  5975. self.clearTimeout(this.timer);
  5976. this.timer = -1;
  5977. }
  5978. }
  5979. startLoad() {
  5980. this.canLoad = true;
  5981. this.requestScheduled = -1;
  5982. this.loadPlaylist();
  5983. }
  5984. stopLoad() {
  5985. this.canLoad = false;
  5986. this.clearTimer();
  5987. }
  5988. switchParams(playlistUri, previous, current) {
  5989. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  5990. if (renditionReports) {
  5991. let foundIndex = -1;
  5992. for (let i = 0; i < renditionReports.length; i++) {
  5993. const attr = renditionReports[i];
  5994. let uri;
  5995. try {
  5996. uri = new self.URL(attr.URI, previous.url).href;
  5997. } catch (error) {
  5998. logger.warn(`Could not construct new URL for Rendition Report: ${error}`);
  5999. uri = attr.URI || '';
  6000. }
  6001. // Use exact match. Otherwise, the last partial match, if any, will be used
  6002. // (Playlist URI includes a query string that the Rendition Report does not)
  6003. if (uri === playlistUri) {
  6004. foundIndex = i;
  6005. break;
  6006. } else if (uri === playlistUri.substring(0, uri.length)) {
  6007. foundIndex = i;
  6008. }
  6009. }
  6010. if (foundIndex !== -1) {
  6011. const attr = renditionReports[foundIndex];
  6012. const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  6013. let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  6014. if (this.hls.config.lowLatencyMode) {
  6015. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  6016. if (part >= 0 && currentGoal > previous.partTarget) {
  6017. part += 1;
  6018. }
  6019. }
  6020. const skip = current && getSkipValue(current);
  6021. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  6022. }
  6023. }
  6024. }
  6025. loadPlaylist(hlsUrlParameters) {
  6026. if (this.requestScheduled === -1) {
  6027. this.requestScheduled = self.performance.now();
  6028. }
  6029. // Loading is handled by the subclasses
  6030. }
  6031. shouldLoadPlaylist(playlist) {
  6032. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  6033. }
  6034. shouldReloadPlaylist(playlist) {
  6035. return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist);
  6036. }
  6037. playlistLoaded(index, data, previousDetails) {
  6038. const {
  6039. details,
  6040. stats
  6041. } = data;
  6042. // Set last updated date-time
  6043. const now = self.performance.now();
  6044. const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  6045. details.advancedDateTime = Date.now() - elapsed;
  6046. // if current playlist is a live playlist, arm a timer to reload it
  6047. if (details.live || previousDetails != null && previousDetails.live) {
  6048. details.reloaded(previousDetails);
  6049. if (previousDetails) {
  6050. this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);
  6051. }
  6052. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  6053. if (previousDetails && details.fragments.length > 0) {
  6054. mergeDetails(previousDetails, details);
  6055. }
  6056. if (!this.canLoad || !details.live) {
  6057. return;
  6058. }
  6059. let deliveryDirectives;
  6060. let msn = undefined;
  6061. let part = undefined;
  6062. if (details.canBlockReload && details.endSN && details.advanced) {
  6063. // Load level with LL-HLS delivery directives
  6064. const lowLatencyMode = this.hls.config.lowLatencyMode;
  6065. const lastPartSn = details.lastPartSn;
  6066. const endSn = details.endSN;
  6067. const lastPartIndex = details.lastPartIndex;
  6068. const hasParts = lastPartIndex !== -1;
  6069. const lastPart = lastPartSn === endSn;
  6070. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  6071. const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  6072. if (hasParts) {
  6073. msn = lastPart ? endSn + 1 : lastPartSn;
  6074. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  6075. } else {
  6076. msn = endSn + 1;
  6077. }
  6078. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  6079. // Update directives to obtain the Playlist that has the estimated additional duration of media
  6080. const lastAdvanced = details.age;
  6081. const cdnAge = lastAdvanced + details.ageHeader;
  6082. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  6083. if (currentGoal > 0) {
  6084. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  6085. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  6086. // then we either can't catchup, or the "age" header cannot be trusted.
  6087. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  6088. currentGoal = 0;
  6089. } else {
  6090. const segments = Math.floor(currentGoal / details.targetduration);
  6091. msn += segments;
  6092. if (part !== undefined) {
  6093. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  6094. part += parts;
  6095. }
  6096. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  6097. }
  6098. details.tuneInGoal = currentGoal;
  6099. }
  6100. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6101. if (lowLatencyMode || !lastPart) {
  6102. this.loadPlaylist(deliveryDirectives);
  6103. return;
  6104. }
  6105. } else if (details.canBlockReload || details.canSkipUntil) {
  6106. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6107. }
  6108. const bufferInfo = this.hls.mainForwardBufferInfo;
  6109. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  6110. const distanceToLiveEdgeMs = (details.edge - position) * 1000;
  6111. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  6112. if (details.updated && now > this.requestScheduled + reloadInterval) {
  6113. this.requestScheduled = stats.loading.start;
  6114. }
  6115. if (msn !== undefined && details.canBlockReload) {
  6116. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  6117. } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now) {
  6118. this.requestScheduled = now;
  6119. } else if (this.requestScheduled - now <= 0) {
  6120. this.requestScheduled += reloadInterval;
  6121. }
  6122. let estimatedTimeUntilUpdate = this.requestScheduled - now;
  6123. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  6124. this.log(`reload live playlist ${index} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  6125. // this.log(
  6126. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  6127. // reload in ${estimatedTimeUntilUpdate / 1000}
  6128. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  6129. // diff ${
  6130. // (reloadInterval -
  6131. // (estimatedTimeUntilUpdate +
  6132. // stats.loading.end -
  6133. // stats.loading.start)) /
  6134. // 1000
  6135. // }
  6136. // reload interval ${reloadInterval / 1000}
  6137. // target duration ${details.targetduration}
  6138. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  6139. // );
  6140. this.timer = self.setTimeout(() => this.loadPlaylist(deliveryDirectives), estimatedTimeUntilUpdate);
  6141. } else {
  6142. this.clearTimer();
  6143. }
  6144. }
  6145. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  6146. let skip = getSkipValue(details);
  6147. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  6148. msn = previousDeliveryDirectives.msn;
  6149. part = previousDeliveryDirectives.part;
  6150. skip = HlsSkip.No;
  6151. }
  6152. return new HlsUrlParameters(msn, part, skip);
  6153. }
  6154. checkRetry(errorEvent) {
  6155. const errorDetails = errorEvent.details;
  6156. const isTimeout = isTimeoutError(errorEvent);
  6157. const errorAction = errorEvent.errorAction;
  6158. const {
  6159. action,
  6160. retryCount = 0,
  6161. retryConfig
  6162. } = errorAction || {};
  6163. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  6164. if (retry) {
  6165. var _errorEvent$context;
  6166. this.requestScheduled = -1;
  6167. if (retryCount >= retryConfig.maxNumRetry) {
  6168. return false;
  6169. }
  6170. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  6171. // The LL-HLS request already timed out so retry immediately
  6172. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  6173. this.loadPlaylist();
  6174. } else {
  6175. const delay = getRetryDelay(retryConfig, retryCount);
  6176. // Schedule level/track reload
  6177. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  6178. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  6179. }
  6180. // `levelRetry = true` used to inform other controllers that a retry is happening
  6181. errorEvent.levelRetry = true;
  6182. errorAction.resolved = true;
  6183. }
  6184. return retry;
  6185. }
  6186. }
  6187. /*
  6188. * compute an Exponential Weighted moving average
  6189. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  6190. * - heavily inspired from shaka-player
  6191. */
  6192. class EWMA {
  6193. // About half of the estimated value will be from the last |halfLife| samples by weight.
  6194. constructor(halfLife, estimate = 0, weight = 0) {
  6195. this.halfLife = void 0;
  6196. this.alpha_ = void 0;
  6197. this.estimate_ = void 0;
  6198. this.totalWeight_ = void 0;
  6199. this.halfLife = halfLife;
  6200. // Larger values of alpha expire historical data more slowly.
  6201. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  6202. this.estimate_ = estimate;
  6203. this.totalWeight_ = weight;
  6204. }
  6205. sample(weight, value) {
  6206. const adjAlpha = Math.pow(this.alpha_, weight);
  6207. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  6208. this.totalWeight_ += weight;
  6209. }
  6210. getTotalWeight() {
  6211. return this.totalWeight_;
  6212. }
  6213. getEstimate() {
  6214. if (this.alpha_) {
  6215. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  6216. if (zeroFactor) {
  6217. return this.estimate_ / zeroFactor;
  6218. }
  6219. }
  6220. return this.estimate_;
  6221. }
  6222. }
  6223. /*
  6224. * EWMA Bandwidth Estimator
  6225. * - heavily inspired from shaka-player
  6226. * Tracks bandwidth samples and estimates available bandwidth.
  6227. * Based on the minimum of two exponentially-weighted moving averages with
  6228. * different half-lives.
  6229. */
  6230. class EwmaBandWidthEstimator {
  6231. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  6232. this.defaultEstimate_ = void 0;
  6233. this.minWeight_ = void 0;
  6234. this.minDelayMs_ = void 0;
  6235. this.slow_ = void 0;
  6236. this.fast_ = void 0;
  6237. this.defaultTTFB_ = void 0;
  6238. this.ttfb_ = void 0;
  6239. this.defaultEstimate_ = defaultEstimate;
  6240. this.minWeight_ = 0.001;
  6241. this.minDelayMs_ = 50;
  6242. this.slow_ = new EWMA(slow);
  6243. this.fast_ = new EWMA(fast);
  6244. this.defaultTTFB_ = defaultTTFB;
  6245. this.ttfb_ = new EWMA(slow);
  6246. }
  6247. update(slow, fast) {
  6248. const {
  6249. slow_,
  6250. fast_,
  6251. ttfb_
  6252. } = this;
  6253. if (slow_.halfLife !== slow) {
  6254. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  6255. }
  6256. if (fast_.halfLife !== fast) {
  6257. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  6258. }
  6259. if (ttfb_.halfLife !== slow) {
  6260. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  6261. }
  6262. }
  6263. sample(durationMs, numBytes) {
  6264. durationMs = Math.max(durationMs, this.minDelayMs_);
  6265. const numBits = 8 * numBytes;
  6266. // weight is duration in seconds
  6267. const durationS = durationMs / 1000;
  6268. // value is bandwidth in bits/s
  6269. const bandwidthInBps = numBits / durationS;
  6270. this.fast_.sample(durationS, bandwidthInBps);
  6271. this.slow_.sample(durationS, bandwidthInBps);
  6272. }
  6273. sampleTTFB(ttfb) {
  6274. // weight is frequency curve applied to TTFB in seconds
  6275. // (longer times have less weight with expected input under 1 second)
  6276. const seconds = ttfb / 1000;
  6277. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  6278. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  6279. }
  6280. canEstimate() {
  6281. return this.fast_.getTotalWeight() >= this.minWeight_;
  6282. }
  6283. getEstimate() {
  6284. if (this.canEstimate()) {
  6285. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  6286. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  6287. // Take the minimum of these two estimates. This should have the effect of
  6288. // adapting down quickly, but up more slowly.
  6289. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  6290. } else {
  6291. return this.defaultEstimate_;
  6292. }
  6293. }
  6294. getEstimateTTFB() {
  6295. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  6296. return this.ttfb_.getEstimate();
  6297. } else {
  6298. return this.defaultTTFB_;
  6299. }
  6300. }
  6301. destroy() {}
  6302. }
  6303. const SUPPORTED_INFO_DEFAULT = {
  6304. supported: true,
  6305. configurations: [],
  6306. decodingInfoResults: [{
  6307. supported: true,
  6308. powerEfficient: true,
  6309. smooth: true
  6310. }]
  6311. };
  6312. const SUPPORTED_INFO_CACHE = {};
  6313. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  6314. // Only test support when configuration is exceeds minimum options
  6315. const audioGroups = level.audioCodec ? level.audioGroups : null;
  6316. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6317. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6318. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  6319. let audioChannels = null;
  6320. if (audioGroups != null && audioGroups.length) {
  6321. try {
  6322. if (audioGroups.length === 1 && audioGroups[0]) {
  6323. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  6324. } else {
  6325. audioChannels = audioGroups.reduce((acc, groupId) => {
  6326. if (groupId) {
  6327. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  6328. if (!audioTrackGroup) {
  6329. throw new Error(`Audio track group ${groupId} not found`);
  6330. }
  6331. // Sum all channel key values
  6332. Object.keys(audioTrackGroup.channels).forEach(key => {
  6333. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  6334. });
  6335. }
  6336. return acc;
  6337. }, {
  6338. 2: 0
  6339. });
  6340. }
  6341. } catch (error) {
  6342. return true;
  6343. }
  6344. }
  6345. return level.videoCodec !== undefined && (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);
  6346. }
  6347. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities) {
  6348. const videoCodecs = level.videoCodec;
  6349. const audioCodecs = level.audioCodec;
  6350. if (!videoCodecs || !audioCodecs || !mediaCapabilities) {
  6351. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  6352. }
  6353. const baseVideoConfiguration = {
  6354. width: level.width,
  6355. height: level.height,
  6356. bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)),
  6357. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  6358. framerate: level.frameRate || 30
  6359. };
  6360. const videoRange = level.videoRange;
  6361. if (videoRange !== 'SDR') {
  6362. baseVideoConfiguration.transferFunction = videoRange.toLowerCase();
  6363. }
  6364. const configurations = videoCodecs.split(',').map(videoCodec => ({
  6365. type: 'media-source',
  6366. video: _objectSpread2(_objectSpread2({}, baseVideoConfiguration), {}, {
  6367. contentType: mimeTypeForCodec(videoCodec, 'video')
  6368. })
  6369. }));
  6370. if (audioCodecs && level.audioGroups) {
  6371. level.audioGroups.forEach(audioGroupId => {
  6372. var _audioTracksByGroup$g;
  6373. if (!audioGroupId) {
  6374. return;
  6375. }
  6376. (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks.forEach(audioTrack => {
  6377. if (audioTrack.groupId === audioGroupId) {
  6378. const channels = audioTrack.channels || '';
  6379. const channelsNumber = parseFloat(channels);
  6380. if (isFiniteNumber(channelsNumber) && channelsNumber > 2) {
  6381. configurations.push.apply(configurations, audioCodecs.split(',').map(audioCodec => ({
  6382. type: 'media-source',
  6383. audio: {
  6384. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  6385. channels: '' + channelsNumber
  6386. // spatialRendering:
  6387. // audioCodec === 'ec-3' && channels.indexOf('JOC'),
  6388. }
  6389. })));
  6390. }
  6391. }
  6392. });
  6393. });
  6394. }
  6395. return Promise.all(configurations.map(configuration => {
  6396. // Cache MediaCapabilities promises
  6397. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  6398. return SUPPORTED_INFO_CACHE[decodingInfoKey] || (SUPPORTED_INFO_CACHE[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  6399. })).then(decodingInfoResults => ({
  6400. supported: !decodingInfoResults.some(info => !info.supported),
  6401. configurations,
  6402. decodingInfoResults
  6403. })).catch(error => ({
  6404. supported: false,
  6405. configurations,
  6406. decodingInfoResults: [],
  6407. error
  6408. }));
  6409. }
  6410. function getMediaDecodingInfoKey(config) {
  6411. const {
  6412. audio,
  6413. video
  6414. } = config;
  6415. const mediaConfig = video || audio;
  6416. if (mediaConfig) {
  6417. const codec = mediaConfig.contentType.split('"')[1];
  6418. if (video) {
  6419. return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || 'sd'}_${codec}_${Math.ceil(video.bitrate / 1e5)}`;
  6420. }
  6421. if (audio) {
  6422. return `c${audio.channels}${audio.spatialRendering ? 's' : 'n'}_${codec}`;
  6423. }
  6424. }
  6425. return '';
  6426. }
  6427. /**
  6428. * @returns Whether we can detect and validate HDR capability within the window context
  6429. */
  6430. function isHdrSupported() {
  6431. if (typeof matchMedia === 'function') {
  6432. const mediaQueryList = matchMedia('(dynamic-range: high)');
  6433. const badQuery = matchMedia('bad query');
  6434. if (mediaQueryList.media !== badQuery.media) {
  6435. return mediaQueryList.matches === true;
  6436. }
  6437. }
  6438. return false;
  6439. }
  6440. /**
  6441. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  6442. * When both inputs are null:
  6443. *
  6444. * `{ preferHDR: false, allowedVideoRanges: [] }`
  6445. *
  6446. * When `currentVideoRange` non-null, maintain the active range:
  6447. *
  6448. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  6449. *
  6450. * When VideoSelectionOption non-null:
  6451. *
  6452. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  6453. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  6454. * - Else check window for HDR support and set `preferHDR` to the result.
  6455. *
  6456. * @param currentVideoRange
  6457. * @param videoPreference
  6458. */
  6459. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  6460. let preferHDR = false;
  6461. let allowedVideoRanges = [];
  6462. if (currentVideoRange) {
  6463. preferHDR = currentVideoRange !== 'SDR';
  6464. allowedVideoRanges = [currentVideoRange];
  6465. }
  6466. if (videoPreference) {
  6467. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  6468. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : isHdrSupported();
  6469. if (preferHDR) {
  6470. allowedVideoRanges = allowedVideoRanges.filter(range => range !== 'SDR');
  6471. } else {
  6472. allowedVideoRanges = ['SDR'];
  6473. }
  6474. }
  6475. return {
  6476. preferHDR,
  6477. allowedVideoRanges
  6478. };
  6479. }
  6480. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  6481. const codecSets = Object.keys(codecTiers);
  6482. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6483. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6484. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  6485. // Use first level set to determine stereo, and minimum resolution and framerate
  6486. let hasStereo = true;
  6487. let hasCurrentVideoRange = false;
  6488. let minHeight = Infinity;
  6489. let minFramerate = Infinity;
  6490. let minBitrate = Infinity;
  6491. let selectedScore = 0;
  6492. let videoRanges = [];
  6493. const {
  6494. preferHDR,
  6495. allowedVideoRanges
  6496. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  6497. for (let i = codecSets.length; i--;) {
  6498. const tier = codecTiers[codecSets[i]];
  6499. hasStereo = tier.channels[2] > 0;
  6500. minHeight = Math.min(minHeight, tier.minHeight);
  6501. minFramerate = Math.min(minFramerate, tier.minFramerate);
  6502. minBitrate = Math.min(minBitrate, tier.minBitrate);
  6503. const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);
  6504. if (matchingVideoRanges.length > 0) {
  6505. hasCurrentVideoRange = true;
  6506. videoRanges = matchingVideoRanges;
  6507. }
  6508. }
  6509. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  6510. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  6511. const maxHeight = Math.max(1080, minHeight);
  6512. const maxFramerate = Math.max(30, minFramerate);
  6513. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  6514. currentBw = Math.max(minBitrate, currentBw);
  6515. // If there are no variants with matching preference, set currentVideoRange to undefined
  6516. if (!hasCurrentVideoRange) {
  6517. currentVideoRange = undefined;
  6518. videoRanges = [];
  6519. }
  6520. const codecSet = codecSets.reduce((selected, candidate) => {
  6521. // 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
  6522. const candidateTier = codecTiers[candidate];
  6523. if (candidate === selected) {
  6524. return selected;
  6525. }
  6526. if (candidateTier.minBitrate > currentBw) {
  6527. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  6528. return selected;
  6529. }
  6530. if (!candidateTier.hasDefaultAudio) {
  6531. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  6532. return selected;
  6533. }
  6534. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  6535. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  6536. return selected;
  6537. }
  6538. if (channelsPreference && !preferStereo) {
  6539. if (!candidateTier.channels[channelsPreference]) {
  6540. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  6541. return selected;
  6542. }
  6543. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  6544. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  6545. return selected;
  6546. }
  6547. if (candidateTier.minHeight > maxHeight) {
  6548. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  6549. return selected;
  6550. }
  6551. if (candidateTier.minFramerate > maxFramerate) {
  6552. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  6553. return selected;
  6554. }
  6555. if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {
  6556. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${JSON.stringify(videoRanges)} found`);
  6557. return selected;
  6558. }
  6559. if (candidateTier.maxScore < selectedScore) {
  6560. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  6561. return selected;
  6562. }
  6563. // Remove candiates with less preferred codecs or more errors
  6564. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  6565. return selected;
  6566. }
  6567. selectedScore = candidateTier.maxScore;
  6568. return candidate;
  6569. }, undefined);
  6570. return {
  6571. codecSet,
  6572. videoRanges,
  6573. preferHDR,
  6574. minFramerate,
  6575. minBitrate
  6576. };
  6577. }
  6578. function logStartCodecCandidateIgnored(codeSet, reason) {
  6579. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  6580. }
  6581. function getAudioTracksByGroup(allAudioTracks) {
  6582. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  6583. let trackGroup = audioTracksByGroup.groups[track.groupId];
  6584. if (!trackGroup) {
  6585. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  6586. tracks: [],
  6587. channels: {
  6588. 2: 0
  6589. },
  6590. hasDefault: false,
  6591. hasAutoSelect: false
  6592. };
  6593. }
  6594. trackGroup.tracks.push(track);
  6595. const channelsKey = track.channels || '2';
  6596. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  6597. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  6598. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  6599. if (trackGroup.hasDefault) {
  6600. audioTracksByGroup.hasDefaultAudio = true;
  6601. }
  6602. if (trackGroup.hasAutoSelect) {
  6603. audioTracksByGroup.hasAutoSelectAudio = true;
  6604. }
  6605. return audioTracksByGroup;
  6606. }, {
  6607. hasDefaultAudio: false,
  6608. hasAutoSelectAudio: false,
  6609. groups: {}
  6610. });
  6611. }
  6612. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  6613. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level) => {
  6614. if (!level.codecSet) {
  6615. return tiers;
  6616. }
  6617. const audioGroups = level.audioGroups;
  6618. let tier = tiers[level.codecSet];
  6619. if (!tier) {
  6620. tiers[level.codecSet] = tier = {
  6621. minBitrate: Infinity,
  6622. minHeight: Infinity,
  6623. minFramerate: Infinity,
  6624. maxScore: 0,
  6625. videoRanges: {
  6626. SDR: 0
  6627. },
  6628. channels: {
  6629. '2': 0
  6630. },
  6631. hasDefaultAudio: !audioGroups,
  6632. fragmentError: 0
  6633. };
  6634. }
  6635. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  6636. const lesserWidthOrHeight = Math.min(level.height, level.width);
  6637. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  6638. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  6639. tier.maxScore = Math.max(tier.maxScore, level.score);
  6640. tier.fragmentError += level.fragmentError;
  6641. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  6642. if (audioGroups) {
  6643. audioGroups.forEach(audioGroupId => {
  6644. if (!audioGroupId) {
  6645. return;
  6646. }
  6647. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  6648. if (!audioGroup) {
  6649. return;
  6650. }
  6651. // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants
  6652. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  6653. Object.keys(audioGroup.channels).forEach(channels => {
  6654. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  6655. });
  6656. });
  6657. }
  6658. return tiers;
  6659. }, {});
  6660. }
  6661. function findMatchingOption(option, tracks, matchPredicate) {
  6662. if ('attrs' in option) {
  6663. const index = tracks.indexOf(option);
  6664. if (index !== -1) {
  6665. return index;
  6666. }
  6667. }
  6668. for (let i = 0; i < tracks.length; i++) {
  6669. const track = tracks[i];
  6670. if (matchesOption(option, track, matchPredicate)) {
  6671. return i;
  6672. }
  6673. }
  6674. return -1;
  6675. }
  6676. function matchesOption(option, track, matchPredicate) {
  6677. const {
  6678. groupId,
  6679. name,
  6680. lang,
  6681. assocLang,
  6682. characteristics,
  6683. default: isDefault
  6684. } = option;
  6685. const forced = option.forced;
  6686. return (groupId === undefined || track.groupId === groupId) && (name === undefined || track.name === name) && (lang === undefined || track.lang === lang) && (lang === undefined || track.assocLang === assocLang) && (isDefault === undefined || track.default === isDefault) && (forced === undefined || track.forced === forced) && (characteristics === undefined || characteristicsMatch(characteristics, track.characteristics)) && (matchPredicate === undefined || matchPredicate(option, track));
  6687. }
  6688. function characteristicsMatch(characteristicsA, characteristicsB = '') {
  6689. const arrA = characteristicsA.split(',');
  6690. const arrB = characteristicsB.split(',');
  6691. // Expects each item to be unique:
  6692. return arrA.length === arrB.length && !arrA.some(el => arrB.indexOf(el) === -1);
  6693. }
  6694. function audioMatchPredicate(option, track) {
  6695. const {
  6696. audioCodec,
  6697. channels
  6698. } = option;
  6699. return (audioCodec === undefined || (track.audioCodec || '').substring(0, 4) === audioCodec.substring(0, 4)) && (channels === undefined || channels === (track.channels || '2'));
  6700. }
  6701. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  6702. const currentLevel = levels[searchIndex];
  6703. // Are there variants with same URI as current level?
  6704. // If so, find a match that does not require any level URI change
  6705. const variants = levels.reduce((variantMap, level, index) => {
  6706. const uri = level.uri;
  6707. const renditions = variantMap[uri] || (variantMap[uri] = []);
  6708. renditions.push(index);
  6709. return variantMap;
  6710. }, {});
  6711. const renditions = variants[currentLevel.uri];
  6712. if (renditions.length > 1) {
  6713. searchIndex = Math.max.apply(Math, renditions);
  6714. }
  6715. // Find best match
  6716. const currentVideoRange = currentLevel.videoRange;
  6717. const currentFrameRate = currentLevel.frameRate;
  6718. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  6719. const matchingVideo = searchDownAndUpList(levels, searchIndex, level => {
  6720. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  6721. return false;
  6722. }
  6723. const audioGroups = level.audioGroups;
  6724. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  6725. return findMatchingOption(option, tracks, matchPredicate) > -1;
  6726. });
  6727. if (matchingVideo > -1) {
  6728. return matchingVideo;
  6729. }
  6730. return searchDownAndUpList(levels, searchIndex, level => {
  6731. const audioGroups = level.audioGroups;
  6732. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  6733. return findMatchingOption(option, tracks, matchPredicate) > -1;
  6734. });
  6735. }
  6736. function searchDownAndUpList(arr, searchIndex, predicate) {
  6737. for (let i = searchIndex; i; i--) {
  6738. if (predicate(arr[i])) {
  6739. return i;
  6740. }
  6741. }
  6742. for (let i = searchIndex + 1; i < arr.length; i++) {
  6743. if (predicate(arr[i])) {
  6744. return i;
  6745. }
  6746. }
  6747. return -1;
  6748. }
  6749. class AbrController {
  6750. constructor(_hls) {
  6751. this.hls = void 0;
  6752. this.lastLevelLoadSec = 0;
  6753. this.lastLoadedFragLevel = -1;
  6754. this.firstSelection = -1;
  6755. this._nextAutoLevel = -1;
  6756. this.nextAutoLevelKey = '';
  6757. this.audioTracksByGroup = null;
  6758. this.codecTiers = null;
  6759. this.timer = -1;
  6760. this.fragCurrent = null;
  6761. this.partCurrent = null;
  6762. this.bitrateTestDelay = 0;
  6763. this.bwEstimator = void 0;
  6764. /*
  6765. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  6766. quickly enough to prevent underbuffering
  6767. */
  6768. this._abandonRulesCheck = () => {
  6769. const {
  6770. fragCurrent: frag,
  6771. partCurrent: part,
  6772. hls
  6773. } = this;
  6774. const {
  6775. autoLevelEnabled,
  6776. media
  6777. } = hls;
  6778. if (!frag || !media) {
  6779. return;
  6780. }
  6781. const now = performance.now();
  6782. const stats = part ? part.stats : frag.stats;
  6783. const duration = part ? part.duration : frag.duration;
  6784. const timeLoading = now - stats.loading.start;
  6785. const minAutoLevel = hls.minAutoLevel;
  6786. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  6787. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) {
  6788. this.clearTimer();
  6789. // reset forced auto level value so that next level will be selected
  6790. this._nextAutoLevel = -1;
  6791. return;
  6792. }
  6793. // This check only runs if we're in ABR mode and actually playing
  6794. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  6795. return;
  6796. }
  6797. const bufferInfo = hls.mainForwardBufferInfo;
  6798. if (bufferInfo === null) {
  6799. return;
  6800. }
  6801. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6802. const playbackRate = Math.abs(media.playbackRate);
  6803. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  6804. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  6805. return;
  6806. }
  6807. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  6808. const bufferStarvationDelay = bufferInfo.len / playbackRate;
  6809. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6810. const loadedFirstByte = stats.loaded && ttfb > -1;
  6811. const bwEstimate = this.getBwEstimate();
  6812. const levels = hls.levels;
  6813. const level = levels[frag.level];
  6814. const expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8));
  6815. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  6816. if (timeStreaming < 1 && loadedFirstByte) {
  6817. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  6818. }
  6819. const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  6820. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  6821. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1000;
  6822. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  6823. if (fragLoadedDelay <= bufferStarvationDelay) {
  6824. return;
  6825. }
  6826. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  6827. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  6828. let nextLoadLevel;
  6829. // Iterate through lower level and try to find the largest one that avoids rebuffering
  6830. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  6831. // compute time to load next fragment at lower level
  6832. // 8 = bits per byte (bps/Bps)
  6833. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  6834. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbEstimate / 1000, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details);
  6835. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  6836. break;
  6837. }
  6838. }
  6839. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  6840. // to load the current one
  6841. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  6842. return;
  6843. }
  6844. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  6845. if (fragLevelNextLoadedDelay > duration * 10) {
  6846. return;
  6847. }
  6848. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  6849. if (loadedFirstByte) {
  6850. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  6851. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6852. } else {
  6853. // If there has been no loading progress, sample TTFB
  6854. this.bwEstimator.sampleTTFB(timeLoading);
  6855. }
  6856. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  6857. if (this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) {
  6858. this.resetEstimator(nextLoadLevelBitrate);
  6859. }
  6860. this.clearTimer();
  6861. logger.warn(`[abr] Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} is loading too slowly;
  6862. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  6863. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  6864. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  6865. TTFB estimate: ${ttfb | 0} ms
  6866. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps
  6867. New BW estimate: ${this.getBwEstimate() | 0} bps
  6868. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  6869. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  6870. frag,
  6871. part,
  6872. stats
  6873. });
  6874. };
  6875. this.hls = _hls;
  6876. this.bwEstimator = this.initEstimator();
  6877. this.registerListeners();
  6878. }
  6879. resetEstimator(abrEwmaDefaultEstimate) {
  6880. if (abrEwmaDefaultEstimate) {
  6881. logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  6882. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  6883. }
  6884. this.firstSelection = -1;
  6885. this.bwEstimator = this.initEstimator();
  6886. }
  6887. initEstimator() {
  6888. const config = this.hls.config;
  6889. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  6890. }
  6891. registerListeners() {
  6892. const {
  6893. hls
  6894. } = this;
  6895. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6896. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  6897. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6898. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6899. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6900. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6901. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6902. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6903. hls.on(Events.ERROR, this.onError, this);
  6904. }
  6905. unregisterListeners() {
  6906. const {
  6907. hls
  6908. } = this;
  6909. if (!hls) {
  6910. return;
  6911. }
  6912. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6913. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  6914. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6915. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6916. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6917. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6918. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6919. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6920. hls.off(Events.ERROR, this.onError, this);
  6921. }
  6922. destroy() {
  6923. this.unregisterListeners();
  6924. this.clearTimer();
  6925. // @ts-ignore
  6926. this.hls = this._abandonRulesCheck = null;
  6927. this.fragCurrent = this.partCurrent = null;
  6928. }
  6929. onManifestLoading(event, data) {
  6930. this.lastLoadedFragLevel = -1;
  6931. this.firstSelection = -1;
  6932. this.lastLevelLoadSec = 0;
  6933. this.fragCurrent = this.partCurrent = null;
  6934. this.onLevelsUpdated();
  6935. this.clearTimer();
  6936. }
  6937. onLevelsUpdated() {
  6938. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  6939. this.lastLoadedFragLevel = this.fragCurrent.level;
  6940. }
  6941. this._nextAutoLevel = -1;
  6942. this.onMaxAutoLevelUpdated();
  6943. this.codecTiers = null;
  6944. this.audioTracksByGroup = null;
  6945. }
  6946. onMaxAutoLevelUpdated() {
  6947. this.firstSelection = -1;
  6948. this.nextAutoLevelKey = '';
  6949. }
  6950. onFragLoading(event, data) {
  6951. const frag = data.frag;
  6952. if (this.ignoreFragment(frag)) {
  6953. return;
  6954. }
  6955. if (!frag.bitrateTest) {
  6956. var _data$part;
  6957. this.fragCurrent = frag;
  6958. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  6959. }
  6960. this.clearTimer();
  6961. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  6962. }
  6963. onLevelSwitching(event, data) {
  6964. this.clearTimer();
  6965. }
  6966. onError(event, data) {
  6967. if (data.fatal) {
  6968. return;
  6969. }
  6970. switch (data.details) {
  6971. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  6972. case ErrorDetails.BUFFER_APPEND_ERROR:
  6973. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  6974. this.lastLoadedFragLevel = -1;
  6975. this.firstSelection = -1;
  6976. break;
  6977. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  6978. {
  6979. const frag = data.frag;
  6980. const {
  6981. fragCurrent,
  6982. partCurrent: part
  6983. } = this;
  6984. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  6985. const now = performance.now();
  6986. const stats = part ? part.stats : frag.stats;
  6987. const timeLoading = now - stats.loading.start;
  6988. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6989. const loadedFirstByte = stats.loaded && ttfb > -1;
  6990. if (loadedFirstByte) {
  6991. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6992. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6993. } else {
  6994. this.bwEstimator.sampleTTFB(timeLoading);
  6995. }
  6996. }
  6997. break;
  6998. }
  6999. }
  7000. }
  7001. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  7002. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  7003. const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
  7004. return fragLoadSec + playlistLoadSec;
  7005. }
  7006. onLevelLoaded(event, data) {
  7007. const config = this.hls.config;
  7008. const {
  7009. loading
  7010. } = data.stats;
  7011. const timeLoadingMs = loading.end - loading.start;
  7012. if (isFiniteNumber(timeLoadingMs)) {
  7013. this.lastLevelLoadSec = timeLoadingMs / 1000;
  7014. }
  7015. if (data.details.live) {
  7016. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  7017. } else {
  7018. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  7019. }
  7020. }
  7021. onFragLoaded(event, {
  7022. frag,
  7023. part
  7024. }) {
  7025. const stats = part ? part.stats : frag.stats;
  7026. if (frag.type === PlaylistLevelType.MAIN) {
  7027. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  7028. }
  7029. if (this.ignoreFragment(frag)) {
  7030. return;
  7031. }
  7032. // stop monitoring bw once frag loaded
  7033. this.clearTimer();
  7034. // reset forced auto level value so that next level will be selected
  7035. if (frag.level === this._nextAutoLevel) {
  7036. this._nextAutoLevel = -1;
  7037. }
  7038. this.firstSelection = -1;
  7039. // compute level average bitrate
  7040. if (this.hls.config.abrMaxWithRealBitrate) {
  7041. const duration = part ? part.duration : frag.duration;
  7042. const level = this.hls.levels[frag.level];
  7043. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  7044. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  7045. level.loaded = {
  7046. bytes: loadedBytes,
  7047. duration: loadedDuration
  7048. };
  7049. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  7050. }
  7051. if (frag.bitrateTest) {
  7052. const fragBufferedData = {
  7053. stats,
  7054. frag,
  7055. part,
  7056. id: frag.type
  7057. };
  7058. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  7059. frag.bitrateTest = false;
  7060. } else {
  7061. // store level id after successful fragment load for playback
  7062. this.lastLoadedFragLevel = frag.level;
  7063. }
  7064. }
  7065. onFragBuffered(event, data) {
  7066. const {
  7067. frag,
  7068. part
  7069. } = data;
  7070. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  7071. if (stats.aborted) {
  7072. return;
  7073. }
  7074. if (this.ignoreFragment(frag)) {
  7075. return;
  7076. }
  7077. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  7078. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  7079. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  7080. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  7081. this.bwEstimator.sample(processingMs, stats.loaded);
  7082. stats.bwEstimate = this.getBwEstimate();
  7083. if (frag.bitrateTest) {
  7084. this.bitrateTestDelay = processingMs / 1000;
  7085. } else {
  7086. this.bitrateTestDelay = 0;
  7087. }
  7088. }
  7089. ignoreFragment(frag) {
  7090. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  7091. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  7092. }
  7093. clearTimer() {
  7094. if (this.timer > -1) {
  7095. self.clearInterval(this.timer);
  7096. this.timer = -1;
  7097. }
  7098. }
  7099. get firstAutoLevel() {
  7100. const {
  7101. maxAutoLevel,
  7102. minAutoLevel
  7103. } = this.hls;
  7104. const bwEstimate = this.getBwEstimate();
  7105. const maxStartDelay = this.hls.config.maxStarvationDelay;
  7106. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  7107. if (abrAutoLevel > -1) {
  7108. return abrAutoLevel;
  7109. }
  7110. const firstLevel = this.hls.firstLevel;
  7111. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  7112. logger.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  7113. return clamped;
  7114. }
  7115. get forcedAutoLevel() {
  7116. if (this.nextAutoLevelKey) {
  7117. return -1;
  7118. }
  7119. return this._nextAutoLevel;
  7120. }
  7121. // return next auto level
  7122. get nextAutoLevel() {
  7123. const forcedAutoLevel = this.forcedAutoLevel;
  7124. const bwEstimator = this.bwEstimator;
  7125. const useEstimate = bwEstimator.canEstimate();
  7126. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  7127. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  7128. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  7129. return forcedAutoLevel;
  7130. }
  7131. // compute next level using ABR logic
  7132. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  7133. // use forced auto level while it hasn't errored more than ABR selection
  7134. if (forcedAutoLevel !== -1) {
  7135. const levels = this.hls.levels;
  7136. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  7137. return forcedAutoLevel;
  7138. }
  7139. }
  7140. // save result until state has changed
  7141. this._nextAutoLevel = nextABRAutoLevel;
  7142. this.nextAutoLevelKey = this.getAutoLevelKey();
  7143. return nextABRAutoLevel;
  7144. }
  7145. getAutoLevelKey() {
  7146. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  7147. }
  7148. getNextABRAutoLevel() {
  7149. const {
  7150. fragCurrent,
  7151. partCurrent,
  7152. hls
  7153. } = this;
  7154. const {
  7155. maxAutoLevel,
  7156. config,
  7157. minAutoLevel
  7158. } = hls;
  7159. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  7160. const avgbw = this.getBwEstimate();
  7161. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  7162. const bufferStarvationDelay = this.getStarvationDelay();
  7163. let bwFactor = config.abrBandWidthFactor;
  7164. let bwUpFactor = config.abrBandWidthUpFactor;
  7165. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  7166. if (bufferStarvationDelay) {
  7167. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  7168. if (_bestLevel >= 0) {
  7169. return _bestLevel;
  7170. }
  7171. }
  7172. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  7173. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  7174. if (!bufferStarvationDelay) {
  7175. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  7176. const bitrateTestDelay = this.bitrateTestDelay;
  7177. if (bitrateTestDelay) {
  7178. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  7179. // max video loading delay used in automatic start level selection :
  7180. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  7181. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  7182. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  7183. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  7184. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  7185. logger.info(`[abr] bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);
  7186. // don't use conservative factor on bitrate test
  7187. bwFactor = bwUpFactor = 1;
  7188. }
  7189. }
  7190. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  7191. logger.info(`[abr] ${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);
  7192. if (bestLevel > -1) {
  7193. return bestLevel;
  7194. }
  7195. // If no matching level found, see if min auto level would be a better option
  7196. const minLevel = hls.levels[minAutoLevel];
  7197. const autoLevel = hls.levels[hls.loadLevel];
  7198. if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) {
  7199. return minAutoLevel;
  7200. }
  7201. // or if bitrate is not lower, continue to use loadLevel
  7202. return hls.loadLevel;
  7203. }
  7204. getStarvationDelay() {
  7205. const hls = this.hls;
  7206. const media = hls.media;
  7207. if (!media) {
  7208. return Infinity;
  7209. }
  7210. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  7211. // if we're playing back at the normal rate.
  7212. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  7213. const bufferInfo = hls.mainForwardBufferInfo;
  7214. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  7215. }
  7216. getBwEstimate() {
  7217. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  7218. }
  7219. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  7220. var _level$details;
  7221. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  7222. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  7223. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  7224. const {
  7225. fragCurrent,
  7226. partCurrent
  7227. } = this;
  7228. const {
  7229. levels,
  7230. allAudioTracks,
  7231. loadLevel,
  7232. config
  7233. } = this.hls;
  7234. if (levels.length === 1) {
  7235. return 0;
  7236. }
  7237. const level = levels[selectionBaseLevel];
  7238. const live = !!(level != null && (_level$details = level.details) != null && _level$details.live);
  7239. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  7240. let currentCodecSet;
  7241. let currentVideoRange = 'SDR';
  7242. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  7243. const {
  7244. audioPreference,
  7245. videoPreference
  7246. } = config;
  7247. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  7248. if (firstSelection) {
  7249. if (this.firstSelection !== -1) {
  7250. return this.firstSelection;
  7251. }
  7252. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  7253. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  7254. const {
  7255. codecSet,
  7256. videoRanges,
  7257. minFramerate,
  7258. minBitrate,
  7259. preferHDR
  7260. } = startTier;
  7261. currentCodecSet = codecSet;
  7262. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  7263. currentFrameRate = minFramerate;
  7264. currentBw = Math.max(currentBw, minBitrate);
  7265. logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`);
  7266. } else {
  7267. currentCodecSet = level == null ? void 0 : level.codecSet;
  7268. currentVideoRange = level == null ? void 0 : level.videoRange;
  7269. }
  7270. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  7271. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  7272. const levelsSkipped = [];
  7273. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  7274. var _levelInfo$supportedR;
  7275. const levelInfo = levels[i];
  7276. const upSwitch = i > selectionBaseLevel;
  7277. if (!levelInfo) {
  7278. continue;
  7279. }
  7280. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  7281. const mediaCapabilities = navigator.mediaCapabilities;
  7282. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === 'function' && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  7283. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities);
  7284. levelInfo.supportedPromise.then(decodingInfo => {
  7285. if (!this.hls) {
  7286. return;
  7287. }
  7288. levelInfo.supportedResult = decodingInfo;
  7289. const levels = this.hls.levels;
  7290. const index = levels.indexOf(levelInfo);
  7291. if (decodingInfo.error) {
  7292. logger.warn(`[abr] MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${JSON.stringify(decodingInfo)}`);
  7293. } else if (!decodingInfo.supported) {
  7294. logger.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${index} ${JSON.stringify(decodingInfo)}`);
  7295. if (index > -1 && levels.length > 1) {
  7296. logger.log(`[abr] Removing unsupported level ${index}`);
  7297. this.hls.removeLevel(index);
  7298. }
  7299. }
  7300. });
  7301. } else {
  7302. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  7303. }
  7304. }
  7305. // skip candidates which change codec-family or video-range,
  7306. // and which decrease or increase frame-rate for up and down-switch respectfully
  7307. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) {
  7308. levelsSkipped.push(i);
  7309. continue;
  7310. }
  7311. const levelDetails = levelInfo.details;
  7312. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  7313. let adjustedbw;
  7314. // follow algorithm captured from stagefright :
  7315. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  7316. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  7317. // consider only 80% of the available bandwidth, but if we are switching up,
  7318. // be even more conservative (70%) to avoid overestimating and immediately
  7319. // switching back.
  7320. if (!upSwitch) {
  7321. adjustedbw = bwFactor * currentBw;
  7322. } else {
  7323. adjustedbw = bwUpFactor * currentBw;
  7324. }
  7325. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  7326. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i].averageBitrate : levels[i].maxBitrate;
  7327. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  7328. const canSwitchWithinTolerance =
  7329. // if adjusted bw is greater than level bitrate AND
  7330. adjustedbw >= bitrate && (
  7331. // no level change, or new level has no error history
  7332. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  7333. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  7334. // 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 ...
  7335. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  7336. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  7337. if (canSwitchWithinTolerance) {
  7338. const forcedAutoLevel = this.forcedAutoLevel;
  7339. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  7340. if (levelsSkipped.length) {
  7341. logger.trace(`[abr] Skipped level(s) ${levelsSkipped.join(',')} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:"${levels[levelsSkipped[0]].codecs}" ${levels[levelsSkipped[0]].videoRange}; not compatible with "${level.codecs}" ${currentVideoRange}`);
  7342. }
  7343. logger.info(`[abr] switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${currentCodecSet} videoRange:${currentVideoRange} hls.loadLevel:${loadLevel}`);
  7344. }
  7345. if (firstSelection) {
  7346. this.firstSelection = i;
  7347. }
  7348. // as we are looping from highest to lowest, this will return the best achievable quality level
  7349. return i;
  7350. }
  7351. }
  7352. // not enough time budget even with quality level 0 ... rebuffering might happen
  7353. return -1;
  7354. }
  7355. set nextAutoLevel(nextLevel) {
  7356. const {
  7357. maxAutoLevel,
  7358. minAutoLevel
  7359. } = this.hls;
  7360. const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  7361. if (this._nextAutoLevel !== value) {
  7362. this.nextAutoLevelKey = '';
  7363. this._nextAutoLevel = value;
  7364. }
  7365. }
  7366. }
  7367. /**
  7368. * @ignore
  7369. * Sub-class specialization of EventHandler base class.
  7370. *
  7371. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  7372. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  7373. *
  7374. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  7375. * using the `tick` method.
  7376. *
  7377. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  7378. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  7379. *
  7380. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  7381. * and cancelled with `clearNextTick`.
  7382. *
  7383. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  7384. *
  7385. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  7386. *
  7387. * Further explanations:
  7388. *
  7389. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  7390. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  7391. *
  7392. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  7393. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  7394. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  7395. */
  7396. class TaskLoop {
  7397. constructor() {
  7398. this._boundTick = void 0;
  7399. this._tickTimer = null;
  7400. this._tickInterval = null;
  7401. this._tickCallCount = 0;
  7402. this._boundTick = this.tick.bind(this);
  7403. }
  7404. destroy() {
  7405. this.onHandlerDestroying();
  7406. this.onHandlerDestroyed();
  7407. }
  7408. onHandlerDestroying() {
  7409. // clear all timers before unregistering from event bus
  7410. this.clearNextTick();
  7411. this.clearInterval();
  7412. }
  7413. onHandlerDestroyed() {}
  7414. hasInterval() {
  7415. return !!this._tickInterval;
  7416. }
  7417. hasNextTick() {
  7418. return !!this._tickTimer;
  7419. }
  7420. /**
  7421. * @param millis - Interval time (ms)
  7422. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  7423. */
  7424. setInterval(millis) {
  7425. if (!this._tickInterval) {
  7426. this._tickCallCount = 0;
  7427. this._tickInterval = self.setInterval(this._boundTick, millis);
  7428. return true;
  7429. }
  7430. return false;
  7431. }
  7432. /**
  7433. * @returns True when interval was cleared, false when none was set (no effect)
  7434. */
  7435. clearInterval() {
  7436. if (this._tickInterval) {
  7437. self.clearInterval(this._tickInterval);
  7438. this._tickInterval = null;
  7439. return true;
  7440. }
  7441. return false;
  7442. }
  7443. /**
  7444. * @returns True when timeout was cleared, false when none was set (no effect)
  7445. */
  7446. clearNextTick() {
  7447. if (this._tickTimer) {
  7448. self.clearTimeout(this._tickTimer);
  7449. this._tickTimer = null;
  7450. return true;
  7451. }
  7452. return false;
  7453. }
  7454. /**
  7455. * Will call the subclass doTick implementation in this main loop tick
  7456. * or in the next one (via setTimeout(,0)) in case it has already been called
  7457. * in this tick (in case this is a re-entrant call).
  7458. */
  7459. tick() {
  7460. this._tickCallCount++;
  7461. if (this._tickCallCount === 1) {
  7462. this.doTick();
  7463. // re-entrant call to tick from previous doTick call stack
  7464. // -> schedule a call on the next main loop iteration to process this task processing request
  7465. if (this._tickCallCount > 1) {
  7466. // make sure only one timer exists at any time at max
  7467. this.tickImmediate();
  7468. }
  7469. this._tickCallCount = 0;
  7470. }
  7471. }
  7472. tickImmediate() {
  7473. this.clearNextTick();
  7474. this._tickTimer = self.setTimeout(this._boundTick, 0);
  7475. }
  7476. /**
  7477. * For subclass to implement task logic
  7478. * @abstract
  7479. */
  7480. doTick() {}
  7481. }
  7482. var FragmentState = {
  7483. NOT_LOADED: "NOT_LOADED",
  7484. APPENDING: "APPENDING",
  7485. PARTIAL: "PARTIAL",
  7486. OK: "OK"
  7487. };
  7488. class FragmentTracker {
  7489. constructor(hls) {
  7490. this.activePartLists = Object.create(null);
  7491. this.endListFragments = Object.create(null);
  7492. this.fragments = Object.create(null);
  7493. this.timeRanges = Object.create(null);
  7494. this.bufferPadding = 0.2;
  7495. this.hls = void 0;
  7496. this.hasGaps = false;
  7497. this.hls = hls;
  7498. this._registerListeners();
  7499. }
  7500. _registerListeners() {
  7501. const {
  7502. hls
  7503. } = this;
  7504. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  7505. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  7506. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  7507. }
  7508. _unregisterListeners() {
  7509. const {
  7510. hls
  7511. } = this;
  7512. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  7513. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  7514. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  7515. }
  7516. destroy() {
  7517. this._unregisterListeners();
  7518. // @ts-ignore
  7519. this.fragments =
  7520. // @ts-ignore
  7521. this.activePartLists =
  7522. // @ts-ignore
  7523. this.endListFragments = this.timeRanges = null;
  7524. }
  7525. /**
  7526. * Return a Fragment or Part with an appended range that matches the position and levelType
  7527. * Otherwise, return null
  7528. */
  7529. getAppendedFrag(position, levelType) {
  7530. const activeParts = this.activePartLists[levelType];
  7531. if (activeParts) {
  7532. for (let i = activeParts.length; i--;) {
  7533. const activePart = activeParts[i];
  7534. if (!activePart) {
  7535. break;
  7536. }
  7537. const appendedPTS = activePart.end;
  7538. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  7539. return activePart;
  7540. }
  7541. }
  7542. }
  7543. return this.getBufferedFrag(position, levelType);
  7544. }
  7545. /**
  7546. * Return a buffered Fragment that matches the position and levelType.
  7547. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  7548. * If not found any Fragment, return null
  7549. */
  7550. getBufferedFrag(position, levelType) {
  7551. const {
  7552. fragments
  7553. } = this;
  7554. const keys = Object.keys(fragments);
  7555. for (let i = keys.length; i--;) {
  7556. const fragmentEntity = fragments[keys[i]];
  7557. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  7558. const frag = fragmentEntity.body;
  7559. if (frag.start <= position && position <= frag.end) {
  7560. return frag;
  7561. }
  7562. }
  7563. }
  7564. return null;
  7565. }
  7566. /**
  7567. * Partial fragments effected by coded frame eviction will be removed
  7568. * The browser will unload parts of the buffer to free up memory for new buffer data
  7569. * 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)
  7570. */
  7571. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) {
  7572. if (this.timeRanges) {
  7573. this.timeRanges[elementaryStream] = timeRange;
  7574. }
  7575. // Check if any flagged fragments have been unloaded
  7576. // excluding anything newer than appendedPartSn
  7577. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  7578. Object.keys(this.fragments).forEach(key => {
  7579. const fragmentEntity = this.fragments[key];
  7580. if (!fragmentEntity) {
  7581. return;
  7582. }
  7583. if (appendedPartSn >= fragmentEntity.body.sn) {
  7584. return;
  7585. }
  7586. if (!fragmentEntity.buffered && !fragmentEntity.loaded) {
  7587. if (fragmentEntity.body.type === playlistType) {
  7588. this.removeFragment(fragmentEntity.body);
  7589. }
  7590. return;
  7591. }
  7592. const esData = fragmentEntity.range[elementaryStream];
  7593. if (!esData) {
  7594. return;
  7595. }
  7596. esData.time.some(time => {
  7597. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  7598. if (isNotBuffered) {
  7599. // Unregister partial fragment as it needs to load again to be reused
  7600. this.removeFragment(fragmentEntity.body);
  7601. }
  7602. return isNotBuffered;
  7603. });
  7604. });
  7605. }
  7606. /**
  7607. * Checks if the fragment passed in is loaded in the buffer properly
  7608. * Partially loaded fragments will be registered as a partial fragment
  7609. */
  7610. detectPartialFragments(data) {
  7611. const timeRanges = this.timeRanges;
  7612. const {
  7613. frag,
  7614. part
  7615. } = data;
  7616. if (!timeRanges || frag.sn === 'initSegment') {
  7617. return;
  7618. }
  7619. const fragKey = getFragmentKey(frag);
  7620. const fragmentEntity = this.fragments[fragKey];
  7621. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  7622. return;
  7623. }
  7624. const isFragHint = !frag.relurl;
  7625. Object.keys(timeRanges).forEach(elementaryStream => {
  7626. const streamInfo = frag.elementaryStreams[elementaryStream];
  7627. if (!streamInfo) {
  7628. return;
  7629. }
  7630. const timeRange = timeRanges[elementaryStream];
  7631. const partial = isFragHint || streamInfo.partial === true;
  7632. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, part, partial, timeRange);
  7633. });
  7634. fragmentEntity.loaded = null;
  7635. if (Object.keys(fragmentEntity.range).length) {
  7636. fragmentEntity.buffered = true;
  7637. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  7638. if (endList) {
  7639. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  7640. }
  7641. if (!isPartial(fragmentEntity)) {
  7642. // Remove older fragment parts from lookup after frag is tracked as buffered
  7643. this.removeParts(frag.sn - 1, frag.type);
  7644. }
  7645. } else {
  7646. // remove fragment if nothing was appended
  7647. this.removeFragment(fragmentEntity.body);
  7648. }
  7649. }
  7650. removeParts(snToKeep, levelType) {
  7651. const activeParts = this.activePartLists[levelType];
  7652. if (!activeParts) {
  7653. return;
  7654. }
  7655. this.activePartLists[levelType] = activeParts.filter(part => part.fragment.sn >= snToKeep);
  7656. }
  7657. fragBuffered(frag, force) {
  7658. const fragKey = getFragmentKey(frag);
  7659. let fragmentEntity = this.fragments[fragKey];
  7660. if (!fragmentEntity && force) {
  7661. fragmentEntity = this.fragments[fragKey] = {
  7662. body: frag,
  7663. appendedPTS: null,
  7664. loaded: null,
  7665. buffered: false,
  7666. range: Object.create(null)
  7667. };
  7668. if (frag.gap) {
  7669. this.hasGaps = true;
  7670. }
  7671. }
  7672. if (fragmentEntity) {
  7673. fragmentEntity.loaded = null;
  7674. fragmentEntity.buffered = true;
  7675. }
  7676. }
  7677. getBufferedTimes(fragment, part, partial, timeRange) {
  7678. const buffered = {
  7679. time: [],
  7680. partial
  7681. };
  7682. const startPTS = fragment.start;
  7683. const endPTS = fragment.end;
  7684. const minEndPTS = fragment.minEndPTS || endPTS;
  7685. const maxStartPTS = fragment.maxStartPTS || startPTS;
  7686. for (let i = 0; i < timeRange.length; i++) {
  7687. const startTime = timeRange.start(i) - this.bufferPadding;
  7688. const endTime = timeRange.end(i) + this.bufferPadding;
  7689. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  7690. // Fragment is entirely contained in buffer
  7691. // No need to check the other timeRange times since it's completely playable
  7692. buffered.time.push({
  7693. startPTS: Math.max(startPTS, timeRange.start(i)),
  7694. endPTS: Math.min(endPTS, timeRange.end(i))
  7695. });
  7696. break;
  7697. } else if (startPTS < endTime && endPTS > startTime) {
  7698. const start = Math.max(startPTS, timeRange.start(i));
  7699. const end = Math.min(endPTS, timeRange.end(i));
  7700. if (end > start) {
  7701. buffered.partial = true;
  7702. // Check for intersection with buffer
  7703. // Get playable sections of the fragment
  7704. buffered.time.push({
  7705. startPTS: start,
  7706. endPTS: end
  7707. });
  7708. }
  7709. } else if (endPTS <= startTime) {
  7710. // No need to check the rest of the timeRange as it is in order
  7711. break;
  7712. }
  7713. }
  7714. return buffered;
  7715. }
  7716. /**
  7717. * Gets the partial fragment for a certain time
  7718. */
  7719. getPartialFragment(time) {
  7720. let bestFragment = null;
  7721. let timePadding;
  7722. let startTime;
  7723. let endTime;
  7724. let bestOverlap = 0;
  7725. const {
  7726. bufferPadding,
  7727. fragments
  7728. } = this;
  7729. Object.keys(fragments).forEach(key => {
  7730. const fragmentEntity = fragments[key];
  7731. if (!fragmentEntity) {
  7732. return;
  7733. }
  7734. if (isPartial(fragmentEntity)) {
  7735. startTime = fragmentEntity.body.start - bufferPadding;
  7736. endTime = fragmentEntity.body.end + bufferPadding;
  7737. if (time >= startTime && time <= endTime) {
  7738. // Use the fragment that has the most padding from start and end time
  7739. timePadding = Math.min(time - startTime, endTime - time);
  7740. if (bestOverlap <= timePadding) {
  7741. bestFragment = fragmentEntity.body;
  7742. bestOverlap = timePadding;
  7743. }
  7744. }
  7745. }
  7746. });
  7747. return bestFragment;
  7748. }
  7749. isEndListAppended(type) {
  7750. const lastFragmentEntity = this.endListFragments[type];
  7751. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  7752. }
  7753. getState(fragment) {
  7754. const fragKey = getFragmentKey(fragment);
  7755. const fragmentEntity = this.fragments[fragKey];
  7756. if (fragmentEntity) {
  7757. if (!fragmentEntity.buffered) {
  7758. return FragmentState.APPENDING;
  7759. } else if (isPartial(fragmentEntity)) {
  7760. return FragmentState.PARTIAL;
  7761. } else {
  7762. return FragmentState.OK;
  7763. }
  7764. }
  7765. return FragmentState.NOT_LOADED;
  7766. }
  7767. isTimeBuffered(startPTS, endPTS, timeRange) {
  7768. let startTime;
  7769. let endTime;
  7770. for (let i = 0; i < timeRange.length; i++) {
  7771. startTime = timeRange.start(i) - this.bufferPadding;
  7772. endTime = timeRange.end(i) + this.bufferPadding;
  7773. if (startPTS >= startTime && endPTS <= endTime) {
  7774. return true;
  7775. }
  7776. if (endPTS <= startTime) {
  7777. // No need to check the rest of the timeRange as it is in order
  7778. return false;
  7779. }
  7780. }
  7781. return false;
  7782. }
  7783. onFragLoaded(event, data) {
  7784. const {
  7785. frag,
  7786. part
  7787. } = data;
  7788. // don't track initsegment (for which sn is not a number)
  7789. // don't track frags used for bitrateTest, they're irrelevant.
  7790. if (frag.sn === 'initSegment' || frag.bitrateTest) {
  7791. return;
  7792. }
  7793. // Fragment entity `loaded` FragLoadedData is null when loading parts
  7794. const loaded = part ? null : data;
  7795. const fragKey = getFragmentKey(frag);
  7796. this.fragments[fragKey] = {
  7797. body: frag,
  7798. appendedPTS: null,
  7799. loaded,
  7800. buffered: false,
  7801. range: Object.create(null)
  7802. };
  7803. }
  7804. onBufferAppended(event, data) {
  7805. const {
  7806. frag,
  7807. part,
  7808. timeRanges
  7809. } = data;
  7810. if (frag.sn === 'initSegment') {
  7811. return;
  7812. }
  7813. const playlistType = frag.type;
  7814. if (part) {
  7815. let activeParts = this.activePartLists[playlistType];
  7816. if (!activeParts) {
  7817. this.activePartLists[playlistType] = activeParts = [];
  7818. }
  7819. activeParts.push(part);
  7820. }
  7821. // Store the latest timeRanges loaded in the buffer
  7822. this.timeRanges = timeRanges;
  7823. Object.keys(timeRanges).forEach(elementaryStream => {
  7824. const timeRange = timeRanges[elementaryStream];
  7825. this.detectEvictedFragments(elementaryStream, timeRange, playlistType, part);
  7826. });
  7827. }
  7828. onFragBuffered(event, data) {
  7829. this.detectPartialFragments(data);
  7830. }
  7831. hasFragment(fragment) {
  7832. const fragKey = getFragmentKey(fragment);
  7833. return !!this.fragments[fragKey];
  7834. }
  7835. hasParts(type) {
  7836. var _this$activePartLists;
  7837. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  7838. }
  7839. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  7840. if (withGapOnly && !this.hasGaps) {
  7841. return;
  7842. }
  7843. Object.keys(this.fragments).forEach(key => {
  7844. const fragmentEntity = this.fragments[key];
  7845. if (!fragmentEntity) {
  7846. return;
  7847. }
  7848. const frag = fragmentEntity.body;
  7849. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  7850. return;
  7851. }
  7852. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  7853. this.removeFragment(frag);
  7854. }
  7855. });
  7856. }
  7857. removeFragment(fragment) {
  7858. const fragKey = getFragmentKey(fragment);
  7859. fragment.stats.loaded = 0;
  7860. fragment.clearElementaryStreamInfo();
  7861. const activeParts = this.activePartLists[fragment.type];
  7862. if (activeParts) {
  7863. const snToRemove = fragment.sn;
  7864. this.activePartLists[fragment.type] = activeParts.filter(part => part.fragment.sn !== snToRemove);
  7865. }
  7866. delete this.fragments[fragKey];
  7867. if (fragment.endList) {
  7868. delete this.endListFragments[fragment.type];
  7869. }
  7870. }
  7871. removeAllFragments() {
  7872. this.fragments = Object.create(null);
  7873. this.endListFragments = Object.create(null);
  7874. this.activePartLists = Object.create(null);
  7875. this.hasGaps = false;
  7876. }
  7877. }
  7878. function isPartial(fragmentEntity) {
  7879. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  7880. 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));
  7881. }
  7882. function getFragmentKey(fragment) {
  7883. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  7884. }
  7885. /**
  7886. * Provides methods dealing with buffer length retrieval for example.
  7887. *
  7888. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  7889. *
  7890. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  7891. */
  7892. const noopBuffered = {
  7893. length: 0,
  7894. start: () => 0,
  7895. end: () => 0
  7896. };
  7897. class BufferHelper {
  7898. /**
  7899. * Return true if `media`'s buffered include `position`
  7900. */
  7901. static isBuffered(media, position) {
  7902. try {
  7903. if (media) {
  7904. const buffered = BufferHelper.getBuffered(media);
  7905. for (let i = 0; i < buffered.length; i++) {
  7906. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  7907. return true;
  7908. }
  7909. }
  7910. }
  7911. } catch (error) {
  7912. // this is to catch
  7913. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7914. // This SourceBuffer has been removed from the parent media source
  7915. }
  7916. return false;
  7917. }
  7918. static bufferInfo(media, pos, maxHoleDuration) {
  7919. try {
  7920. if (media) {
  7921. const vbuffered = BufferHelper.getBuffered(media);
  7922. const buffered = [];
  7923. let i;
  7924. for (i = 0; i < vbuffered.length; i++) {
  7925. buffered.push({
  7926. start: vbuffered.start(i),
  7927. end: vbuffered.end(i)
  7928. });
  7929. }
  7930. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  7931. }
  7932. } catch (error) {
  7933. // this is to catch
  7934. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7935. // This SourceBuffer has been removed from the parent media source
  7936. }
  7937. return {
  7938. len: 0,
  7939. start: pos,
  7940. end: pos,
  7941. nextStart: undefined
  7942. };
  7943. }
  7944. static bufferedInfo(buffered, pos, maxHoleDuration) {
  7945. pos = Math.max(0, pos);
  7946. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  7947. buffered.sort(function (a, b) {
  7948. const diff = a.start - b.start;
  7949. if (diff) {
  7950. return diff;
  7951. } else {
  7952. return b.end - a.end;
  7953. }
  7954. });
  7955. let buffered2 = [];
  7956. if (maxHoleDuration) {
  7957. // there might be some small holes between buffer time range
  7958. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  7959. // buffer time range representations that discards those holes
  7960. for (let i = 0; i < buffered.length; i++) {
  7961. const buf2len = buffered2.length;
  7962. if (buf2len) {
  7963. const buf2end = buffered2[buf2len - 1].end;
  7964. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  7965. if (buffered[i].start - buf2end < maxHoleDuration) {
  7966. // merge overlapping time ranges
  7967. // update lastRange.end only if smaller than item.end
  7968. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  7969. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  7970. if (buffered[i].end > buf2end) {
  7971. buffered2[buf2len - 1].end = buffered[i].end;
  7972. }
  7973. } else {
  7974. // big hole
  7975. buffered2.push(buffered[i]);
  7976. }
  7977. } else {
  7978. // first value
  7979. buffered2.push(buffered[i]);
  7980. }
  7981. }
  7982. } else {
  7983. buffered2 = buffered;
  7984. }
  7985. let bufferLen = 0;
  7986. // bufferStartNext can possibly be undefined based on the conditional logic below
  7987. let bufferStartNext;
  7988. // bufferStart and bufferEnd are buffer boundaries around current video position
  7989. let bufferStart = pos;
  7990. let bufferEnd = pos;
  7991. for (let i = 0; i < buffered2.length; i++) {
  7992. const start = buffered2[i].start;
  7993. const end = buffered2[i].end;
  7994. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  7995. if (pos + maxHoleDuration >= start && pos < end) {
  7996. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7997. bufferStart = start;
  7998. bufferEnd = end;
  7999. bufferLen = bufferEnd - pos;
  8000. } else if (pos + maxHoleDuration < start) {
  8001. bufferStartNext = start;
  8002. break;
  8003. }
  8004. }
  8005. return {
  8006. len: bufferLen,
  8007. start: bufferStart || 0,
  8008. end: bufferEnd || 0,
  8009. nextStart: bufferStartNext
  8010. };
  8011. }
  8012. /**
  8013. * Safe method to get buffered property.
  8014. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  8015. */
  8016. static getBuffered(media) {
  8017. try {
  8018. return media.buffered;
  8019. } catch (e) {
  8020. logger.log('failed to get media.buffered', e);
  8021. return noopBuffered;
  8022. }
  8023. }
  8024. }
  8025. class ChunkMetadata {
  8026. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  8027. this.level = void 0;
  8028. this.sn = void 0;
  8029. this.part = void 0;
  8030. this.id = void 0;
  8031. this.size = void 0;
  8032. this.partial = void 0;
  8033. this.transmuxing = getNewPerformanceTiming();
  8034. this.buffering = {
  8035. audio: getNewPerformanceTiming(),
  8036. video: getNewPerformanceTiming(),
  8037. audiovideo: getNewPerformanceTiming()
  8038. };
  8039. this.level = level;
  8040. this.sn = sn;
  8041. this.id = id;
  8042. this.size = size;
  8043. this.part = part;
  8044. this.partial = partial;
  8045. }
  8046. }
  8047. function getNewPerformanceTiming() {
  8048. return {
  8049. start: 0,
  8050. executeStart: 0,
  8051. executeEnd: 0,
  8052. end: 0
  8053. };
  8054. }
  8055. function findFirstFragWithCC(fragments, cc) {
  8056. for (let i = 0, len = fragments.length; i < len; i++) {
  8057. var _fragments$i;
  8058. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  8059. return fragments[i];
  8060. }
  8061. }
  8062. return null;
  8063. }
  8064. function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) {
  8065. if (switchDetails) {
  8066. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  8067. return true;
  8068. }
  8069. }
  8070. return false;
  8071. }
  8072. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  8073. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  8074. const prevFrags = prevDetails.fragments;
  8075. const curFrags = curDetails.fragments;
  8076. if (!curFrags.length || !prevFrags.length) {
  8077. logger.log('No fragments to align');
  8078. return;
  8079. }
  8080. const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  8081. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  8082. logger.log('No frag in previous level to align on');
  8083. return;
  8084. }
  8085. return prevStartFrag;
  8086. }
  8087. function adjustFragmentStart(frag, sliding) {
  8088. if (frag) {
  8089. const start = frag.start + sliding;
  8090. frag.start = frag.startPTS = start;
  8091. frag.endPTS = start + frag.duration;
  8092. }
  8093. }
  8094. function adjustSlidingStart(sliding, details) {
  8095. // Update segments
  8096. const fragments = details.fragments;
  8097. for (let i = 0, len = fragments.length; i < len; i++) {
  8098. adjustFragmentStart(fragments[i], sliding);
  8099. }
  8100. // Update LL-HLS parts at the end of the playlist
  8101. if (details.fragmentHint) {
  8102. adjustFragmentStart(details.fragmentHint, sliding);
  8103. }
  8104. details.alignedSliding = true;
  8105. }
  8106. /**
  8107. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  8108. * contiguous stream with the last fragments.
  8109. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  8110. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  8111. * and an extra download.
  8112. * @param lastFrag
  8113. * @param lastLevel
  8114. * @param details
  8115. */
  8116. function alignStream(lastFrag, switchDetails, details) {
  8117. if (!switchDetails) {
  8118. return;
  8119. }
  8120. alignDiscontinuities(lastFrag, details, switchDetails);
  8121. if (!details.alignedSliding && switchDetails) {
  8122. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  8123. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  8124. // discontinuity sequence.
  8125. alignMediaPlaylistByPDT(details, switchDetails);
  8126. }
  8127. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  8128. // Try to align on sn so that we pick a better start fragment.
  8129. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  8130. // and adjustSliding only adjusts fragments after skippedSegments.
  8131. adjustSliding(switchDetails, details);
  8132. }
  8133. }
  8134. /**
  8135. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  8136. * discontinuity sequence.
  8137. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  8138. * @param lastLevel - The details of the last loaded level
  8139. * @param details - The details of the new level
  8140. */
  8141. function alignDiscontinuities(lastFrag, details, switchDetails) {
  8142. if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {
  8143. const referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details);
  8144. if (referenceFrag && isFiniteNumber(referenceFrag.start)) {
  8145. logger.log(`Adjusting PTS using last level due to CC increase within current level ${details.url}`);
  8146. adjustSlidingStart(referenceFrag.start, details);
  8147. }
  8148. }
  8149. }
  8150. /**
  8151. * Ensures appropriate time-alignment between renditions based on PDT.
  8152. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  8153. * for the last discontinuity sequence number shared by both playlists when present,
  8154. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  8155. * times/timelines of `details` accordingly.
  8156. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  8157. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  8158. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  8159. * be consistent across playlists, per the HLS spec.
  8160. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  8161. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  8162. */
  8163. function alignMediaPlaylistByPDT(details, refDetails) {
  8164. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  8165. return;
  8166. }
  8167. const fragments = details.fragments;
  8168. const refFragments = refDetails.fragments;
  8169. if (!fragments.length || !refFragments.length) {
  8170. return;
  8171. }
  8172. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  8173. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  8174. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  8175. let refFrag;
  8176. let frag;
  8177. const targetCC = Math.min(refDetails.endCC, details.endCC);
  8178. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  8179. refFrag = findFirstFragWithCC(refFragments, targetCC);
  8180. frag = findFirstFragWithCC(fragments, targetCC);
  8181. }
  8182. if (!refFrag || !frag) {
  8183. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  8184. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  8185. }
  8186. const refPDT = refFrag.programDateTime;
  8187. const targetPDT = frag.programDateTime;
  8188. if (!refPDT || !targetPDT) {
  8189. return;
  8190. }
  8191. const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  8192. adjustSlidingStart(delta, details);
  8193. }
  8194. const MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  8195. class FragmentLoader {
  8196. constructor(config) {
  8197. this.config = void 0;
  8198. this.loader = null;
  8199. this.partLoadTimeout = -1;
  8200. this.config = config;
  8201. }
  8202. destroy() {
  8203. if (this.loader) {
  8204. this.loader.destroy();
  8205. this.loader = null;
  8206. }
  8207. }
  8208. abort() {
  8209. if (this.loader) {
  8210. // Abort the loader for current fragment. Only one may load at any given time
  8211. this.loader.abort();
  8212. }
  8213. }
  8214. load(frag, onProgress) {
  8215. const url = frag.url;
  8216. if (!url) {
  8217. return Promise.reject(new LoadError({
  8218. type: ErrorTypes.NETWORK_ERROR,
  8219. details: ErrorDetails.FRAG_LOAD_ERROR,
  8220. fatal: false,
  8221. frag,
  8222. error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),
  8223. networkDetails: null
  8224. }));
  8225. }
  8226. this.abort();
  8227. const config = this.config;
  8228. const FragmentILoader = config.fLoader;
  8229. const DefaultILoader = config.loader;
  8230. return new Promise((resolve, reject) => {
  8231. if (this.loader) {
  8232. this.loader.destroy();
  8233. }
  8234. if (frag.gap) {
  8235. if (frag.tagList.some(tags => tags[0] === 'GAP')) {
  8236. reject(createGapLoadError(frag));
  8237. return;
  8238. } else {
  8239. // Reset temporary treatment as GAP tag
  8240. frag.gap = false;
  8241. }
  8242. }
  8243. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  8244. const loaderContext = createLoaderContext(frag);
  8245. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  8246. const loaderConfig = {
  8247. loadPolicy,
  8248. timeout: loadPolicy.maxLoadTimeMs,
  8249. maxRetry: 0,
  8250. retryDelay: 0,
  8251. maxRetryDelay: 0,
  8252. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  8253. };
  8254. // Assign frag stats to the loader's stats reference
  8255. frag.stats = loader.stats;
  8256. loader.load(loaderContext, loaderConfig, {
  8257. onSuccess: (response, stats, context, networkDetails) => {
  8258. this.resetLoader(frag, loader);
  8259. let payload = response.data;
  8260. if (context.resetIV && frag.decryptdata) {
  8261. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  8262. payload = payload.slice(16);
  8263. }
  8264. resolve({
  8265. frag,
  8266. part: null,
  8267. payload,
  8268. networkDetails
  8269. });
  8270. },
  8271. onError: (response, context, networkDetails, stats) => {
  8272. this.resetLoader(frag, loader);
  8273. reject(new LoadError({
  8274. type: ErrorTypes.NETWORK_ERROR,
  8275. details: ErrorDetails.FRAG_LOAD_ERROR,
  8276. fatal: false,
  8277. frag,
  8278. response: _objectSpread2({
  8279. url,
  8280. data: undefined
  8281. }, response),
  8282. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  8283. networkDetails,
  8284. stats
  8285. }));
  8286. },
  8287. onAbort: (stats, context, networkDetails) => {
  8288. this.resetLoader(frag, loader);
  8289. reject(new LoadError({
  8290. type: ErrorTypes.NETWORK_ERROR,
  8291. details: ErrorDetails.INTERNAL_ABORTED,
  8292. fatal: false,
  8293. frag,
  8294. error: new Error('Aborted'),
  8295. networkDetails,
  8296. stats
  8297. }));
  8298. },
  8299. onTimeout: (stats, context, networkDetails) => {
  8300. this.resetLoader(frag, loader);
  8301. reject(new LoadError({
  8302. type: ErrorTypes.NETWORK_ERROR,
  8303. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  8304. fatal: false,
  8305. frag,
  8306. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  8307. networkDetails,
  8308. stats
  8309. }));
  8310. },
  8311. onProgress: (stats, context, data, networkDetails) => {
  8312. if (onProgress) {
  8313. onProgress({
  8314. frag,
  8315. part: null,
  8316. payload: data,
  8317. networkDetails
  8318. });
  8319. }
  8320. }
  8321. });
  8322. });
  8323. }
  8324. loadPart(frag, part, onProgress) {
  8325. this.abort();
  8326. const config = this.config;
  8327. const FragmentILoader = config.fLoader;
  8328. const DefaultILoader = config.loader;
  8329. return new Promise((resolve, reject) => {
  8330. if (this.loader) {
  8331. this.loader.destroy();
  8332. }
  8333. if (frag.gap || part.gap) {
  8334. reject(createGapLoadError(frag, part));
  8335. return;
  8336. }
  8337. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  8338. const loaderContext = createLoaderContext(frag, part);
  8339. // Should we define another load policy for parts?
  8340. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  8341. const loaderConfig = {
  8342. loadPolicy,
  8343. timeout: loadPolicy.maxLoadTimeMs,
  8344. maxRetry: 0,
  8345. retryDelay: 0,
  8346. maxRetryDelay: 0,
  8347. highWaterMark: MIN_CHUNK_SIZE
  8348. };
  8349. // Assign part stats to the loader's stats reference
  8350. part.stats = loader.stats;
  8351. loader.load(loaderContext, loaderConfig, {
  8352. onSuccess: (response, stats, context, networkDetails) => {
  8353. this.resetLoader(frag, loader);
  8354. this.updateStatsFromPart(frag, part);
  8355. const partLoadedData = {
  8356. frag,
  8357. part,
  8358. payload: response.data,
  8359. networkDetails
  8360. };
  8361. onProgress(partLoadedData);
  8362. resolve(partLoadedData);
  8363. },
  8364. onError: (response, context, networkDetails, stats) => {
  8365. this.resetLoader(frag, loader);
  8366. reject(new LoadError({
  8367. type: ErrorTypes.NETWORK_ERROR,
  8368. details: ErrorDetails.FRAG_LOAD_ERROR,
  8369. fatal: false,
  8370. frag,
  8371. part,
  8372. response: _objectSpread2({
  8373. url: loaderContext.url,
  8374. data: undefined
  8375. }, response),
  8376. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  8377. networkDetails,
  8378. stats
  8379. }));
  8380. },
  8381. onAbort: (stats, context, networkDetails) => {
  8382. frag.stats.aborted = part.stats.aborted;
  8383. this.resetLoader(frag, loader);
  8384. reject(new LoadError({
  8385. type: ErrorTypes.NETWORK_ERROR,
  8386. details: ErrorDetails.INTERNAL_ABORTED,
  8387. fatal: false,
  8388. frag,
  8389. part,
  8390. error: new Error('Aborted'),
  8391. networkDetails,
  8392. stats
  8393. }));
  8394. },
  8395. onTimeout: (stats, context, networkDetails) => {
  8396. this.resetLoader(frag, loader);
  8397. reject(new LoadError({
  8398. type: ErrorTypes.NETWORK_ERROR,
  8399. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  8400. fatal: false,
  8401. frag,
  8402. part,
  8403. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  8404. networkDetails,
  8405. stats
  8406. }));
  8407. }
  8408. });
  8409. });
  8410. }
  8411. updateStatsFromPart(frag, part) {
  8412. const fragStats = frag.stats;
  8413. const partStats = part.stats;
  8414. const partTotal = partStats.total;
  8415. fragStats.loaded += partStats.loaded;
  8416. if (partTotal) {
  8417. const estTotalParts = Math.round(frag.duration / part.duration);
  8418. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  8419. const estRemainingParts = estTotalParts - estLoadedParts;
  8420. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  8421. fragStats.total = fragStats.loaded + estRemainingBytes;
  8422. } else {
  8423. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  8424. }
  8425. const fragLoading = fragStats.loading;
  8426. const partLoading = partStats.loading;
  8427. if (fragLoading.start) {
  8428. // add to fragment loader latency
  8429. fragLoading.first += partLoading.first - partLoading.start;
  8430. } else {
  8431. fragLoading.start = partLoading.start;
  8432. fragLoading.first = partLoading.first;
  8433. }
  8434. fragLoading.end = partLoading.end;
  8435. }
  8436. resetLoader(frag, loader) {
  8437. frag.loader = null;
  8438. if (this.loader === loader) {
  8439. self.clearTimeout(this.partLoadTimeout);
  8440. this.loader = null;
  8441. }
  8442. loader.destroy();
  8443. }
  8444. }
  8445. function createLoaderContext(frag, part = null) {
  8446. const segment = part || frag;
  8447. const loaderContext = {
  8448. frag,
  8449. part,
  8450. responseType: 'arraybuffer',
  8451. url: segment.url,
  8452. headers: {},
  8453. rangeStart: 0,
  8454. rangeEnd: 0
  8455. };
  8456. const start = segment.byteRangeStartOffset;
  8457. const end = segment.byteRangeEndOffset;
  8458. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  8459. var _frag$decryptdata;
  8460. let byteRangeStart = start;
  8461. let byteRangeEnd = end;
  8462. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  8463. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  8464. // has the unencrypted size specified in the range.
  8465. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  8466. const fragmentLen = end - start;
  8467. if (fragmentLen % 16) {
  8468. byteRangeEnd = end + (16 - fragmentLen % 16);
  8469. }
  8470. if (start !== 0) {
  8471. loaderContext.resetIV = true;
  8472. byteRangeStart = start - 16;
  8473. }
  8474. }
  8475. loaderContext.rangeStart = byteRangeStart;
  8476. loaderContext.rangeEnd = byteRangeEnd;
  8477. }
  8478. return loaderContext;
  8479. }
  8480. function createGapLoadError(frag, part) {
  8481. const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);
  8482. const errorData = {
  8483. type: ErrorTypes.MEDIA_ERROR,
  8484. details: ErrorDetails.FRAG_GAP,
  8485. fatal: false,
  8486. frag,
  8487. error,
  8488. networkDetails: null
  8489. };
  8490. if (part) {
  8491. errorData.part = part;
  8492. }
  8493. (part ? part : frag).stats.aborted = true;
  8494. return new LoadError(errorData);
  8495. }
  8496. class LoadError extends Error {
  8497. constructor(data) {
  8498. super(data.error.message);
  8499. this.data = void 0;
  8500. this.data = data;
  8501. }
  8502. }
  8503. class AESCrypto {
  8504. constructor(subtle, iv) {
  8505. this.subtle = void 0;
  8506. this.aesIV = void 0;
  8507. this.subtle = subtle;
  8508. this.aesIV = iv;
  8509. }
  8510. decrypt(data, key) {
  8511. return this.subtle.decrypt({
  8512. name: 'AES-CBC',
  8513. iv: this.aesIV
  8514. }, key, data);
  8515. }
  8516. }
  8517. class FastAESKey {
  8518. constructor(subtle, key) {
  8519. this.subtle = void 0;
  8520. this.key = void 0;
  8521. this.subtle = subtle;
  8522. this.key = key;
  8523. }
  8524. expandKey() {
  8525. return this.subtle.importKey('raw', this.key, {
  8526. name: 'AES-CBC'
  8527. }, false, ['encrypt', 'decrypt']);
  8528. }
  8529. }
  8530. // PKCS7
  8531. function removePadding(array) {
  8532. const outputBytes = array.byteLength;
  8533. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  8534. if (paddingBytes) {
  8535. return sliceUint8(array, 0, outputBytes - paddingBytes);
  8536. }
  8537. return array;
  8538. }
  8539. class AESDecryptor {
  8540. constructor() {
  8541. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  8542. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8543. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8544. this.sBox = new Uint32Array(256);
  8545. this.invSBox = new Uint32Array(256);
  8546. this.key = new Uint32Array(0);
  8547. this.ksRows = 0;
  8548. this.keySize = 0;
  8549. this.keySchedule = void 0;
  8550. this.invKeySchedule = void 0;
  8551. this.initTable();
  8552. }
  8553. // Using view.getUint32() also swaps the byte order.
  8554. uint8ArrayToUint32Array_(arrayBuffer) {
  8555. const view = new DataView(arrayBuffer);
  8556. const newArray = new Uint32Array(4);
  8557. for (let i = 0; i < 4; i++) {
  8558. newArray[i] = view.getUint32(i * 4);
  8559. }
  8560. return newArray;
  8561. }
  8562. initTable() {
  8563. const sBox = this.sBox;
  8564. const invSBox = this.invSBox;
  8565. const subMix = this.subMix;
  8566. const subMix0 = subMix[0];
  8567. const subMix1 = subMix[1];
  8568. const subMix2 = subMix[2];
  8569. const subMix3 = subMix[3];
  8570. const invSubMix = this.invSubMix;
  8571. const invSubMix0 = invSubMix[0];
  8572. const invSubMix1 = invSubMix[1];
  8573. const invSubMix2 = invSubMix[2];
  8574. const invSubMix3 = invSubMix[3];
  8575. const d = new Uint32Array(256);
  8576. let x = 0;
  8577. let xi = 0;
  8578. let i = 0;
  8579. for (i = 0; i < 256; i++) {
  8580. if (i < 128) {
  8581. d[i] = i << 1;
  8582. } else {
  8583. d[i] = i << 1 ^ 0x11b;
  8584. }
  8585. }
  8586. for (i = 0; i < 256; i++) {
  8587. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  8588. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  8589. sBox[x] = sx;
  8590. invSBox[sx] = x;
  8591. // Compute multiplication
  8592. const x2 = d[x];
  8593. const x4 = d[x2];
  8594. const x8 = d[x4];
  8595. // Compute sub/invSub bytes, mix columns tables
  8596. let t = d[sx] * 0x101 ^ sx * 0x1010100;
  8597. subMix0[x] = t << 24 | t >>> 8;
  8598. subMix1[x] = t << 16 | t >>> 16;
  8599. subMix2[x] = t << 8 | t >>> 24;
  8600. subMix3[x] = t;
  8601. // Compute inv sub bytes, inv mix columns tables
  8602. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  8603. invSubMix0[sx] = t << 24 | t >>> 8;
  8604. invSubMix1[sx] = t << 16 | t >>> 16;
  8605. invSubMix2[sx] = t << 8 | t >>> 24;
  8606. invSubMix3[sx] = t;
  8607. // Compute next counter
  8608. if (!x) {
  8609. x = xi = 1;
  8610. } else {
  8611. x = x2 ^ d[d[d[x8 ^ x2]]];
  8612. xi ^= d[d[xi]];
  8613. }
  8614. }
  8615. }
  8616. expandKey(keyBuffer) {
  8617. // convert keyBuffer to Uint32Array
  8618. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  8619. let sameKey = true;
  8620. let offset = 0;
  8621. while (offset < key.length && sameKey) {
  8622. sameKey = key[offset] === this.key[offset];
  8623. offset++;
  8624. }
  8625. if (sameKey) {
  8626. return;
  8627. }
  8628. this.key = key;
  8629. const keySize = this.keySize = key.length;
  8630. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  8631. throw new Error('Invalid aes key size=' + keySize);
  8632. }
  8633. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  8634. let ksRow;
  8635. let invKsRow;
  8636. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  8637. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  8638. const sbox = this.sBox;
  8639. const rcon = this.rcon;
  8640. const invSubMix = this.invSubMix;
  8641. const invSubMix0 = invSubMix[0];
  8642. const invSubMix1 = invSubMix[1];
  8643. const invSubMix2 = invSubMix[2];
  8644. const invSubMix3 = invSubMix[3];
  8645. let prev;
  8646. let t;
  8647. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  8648. if (ksRow < keySize) {
  8649. prev = keySchedule[ksRow] = key[ksRow];
  8650. continue;
  8651. }
  8652. t = prev;
  8653. if (ksRow % keySize === 0) {
  8654. // Rot word
  8655. t = t << 8 | t >>> 24;
  8656. // Sub word
  8657. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8658. // Mix Rcon
  8659. t ^= rcon[ksRow / keySize | 0] << 24;
  8660. } else if (keySize > 6 && ksRow % keySize === 4) {
  8661. // Sub word
  8662. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8663. }
  8664. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  8665. }
  8666. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  8667. ksRow = ksRows - invKsRow;
  8668. if (invKsRow & 3) {
  8669. t = keySchedule[ksRow];
  8670. } else {
  8671. t = keySchedule[ksRow - 4];
  8672. }
  8673. if (invKsRow < 4 || ksRow <= 4) {
  8674. invKeySchedule[invKsRow] = t;
  8675. } else {
  8676. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  8677. }
  8678. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  8679. }
  8680. }
  8681. // Adding this as a method greatly improves performance.
  8682. networkToHostOrderSwap(word) {
  8683. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  8684. }
  8685. decrypt(inputArrayBuffer, offset, aesIV) {
  8686. const nRounds = this.keySize + 6;
  8687. const invKeySchedule = this.invKeySchedule;
  8688. const invSBOX = this.invSBox;
  8689. const invSubMix = this.invSubMix;
  8690. const invSubMix0 = invSubMix[0];
  8691. const invSubMix1 = invSubMix[1];
  8692. const invSubMix2 = invSubMix[2];
  8693. const invSubMix3 = invSubMix[3];
  8694. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  8695. let initVector0 = initVector[0];
  8696. let initVector1 = initVector[1];
  8697. let initVector2 = initVector[2];
  8698. let initVector3 = initVector[3];
  8699. const inputInt32 = new Int32Array(inputArrayBuffer);
  8700. const outputInt32 = new Int32Array(inputInt32.length);
  8701. let t0, t1, t2, t3;
  8702. let s0, s1, s2, s3;
  8703. let inputWords0, inputWords1, inputWords2, inputWords3;
  8704. let ksRow, i;
  8705. const swapWord = this.networkToHostOrderSwap;
  8706. while (offset < inputInt32.length) {
  8707. inputWords0 = swapWord(inputInt32[offset]);
  8708. inputWords1 = swapWord(inputInt32[offset + 1]);
  8709. inputWords2 = swapWord(inputInt32[offset + 2]);
  8710. inputWords3 = swapWord(inputInt32[offset + 3]);
  8711. s0 = inputWords0 ^ invKeySchedule[0];
  8712. s1 = inputWords3 ^ invKeySchedule[1];
  8713. s2 = inputWords2 ^ invKeySchedule[2];
  8714. s3 = inputWords1 ^ invKeySchedule[3];
  8715. ksRow = 4;
  8716. // Iterate through the rounds of decryption
  8717. for (i = 1; i < nRounds; i++) {
  8718. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  8719. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  8720. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  8721. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  8722. // Update state
  8723. s0 = t0;
  8724. s1 = t1;
  8725. s2 = t2;
  8726. s3 = t3;
  8727. ksRow = ksRow + 4;
  8728. }
  8729. // Shift rows, sub bytes, add round key
  8730. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  8731. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  8732. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  8733. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  8734. // Write
  8735. outputInt32[offset] = swapWord(t0 ^ initVector0);
  8736. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  8737. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  8738. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  8739. // reset initVector to last 4 unsigned int
  8740. initVector0 = inputWords0;
  8741. initVector1 = inputWords1;
  8742. initVector2 = inputWords2;
  8743. initVector3 = inputWords3;
  8744. offset = offset + 4;
  8745. }
  8746. return outputInt32.buffer;
  8747. }
  8748. }
  8749. const CHUNK_SIZE = 16; // 16 bytes, 128 bits
  8750. class Decrypter {
  8751. constructor(config, {
  8752. removePKCS7Padding = true
  8753. } = {}) {
  8754. this.logEnabled = true;
  8755. this.removePKCS7Padding = void 0;
  8756. this.subtle = null;
  8757. this.softwareDecrypter = null;
  8758. this.key = null;
  8759. this.fastAesKey = null;
  8760. this.remainderData = null;
  8761. this.currentIV = null;
  8762. this.currentResult = null;
  8763. this.useSoftware = void 0;
  8764. this.useSoftware = config.enableSoftwareAES;
  8765. this.removePKCS7Padding = removePKCS7Padding;
  8766. // built in decryptor expects PKCS7 padding
  8767. if (removePKCS7Padding) {
  8768. try {
  8769. const browserCrypto = self.crypto;
  8770. if (browserCrypto) {
  8771. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  8772. }
  8773. } catch (e) {
  8774. /* no-op */
  8775. }
  8776. }
  8777. this.useSoftware = !this.subtle;
  8778. }
  8779. destroy() {
  8780. this.subtle = null;
  8781. this.softwareDecrypter = null;
  8782. this.key = null;
  8783. this.fastAesKey = null;
  8784. this.remainderData = null;
  8785. this.currentIV = null;
  8786. this.currentResult = null;
  8787. }
  8788. isSync() {
  8789. return this.useSoftware;
  8790. }
  8791. flush() {
  8792. const {
  8793. currentResult,
  8794. remainderData
  8795. } = this;
  8796. if (!currentResult || remainderData) {
  8797. this.reset();
  8798. return null;
  8799. }
  8800. const data = new Uint8Array(currentResult);
  8801. this.reset();
  8802. if (this.removePKCS7Padding) {
  8803. return removePadding(data);
  8804. }
  8805. return data;
  8806. }
  8807. reset() {
  8808. this.currentResult = null;
  8809. this.currentIV = null;
  8810. this.remainderData = null;
  8811. if (this.softwareDecrypter) {
  8812. this.softwareDecrypter = null;
  8813. }
  8814. }
  8815. decrypt(data, key, iv) {
  8816. if (this.useSoftware) {
  8817. return new Promise((resolve, reject) => {
  8818. this.softwareDecrypt(new Uint8Array(data), key, iv);
  8819. const decryptResult = this.flush();
  8820. if (decryptResult) {
  8821. resolve(decryptResult.buffer);
  8822. } else {
  8823. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  8824. }
  8825. });
  8826. }
  8827. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  8828. }
  8829. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  8830. // data is handled in the flush() call
  8831. softwareDecrypt(data, key, iv) {
  8832. const {
  8833. currentIV,
  8834. currentResult,
  8835. remainderData
  8836. } = this;
  8837. this.logOnce('JS AES decrypt');
  8838. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  8839. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  8840. // the end on flush(), but by that time we have already received all bytes for the segment.
  8841. // Progressive decryption does not work with WebCrypto
  8842. if (remainderData) {
  8843. data = appendUint8Array(remainderData, data);
  8844. this.remainderData = null;
  8845. }
  8846. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  8847. const currentChunk = this.getValidChunk(data);
  8848. if (!currentChunk.length) {
  8849. return null;
  8850. }
  8851. if (currentIV) {
  8852. iv = currentIV;
  8853. }
  8854. let softwareDecrypter = this.softwareDecrypter;
  8855. if (!softwareDecrypter) {
  8856. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  8857. }
  8858. softwareDecrypter.expandKey(key);
  8859. const result = currentResult;
  8860. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  8861. this.currentIV = sliceUint8(currentChunk, -16).buffer;
  8862. if (!result) {
  8863. return null;
  8864. }
  8865. return result;
  8866. }
  8867. webCryptoDecrypt(data, key, iv) {
  8868. if (this.key !== key || !this.fastAesKey) {
  8869. if (!this.subtle) {
  8870. return Promise.resolve(this.onWebCryptoError(data, key, iv));
  8871. }
  8872. this.key = key;
  8873. this.fastAesKey = new FastAESKey(this.subtle, key);
  8874. }
  8875. return this.fastAesKey.expandKey().then(aesKey => {
  8876. // decrypt using web crypto
  8877. if (!this.subtle) {
  8878. return Promise.reject(new Error('web crypto not initialized'));
  8879. }
  8880. this.logOnce('WebCrypto AES decrypt');
  8881. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv));
  8882. return crypto.decrypt(data.buffer, aesKey);
  8883. }).catch(err => {
  8884. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  8885. return this.onWebCryptoError(data, key, iv);
  8886. });
  8887. }
  8888. onWebCryptoError(data, key, iv) {
  8889. this.useSoftware = true;
  8890. this.logEnabled = true;
  8891. this.softwareDecrypt(data, key, iv);
  8892. const decryptResult = this.flush();
  8893. if (decryptResult) {
  8894. return decryptResult.buffer;
  8895. }
  8896. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  8897. }
  8898. getValidChunk(data) {
  8899. let currentChunk = data;
  8900. const splitPoint = data.length - data.length % CHUNK_SIZE;
  8901. if (splitPoint !== data.length) {
  8902. currentChunk = sliceUint8(data, 0, splitPoint);
  8903. this.remainderData = sliceUint8(data, splitPoint);
  8904. }
  8905. return currentChunk;
  8906. }
  8907. logOnce(msg) {
  8908. if (!this.logEnabled) {
  8909. return;
  8910. }
  8911. logger.log(`[decrypter]: ${msg}`);
  8912. this.logEnabled = false;
  8913. }
  8914. }
  8915. /**
  8916. * TimeRanges to string helper
  8917. */
  8918. const TimeRanges = {
  8919. toString: function (r) {
  8920. let log = '';
  8921. const len = r.length;
  8922. for (let i = 0; i < len; i++) {
  8923. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  8924. }
  8925. return log;
  8926. }
  8927. };
  8928. const State = {
  8929. STOPPED: 'STOPPED',
  8930. IDLE: 'IDLE',
  8931. KEY_LOADING: 'KEY_LOADING',
  8932. FRAG_LOADING: 'FRAG_LOADING',
  8933. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  8934. WAITING_TRACK: 'WAITING_TRACK',
  8935. PARSING: 'PARSING',
  8936. PARSED: 'PARSED',
  8937. ENDED: 'ENDED',
  8938. ERROR: 'ERROR',
  8939. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  8940. WAITING_LEVEL: 'WAITING_LEVEL'
  8941. };
  8942. class BaseStreamController extends TaskLoop {
  8943. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  8944. super();
  8945. this.hls = void 0;
  8946. this.fragPrevious = null;
  8947. this.fragCurrent = null;
  8948. this.fragmentTracker = void 0;
  8949. this.transmuxer = null;
  8950. this._state = State.STOPPED;
  8951. this.playlistType = void 0;
  8952. this.media = null;
  8953. this.mediaBuffer = null;
  8954. this.config = void 0;
  8955. this.bitrateTest = false;
  8956. this.lastCurrentTime = 0;
  8957. this.nextLoadPosition = 0;
  8958. this.startPosition = 0;
  8959. this.startTimeOffset = null;
  8960. this.loadedmetadata = false;
  8961. this.retryDate = 0;
  8962. this.levels = null;
  8963. this.fragmentLoader = void 0;
  8964. this.keyLoader = void 0;
  8965. this.levelLastLoaded = null;
  8966. this.startFragRequested = false;
  8967. this.decrypter = void 0;
  8968. this.initPTS = [];
  8969. this.onvseeking = null;
  8970. this.onvended = null;
  8971. this.logPrefix = '';
  8972. this.log = void 0;
  8973. this.warn = void 0;
  8974. this.playlistType = playlistType;
  8975. this.logPrefix = logPrefix;
  8976. this.log = logger.log.bind(logger, `${logPrefix}:`);
  8977. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  8978. this.hls = hls;
  8979. this.fragmentLoader = new FragmentLoader(hls.config);
  8980. this.keyLoader = keyLoader;
  8981. this.fragmentTracker = fragmentTracker;
  8982. this.config = hls.config;
  8983. this.decrypter = new Decrypter(hls.config);
  8984. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8985. }
  8986. doTick() {
  8987. this.onTickEnd();
  8988. }
  8989. onTickEnd() {}
  8990. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  8991. startLoad(startPosition) {}
  8992. stopLoad() {
  8993. this.fragmentLoader.abort();
  8994. this.keyLoader.abort(this.playlistType);
  8995. const frag = this.fragCurrent;
  8996. if (frag != null && frag.loader) {
  8997. frag.abortRequests();
  8998. this.fragmentTracker.removeFragment(frag);
  8999. }
  9000. this.resetTransmuxer();
  9001. this.fragCurrent = null;
  9002. this.fragPrevious = null;
  9003. this.clearInterval();
  9004. this.clearNextTick();
  9005. this.state = State.STOPPED;
  9006. }
  9007. _streamEnded(bufferInfo, levelDetails) {
  9008. // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,
  9009. // of nothing loading/loaded return false
  9010. if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) {
  9011. return false;
  9012. }
  9013. const partList = levelDetails.partList;
  9014. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  9015. // check instead if the last part is buffered.
  9016. if (partList != null && partList.length) {
  9017. const lastPart = partList[partList.length - 1];
  9018. // Checking the midpoint of the part for potential margin of error and related issues.
  9019. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  9020. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  9021. // part mismatches for independent audio and video playlists/segments.
  9022. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  9023. return lastPartBuffered;
  9024. }
  9025. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  9026. return this.fragmentTracker.isEndListAppended(playlistType);
  9027. }
  9028. getLevelDetails() {
  9029. if (this.levels && this.levelLastLoaded !== null) {
  9030. var _this$levelLastLoaded;
  9031. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  9032. }
  9033. }
  9034. onMediaAttached(event, data) {
  9035. const media = this.media = this.mediaBuffer = data.media;
  9036. this.onvseeking = this.onMediaSeeking.bind(this);
  9037. this.onvended = this.onMediaEnded.bind(this);
  9038. media.addEventListener('seeking', this.onvseeking);
  9039. media.addEventListener('ended', this.onvended);
  9040. const config = this.config;
  9041. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  9042. this.startLoad(config.startPosition);
  9043. }
  9044. }
  9045. onMediaDetaching() {
  9046. const media = this.media;
  9047. if (media != null && media.ended) {
  9048. this.log('MSE detaching and video ended, reset startPosition');
  9049. this.startPosition = this.lastCurrentTime = 0;
  9050. }
  9051. // remove video listeners
  9052. if (media && this.onvseeking && this.onvended) {
  9053. media.removeEventListener('seeking', this.onvseeking);
  9054. media.removeEventListener('ended', this.onvended);
  9055. this.onvseeking = this.onvended = null;
  9056. }
  9057. if (this.keyLoader) {
  9058. this.keyLoader.detach();
  9059. }
  9060. this.media = this.mediaBuffer = null;
  9061. this.loadedmetadata = false;
  9062. this.fragmentTracker.removeAllFragments();
  9063. this.stopLoad();
  9064. }
  9065. onMediaSeeking() {
  9066. const {
  9067. config,
  9068. fragCurrent,
  9069. media,
  9070. mediaBuffer,
  9071. state
  9072. } = this;
  9073. const currentTime = media ? media.currentTime : 0;
  9074. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  9075. this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`);
  9076. if (this.state === State.ENDED) {
  9077. this.resetLoadingState();
  9078. } else if (fragCurrent) {
  9079. // Seeking while frag load is in progress
  9080. const tolerance = config.maxFragLookUpTolerance;
  9081. const fragStartOffset = fragCurrent.start - tolerance;
  9082. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  9083. // if seeking out of buffered range or into new one
  9084. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  9085. const pastFragment = currentTime > fragEndOffset;
  9086. // if the seek position is outside the current fragment range
  9087. if (currentTime < fragStartOffset || pastFragment) {
  9088. if (pastFragment && fragCurrent.loader) {
  9089. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  9090. fragCurrent.abortRequests();
  9091. this.resetLoadingState();
  9092. }
  9093. this.fragPrevious = null;
  9094. }
  9095. }
  9096. }
  9097. if (media) {
  9098. // Remove gap fragments
  9099. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  9100. this.lastCurrentTime = currentTime;
  9101. }
  9102. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  9103. if (!this.loadedmetadata && !bufferInfo.len) {
  9104. this.nextLoadPosition = this.startPosition = currentTime;
  9105. }
  9106. // Async tick to speed up processing
  9107. this.tickImmediate();
  9108. }
  9109. onMediaEnded() {
  9110. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  9111. this.startPosition = this.lastCurrentTime = 0;
  9112. }
  9113. onManifestLoaded(event, data) {
  9114. this.startTimeOffset = data.startTimeOffset;
  9115. this.initPTS = [];
  9116. }
  9117. onHandlerDestroying() {
  9118. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9119. this.stopLoad();
  9120. super.onHandlerDestroying();
  9121. // @ts-ignore
  9122. this.hls = null;
  9123. }
  9124. onHandlerDestroyed() {
  9125. this.state = State.STOPPED;
  9126. if (this.fragmentLoader) {
  9127. this.fragmentLoader.destroy();
  9128. }
  9129. if (this.keyLoader) {
  9130. this.keyLoader.destroy();
  9131. }
  9132. if (this.decrypter) {
  9133. this.decrypter.destroy();
  9134. }
  9135. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  9136. super.onHandlerDestroyed();
  9137. }
  9138. loadFragment(frag, level, targetBufferTime) {
  9139. this._loadFragForPlayback(frag, level, targetBufferTime);
  9140. }
  9141. _loadFragForPlayback(frag, level, targetBufferTime) {
  9142. const progressCallback = data => {
  9143. if (this.fragContextChanged(frag)) {
  9144. this.warn(`Fragment ${frag.sn}${data.part ? ' p: ' + data.part.index : ''} of level ${frag.level} was dropped during download.`);
  9145. this.fragmentTracker.removeFragment(frag);
  9146. return;
  9147. }
  9148. frag.stats.chunkCount++;
  9149. this._handleFragmentLoadProgress(data);
  9150. };
  9151. this._doFragLoad(frag, level, targetBufferTime, progressCallback).then(data => {
  9152. if (!data) {
  9153. // if we're here we probably needed to backtrack or are waiting for more parts
  9154. return;
  9155. }
  9156. const state = this.state;
  9157. if (this.fragContextChanged(frag)) {
  9158. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  9159. this.fragmentTracker.removeFragment(frag);
  9160. this.state = State.IDLE;
  9161. }
  9162. return;
  9163. }
  9164. if ('payload' in data) {
  9165. this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);
  9166. this.hls.trigger(Events.FRAG_LOADED, data);
  9167. }
  9168. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  9169. this._handleFragmentLoadComplete(data);
  9170. }).catch(reason => {
  9171. if (this.state === State.STOPPED || this.state === State.ERROR) {
  9172. return;
  9173. }
  9174. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  9175. this.resetFragmentLoading(frag);
  9176. });
  9177. }
  9178. clearTrackerIfNeeded(frag) {
  9179. var _this$mediaBuffer;
  9180. const {
  9181. fragmentTracker
  9182. } = this;
  9183. const fragState = fragmentTracker.getState(frag);
  9184. if (fragState === FragmentState.APPENDING) {
  9185. // Lower the max buffer length and try again
  9186. const playlistType = frag.type;
  9187. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  9188. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  9189. // If backtracking, always remove from the tracker without reducing max buffer length
  9190. const backtrackFragment = this.backtrackFragment;
  9191. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  9192. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  9193. fragmentTracker.removeFragment(frag);
  9194. }
  9195. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  9196. // Stop gap for bad tracker / buffer flush behavior
  9197. fragmentTracker.removeAllFragments();
  9198. } else if (fragmentTracker.hasParts(frag.type)) {
  9199. // In low latency mode, remove fragments for which only some parts were buffered
  9200. fragmentTracker.detectPartialFragments({
  9201. frag,
  9202. part: null,
  9203. stats: frag.stats,
  9204. id: frag.type
  9205. });
  9206. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  9207. fragmentTracker.removeFragment(frag);
  9208. }
  9209. }
  9210. }
  9211. checkLiveUpdate(details) {
  9212. if (details.updated && !details.live) {
  9213. // Live stream ended, update fragment tracker
  9214. const lastFragment = details.fragments[details.fragments.length - 1];
  9215. this.fragmentTracker.detectPartialFragments({
  9216. frag: lastFragment,
  9217. part: null,
  9218. stats: lastFragment.stats,
  9219. id: lastFragment.type
  9220. });
  9221. }
  9222. if (!details.fragments[0]) {
  9223. details.deltaUpdateFailed = true;
  9224. }
  9225. }
  9226. flushMainBuffer(startOffset, endOffset, type = null) {
  9227. if (!(startOffset - endOffset)) {
  9228. return;
  9229. }
  9230. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  9231. // passing a null type flushes both buffers
  9232. const flushScope = {
  9233. startOffset,
  9234. endOffset,
  9235. type
  9236. };
  9237. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  9238. }
  9239. _loadInitSegment(frag, level) {
  9240. this._doFragLoad(frag, level).then(data => {
  9241. if (!data || this.fragContextChanged(frag) || !this.levels) {
  9242. throw new Error('init load aborted');
  9243. }
  9244. return data;
  9245. }).then(data => {
  9246. const {
  9247. hls
  9248. } = this;
  9249. const {
  9250. payload
  9251. } = data;
  9252. const decryptData = frag.decryptdata;
  9253. // check to see if the payload needs to be decrypted
  9254. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  9255. const startTime = self.performance.now();
  9256. // decrypt init segment data
  9257. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(err => {
  9258. hls.trigger(Events.ERROR, {
  9259. type: ErrorTypes.MEDIA_ERROR,
  9260. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  9261. fatal: false,
  9262. error: err,
  9263. reason: err.message,
  9264. frag
  9265. });
  9266. throw err;
  9267. }).then(decryptedData => {
  9268. const endTime = self.performance.now();
  9269. hls.trigger(Events.FRAG_DECRYPTED, {
  9270. frag,
  9271. payload: decryptedData,
  9272. stats: {
  9273. tstart: startTime,
  9274. tdecrypt: endTime
  9275. }
  9276. });
  9277. data.payload = decryptedData;
  9278. return this.completeInitSegmentLoad(data);
  9279. });
  9280. }
  9281. return this.completeInitSegmentLoad(data);
  9282. }).catch(reason => {
  9283. if (this.state === State.STOPPED || this.state === State.ERROR) {
  9284. return;
  9285. }
  9286. this.warn(reason);
  9287. this.resetFragmentLoading(frag);
  9288. });
  9289. }
  9290. completeInitSegmentLoad(data) {
  9291. const {
  9292. levels
  9293. } = this;
  9294. if (!levels) {
  9295. throw new Error('init load aborted, missing levels');
  9296. }
  9297. const stats = data.frag.stats;
  9298. this.state = State.IDLE;
  9299. data.frag.data = new Uint8Array(data.payload);
  9300. stats.parsing.start = stats.buffering.start = self.performance.now();
  9301. stats.parsing.end = stats.buffering.end = self.performance.now();
  9302. this.tick();
  9303. }
  9304. fragContextChanged(frag) {
  9305. const {
  9306. fragCurrent
  9307. } = this;
  9308. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  9309. }
  9310. fragBufferedComplete(frag, part) {
  9311. var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious;
  9312. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  9313. this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track'} ${frag.level} (frag:[${((_frag$startPTS = frag.startPTS) != null ? _frag$startPTS : NaN).toFixed(3)}-${((_frag$endPTS = frag.endPTS) != null ? _frag$endPTS : NaN).toFixed(3)}] > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)'})`);
  9314. if (frag.sn !== 'initSegment') {
  9315. var _this$levels;
  9316. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  9317. const el = frag.elementaryStreams;
  9318. if (!Object.keys(el).some(type => !!el[type])) {
  9319. // empty segment
  9320. this.state = State.IDLE;
  9321. return;
  9322. }
  9323. }
  9324. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  9325. if (level != null && level.fragmentError) {
  9326. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  9327. level.fragmentError = 0;
  9328. }
  9329. }
  9330. this.state = State.IDLE;
  9331. if (!media) {
  9332. return;
  9333. }
  9334. if (!this.loadedmetadata && frag.type == PlaylistLevelType.MAIN && media.buffered.length && ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.sn) === ((_this$fragPrevious = this.fragPrevious) == null ? void 0 : _this$fragPrevious.sn)) {
  9335. this.loadedmetadata = true;
  9336. this.seekToStartPos();
  9337. }
  9338. this.tick();
  9339. }
  9340. seekToStartPos() {}
  9341. _handleFragmentLoadComplete(fragLoadedEndData) {
  9342. const {
  9343. transmuxer
  9344. } = this;
  9345. if (!transmuxer) {
  9346. return;
  9347. }
  9348. const {
  9349. frag,
  9350. part,
  9351. partsLoaded
  9352. } = fragLoadedEndData;
  9353. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  9354. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);
  9355. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  9356. transmuxer.flush(chunkMeta);
  9357. }
  9358. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  9359. _handleFragmentLoadProgress(frag) {}
  9360. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  9361. var _frag$decryptdata;
  9362. const details = level == null ? void 0 : level.details;
  9363. if (!this.levels || !details) {
  9364. throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);
  9365. }
  9366. let keyLoadingPromise = null;
  9367. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  9368. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${frag.level}`);
  9369. this.state = State.KEY_LOADING;
  9370. this.fragCurrent = frag;
  9371. keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {
  9372. if (!this.fragContextChanged(keyLoadedData.frag)) {
  9373. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  9374. if (this.state === State.KEY_LOADING) {
  9375. this.state = State.IDLE;
  9376. }
  9377. return keyLoadedData;
  9378. }
  9379. });
  9380. this.hls.trigger(Events.KEY_LOADING, {
  9381. frag
  9382. });
  9383. if (this.fragCurrent === null) {
  9384. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  9385. }
  9386. } else if (!frag.encrypted && details.encryptedFragments.length) {
  9387. this.keyLoader.loadClear(frag, details.encryptedFragments);
  9388. }
  9389. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  9390. if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {
  9391. const partList = details.partList;
  9392. if (partList && progressCallback) {
  9393. if (targetBufferTime > frag.end && details.fragmentHint) {
  9394. frag = details.fragmentHint;
  9395. }
  9396. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  9397. if (partIndex > -1) {
  9398. const part = partList[partIndex];
  9399. this.log(`Loading part sn: ${frag.sn} p: ${part.index} cc: ${frag.cc} of playlist [${details.startSN}-${details.endSN}] parts [0-${partIndex}-${partList.length - 1}] ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  9400. this.nextLoadPosition = part.start + part.duration;
  9401. this.state = State.FRAG_LOADING;
  9402. let _result;
  9403. if (keyLoadingPromise) {
  9404. _result = keyLoadingPromise.then(keyLoadedData => {
  9405. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  9406. return null;
  9407. }
  9408. return this.doFragPartsLoad(frag, part, level, progressCallback);
  9409. }).catch(error => this.handleFragLoadError(error));
  9410. } else {
  9411. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));
  9412. }
  9413. this.hls.trigger(Events.FRAG_LOADING, {
  9414. frag,
  9415. part,
  9416. targetBufferTime
  9417. });
  9418. if (this.fragCurrent === null) {
  9419. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  9420. }
  9421. return _result;
  9422. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  9423. // Fragment hint has no parts
  9424. return Promise.resolve(null);
  9425. }
  9426. }
  9427. }
  9428. this.log(`Loading fragment ${frag.sn} cc: ${frag.cc} ${details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''}${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${frag.level}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);
  9429. // Don't update nextLoadPosition for fragments which are not buffered
  9430. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  9431. this.nextLoadPosition = frag.start + frag.duration;
  9432. }
  9433. this.state = State.FRAG_LOADING;
  9434. // Load key before streaming fragment data
  9435. const dataOnProgress = this.config.progressive;
  9436. let result;
  9437. if (dataOnProgress && keyLoadingPromise) {
  9438. result = keyLoadingPromise.then(keyLoadedData => {
  9439. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  9440. return null;
  9441. }
  9442. return this.fragmentLoader.load(frag, progressCallback);
  9443. }).catch(error => this.handleFragLoadError(error));
  9444. } else {
  9445. // load unencrypted fragment data with progress event,
  9446. // or handle fragment result after key and fragment are finished loading
  9447. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {
  9448. if (!dataOnProgress && fragLoadedData && progressCallback) {
  9449. progressCallback(fragLoadedData);
  9450. }
  9451. return fragLoadedData;
  9452. }).catch(error => this.handleFragLoadError(error));
  9453. }
  9454. this.hls.trigger(Events.FRAG_LOADING, {
  9455. frag,
  9456. targetBufferTime
  9457. });
  9458. if (this.fragCurrent === null) {
  9459. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  9460. }
  9461. return result;
  9462. }
  9463. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  9464. return new Promise((resolve, reject) => {
  9465. var _level$details;
  9466. const partsLoaded = [];
  9467. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  9468. const loadPart = part => {
  9469. this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {
  9470. partsLoaded[part.index] = partLoadedData;
  9471. const loadedPart = partLoadedData.part;
  9472. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  9473. const nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  9474. if (nextPart) {
  9475. loadPart(nextPart);
  9476. } else {
  9477. return resolve({
  9478. frag,
  9479. part: loadedPart,
  9480. partsLoaded
  9481. });
  9482. }
  9483. }).catch(reject);
  9484. };
  9485. loadPart(fromPart);
  9486. });
  9487. }
  9488. handleFragLoadError(error) {
  9489. if ('data' in error) {
  9490. const data = error.data;
  9491. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  9492. this.handleFragLoadAborted(data.frag, data.part);
  9493. } else {
  9494. this.hls.trigger(Events.ERROR, data);
  9495. }
  9496. } else {
  9497. this.hls.trigger(Events.ERROR, {
  9498. type: ErrorTypes.OTHER_ERROR,
  9499. details: ErrorDetails.INTERNAL_EXCEPTION,
  9500. err: error,
  9501. error,
  9502. fatal: true
  9503. });
  9504. }
  9505. return null;
  9506. }
  9507. _handleTransmuxerFlush(chunkMeta) {
  9508. const context = this.getCurrentContext(chunkMeta);
  9509. if (!context || this.state !== State.PARSING) {
  9510. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  9511. this.state = State.IDLE;
  9512. }
  9513. return;
  9514. }
  9515. const {
  9516. frag,
  9517. part,
  9518. level
  9519. } = context;
  9520. const now = self.performance.now();
  9521. frag.stats.parsing.end = now;
  9522. if (part) {
  9523. part.stats.parsing.end = now;
  9524. }
  9525. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  9526. }
  9527. getCurrentContext(chunkMeta) {
  9528. const {
  9529. levels,
  9530. fragCurrent
  9531. } = this;
  9532. const {
  9533. level: levelIndex,
  9534. sn,
  9535. part: partIndex
  9536. } = chunkMeta;
  9537. if (!(levels != null && levels[levelIndex])) {
  9538. this.warn(`Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`);
  9539. return null;
  9540. }
  9541. const level = levels[levelIndex];
  9542. const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  9543. const frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent);
  9544. if (!frag) {
  9545. return null;
  9546. }
  9547. if (fragCurrent && fragCurrent !== frag) {
  9548. frag.stats = fragCurrent.stats;
  9549. }
  9550. return {
  9551. frag,
  9552. part,
  9553. level
  9554. };
  9555. }
  9556. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  9557. var _buffer;
  9558. if (!data || this.state !== State.PARSING) {
  9559. return;
  9560. }
  9561. const {
  9562. data1,
  9563. data2
  9564. } = data;
  9565. let buffer = data1;
  9566. if (data1 && data2) {
  9567. // Combine the moof + mdat so that we buffer with a single append
  9568. buffer = appendUint8Array(data1, data2);
  9569. }
  9570. if (!((_buffer = buffer) != null && _buffer.length)) {
  9571. return;
  9572. }
  9573. const segment = {
  9574. type: data.type,
  9575. frag,
  9576. part,
  9577. chunkMeta,
  9578. parent: frag.type,
  9579. data: buffer
  9580. };
  9581. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  9582. if (data.dropped && data.independent && !part) {
  9583. if (noBacktracking) {
  9584. return;
  9585. }
  9586. // Clear buffer so that we reload previous segments sequentially if required
  9587. this.flushBufferGap(frag);
  9588. }
  9589. }
  9590. flushBufferGap(frag) {
  9591. const media = this.media;
  9592. if (!media) {
  9593. return;
  9594. }
  9595. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  9596. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  9597. this.flushMainBuffer(0, frag.start);
  9598. return;
  9599. }
  9600. // Remove back-buffer without interrupting playback to allow back tracking
  9601. const currentTime = media.currentTime;
  9602. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  9603. const fragDuration = frag.duration;
  9604. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  9605. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  9606. if (frag.start - start > segmentFraction) {
  9607. this.flushMainBuffer(start, frag.start);
  9608. }
  9609. }
  9610. getFwdBufferInfo(bufferable, type) {
  9611. const pos = this.getLoadPosition();
  9612. if (!isFiniteNumber(pos)) {
  9613. return null;
  9614. }
  9615. return this.getFwdBufferInfoAtPos(bufferable, pos, type);
  9616. }
  9617. getFwdBufferInfoAtPos(bufferable, pos, type) {
  9618. const {
  9619. config: {
  9620. maxBufferHole
  9621. }
  9622. } = this;
  9623. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  9624. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  9625. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  9626. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  9627. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  9628. return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole));
  9629. }
  9630. }
  9631. return bufferInfo;
  9632. }
  9633. getMaxBufferLength(levelBitrate) {
  9634. const {
  9635. config
  9636. } = this;
  9637. let maxBufLen;
  9638. if (levelBitrate) {
  9639. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  9640. } else {
  9641. maxBufLen = config.maxBufferLength;
  9642. }
  9643. return Math.min(maxBufLen, config.maxMaxBufferLength);
  9644. }
  9645. reduceMaxBufferLength(threshold, fragDuration) {
  9646. const config = this.config;
  9647. const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  9648. const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  9649. if (reducedLength >= minLength) {
  9650. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  9651. config.maxMaxBufferLength = reducedLength;
  9652. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  9653. return true;
  9654. }
  9655. return false;
  9656. }
  9657. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  9658. const fragOrPart = this.fragmentTracker.getAppendedFrag(position, PlaylistLevelType.MAIN);
  9659. if (fragOrPart && 'fragment' in fragOrPart) {
  9660. return fragOrPart.fragment;
  9661. }
  9662. return fragOrPart;
  9663. }
  9664. getNextFragment(pos, levelDetails) {
  9665. const fragments = levelDetails.fragments;
  9666. const fragLen = fragments.length;
  9667. if (!fragLen) {
  9668. return null;
  9669. }
  9670. // find fragment index, contiguous with end of buffer position
  9671. const {
  9672. config
  9673. } = this;
  9674. const start = fragments[0].start;
  9675. let frag;
  9676. if (levelDetails.live) {
  9677. const initialLiveManifestSize = config.initialLiveManifestSize;
  9678. if (fragLen < initialLiveManifestSize) {
  9679. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  9680. return null;
  9681. }
  9682. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  9683. // In order to discover the range, we load the best matching fragment for that level and demux it.
  9684. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  9685. // we get the fragment matching that start time
  9686. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  9687. frag = this.getInitialLiveFragment(levelDetails, fragments);
  9688. this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  9689. }
  9690. } else if (pos <= start) {
  9691. // VoD playlist: if loadPosition before start of playlist, load first fragment
  9692. frag = fragments[0];
  9693. }
  9694. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  9695. if (!frag) {
  9696. const end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  9697. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  9698. }
  9699. return this.mapToInitFragWhenRequired(frag);
  9700. }
  9701. isLoopLoading(frag, targetBufferTime) {
  9702. const trackerState = this.fragmentTracker.getState(frag);
  9703. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  9704. }
  9705. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  9706. const gapStart = frag.gap;
  9707. const nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  9708. if (nextFragment === null) {
  9709. return nextFragment;
  9710. }
  9711. frag = nextFragment;
  9712. if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {
  9713. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  9714. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType);
  9715. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  9716. // Returning here might result in not finding an audio and video candiate to skip to
  9717. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${frag.sn}`);
  9718. return null;
  9719. }
  9720. }
  9721. return frag;
  9722. }
  9723. mapToInitFragWhenRequired(frag) {
  9724. // If an initSegment is present, it must be buffered first
  9725. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  9726. return frag.initSegment;
  9727. }
  9728. return frag;
  9729. }
  9730. getNextPart(partList, frag, targetBufferTime) {
  9731. let nextPart = -1;
  9732. let contiguous = false;
  9733. let independentAttrOmitted = true;
  9734. for (let i = 0, len = partList.length; i < len; i++) {
  9735. const part = partList[i];
  9736. independentAttrOmitted = independentAttrOmitted && !part.independent;
  9737. if (nextPart > -1 && targetBufferTime < part.start) {
  9738. break;
  9739. }
  9740. const loaded = part.loaded;
  9741. if (loaded) {
  9742. nextPart = -1;
  9743. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  9744. nextPart = i;
  9745. }
  9746. contiguous = loaded;
  9747. }
  9748. return nextPart;
  9749. }
  9750. loadedEndOfParts(partList, targetBufferTime) {
  9751. const lastPart = partList[partList.length - 1];
  9752. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  9753. }
  9754. /*
  9755. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  9756. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  9757. start and end times for each fragment in the playlist (after which this method will not need to be called).
  9758. */
  9759. getInitialLiveFragment(levelDetails, fragments) {
  9760. const fragPrevious = this.fragPrevious;
  9761. let frag = null;
  9762. if (fragPrevious) {
  9763. if (levelDetails.hasProgramDateTime) {
  9764. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  9765. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  9766. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  9767. }
  9768. if (!frag) {
  9769. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  9770. const targetSN = fragPrevious.sn + 1;
  9771. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  9772. const fragNext = fragments[targetSN - levelDetails.startSN];
  9773. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  9774. if (fragPrevious.cc === fragNext.cc) {
  9775. frag = fragNext;
  9776. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  9777. }
  9778. }
  9779. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  9780. // will have the wrong start times
  9781. if (!frag) {
  9782. frag = findFragWithCC(fragments, fragPrevious.cc);
  9783. if (frag) {
  9784. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  9785. }
  9786. }
  9787. }
  9788. } else {
  9789. // Find a new start fragment when fragPrevious is null
  9790. const liveStart = this.hls.liveSyncPosition;
  9791. if (liveStart !== null) {
  9792. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  9793. }
  9794. }
  9795. return frag;
  9796. }
  9797. /*
  9798. This method finds the best matching fragment given the provided position.
  9799. */
  9800. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  9801. const {
  9802. config
  9803. } = this;
  9804. let {
  9805. fragPrevious
  9806. } = this;
  9807. let {
  9808. fragments,
  9809. endSN
  9810. } = levelDetails;
  9811. const {
  9812. fragmentHint
  9813. } = levelDetails;
  9814. const {
  9815. maxFragLookUpTolerance
  9816. } = config;
  9817. const partList = levelDetails.partList;
  9818. const loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint);
  9819. if (loadingParts && fragmentHint && !this.bitrateTest) {
  9820. // Include incomplete fragment with parts at end
  9821. fragments = fragments.concat(fragmentHint);
  9822. endSN = fragmentHint.sn;
  9823. }
  9824. let frag;
  9825. if (bufferEnd < end) {
  9826. const lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;
  9827. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  9828. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  9829. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  9830. } else {
  9831. // reach end of playlist
  9832. frag = fragments[fragments.length - 1];
  9833. }
  9834. if (frag) {
  9835. const curSNIdx = frag.sn - levelDetails.startSN;
  9836. // Move fragPrevious forward to support forcing the next fragment to load
  9837. // when the buffer catches up to a previously buffered range.
  9838. const fragState = this.fragmentTracker.getState(frag);
  9839. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  9840. fragPrevious = frag;
  9841. }
  9842. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) {
  9843. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  9844. // non-uniform fragment durations
  9845. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  9846. if (sameLevel) {
  9847. const nextFrag = fragments[curSNIdx + 1];
  9848. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  9849. frag = nextFrag;
  9850. } else {
  9851. frag = null;
  9852. }
  9853. }
  9854. }
  9855. }
  9856. return frag;
  9857. }
  9858. synchronizeToLiveEdge(levelDetails) {
  9859. const {
  9860. config,
  9861. media
  9862. } = this;
  9863. if (!media) {
  9864. return;
  9865. }
  9866. const liveSyncPosition = this.hls.liveSyncPosition;
  9867. const currentTime = media.currentTime;
  9868. const start = levelDetails.fragments[0].start;
  9869. const end = levelDetails.edge;
  9870. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  9871. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  9872. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  9873. // Continue if buffer is starving or if current time is behind max latency
  9874. const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  9875. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  9876. if (!this.loadedmetadata) {
  9877. this.nextLoadPosition = liveSyncPosition;
  9878. }
  9879. // Only seek if ready and there is not a significant forward buffer available for playback
  9880. if (media.readyState) {
  9881. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  9882. media.currentTime = liveSyncPosition;
  9883. }
  9884. }
  9885. }
  9886. }
  9887. alignPlaylists(details, previousDetails, switchDetails) {
  9888. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  9889. // this could all go in level-helper mergeDetails()
  9890. const length = details.fragments.length;
  9891. if (!length) {
  9892. this.warn(`No fragments in live playlist`);
  9893. return 0;
  9894. }
  9895. const slidingStart = details.fragments[0].start;
  9896. const firstLevelLoad = !previousDetails;
  9897. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  9898. if (firstLevelLoad || !aligned && !slidingStart) {
  9899. const {
  9900. fragPrevious
  9901. } = this;
  9902. alignStream(fragPrevious, switchDetails, details);
  9903. const alignedSlidingStart = details.fragments[0].start;
  9904. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} prev-sn: ${fragPrevious ? fragPrevious.sn : 'na'} fragments: ${length}`);
  9905. return alignedSlidingStart;
  9906. }
  9907. return slidingStart;
  9908. }
  9909. waitForCdnTuneIn(details) {
  9910. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  9911. const advancePartLimit = 3;
  9912. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  9913. }
  9914. setStartPosition(details, sliding) {
  9915. // compute start position if set to -1. use it straight away if value is defined
  9916. let startPosition = this.startPosition;
  9917. if (startPosition < sliding) {
  9918. startPosition = -1;
  9919. }
  9920. if (startPosition === -1 || this.lastCurrentTime === -1) {
  9921. // Use Playlist EXT-X-START:TIME-OFFSET when set
  9922. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  9923. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  9924. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  9925. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  9926. startPosition = sliding + startTimeOffset;
  9927. if (startTimeOffset < 0) {
  9928. startPosition += details.totalduration;
  9929. }
  9930. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  9931. this.log(`Start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist, adjust startPosition to ${startPosition}`);
  9932. this.startPosition = startPosition;
  9933. } else if (details.live) {
  9934. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  9935. // not been specified via the config or an as an argument to startLoad (#3736).
  9936. startPosition = this.hls.liveSyncPosition || sliding;
  9937. } else {
  9938. this.startPosition = startPosition = 0;
  9939. }
  9940. this.lastCurrentTime = startPosition;
  9941. }
  9942. this.nextLoadPosition = startPosition;
  9943. }
  9944. getLoadPosition() {
  9945. const {
  9946. media
  9947. } = this;
  9948. // if we have not yet loaded any fragment, start loading from start position
  9949. let pos = 0;
  9950. if (this.loadedmetadata && media) {
  9951. pos = media.currentTime;
  9952. } else if (this.nextLoadPosition) {
  9953. pos = this.nextLoadPosition;
  9954. }
  9955. return pos;
  9956. }
  9957. handleFragLoadAborted(frag, part) {
  9958. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  9959. this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} was aborted`);
  9960. this.resetFragmentLoading(frag);
  9961. }
  9962. }
  9963. resetFragmentLoading(frag) {
  9964. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  9965. this.state = State.IDLE;
  9966. }
  9967. }
  9968. onFragmentOrKeyLoadError(filterType, data) {
  9969. if (data.chunkMeta && !data.frag) {
  9970. const context = this.getCurrentContext(data.chunkMeta);
  9971. if (context) {
  9972. data.frag = context.frag;
  9973. }
  9974. }
  9975. const frag = data.frag;
  9976. // Handle frag error related to caller's filterType
  9977. if (!frag || frag.type !== filterType || !this.levels) {
  9978. return;
  9979. }
  9980. if (this.fragContextChanged(frag)) {
  9981. var _this$fragCurrent2;
  9982. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url}`);
  9983. return;
  9984. }
  9985. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  9986. if (gapTagEncountered) {
  9987. this.fragmentTracker.fragBuffered(frag, true);
  9988. }
  9989. // keep retrying until the limit will be reached
  9990. const errorAction = data.errorAction;
  9991. const {
  9992. action,
  9993. retryCount = 0,
  9994. retryConfig
  9995. } = errorAction || {};
  9996. if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) {
  9997. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9998. const delay = getRetryDelay(retryConfig, retryCount);
  9999. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  10000. errorAction.resolved = true;
  10001. this.retryDate = self.performance.now() + delay;
  10002. this.state = State.FRAG_LOADING_WAITING_RETRY;
  10003. } else if (retryConfig && errorAction) {
  10004. this.resetFragmentErrors(filterType);
  10005. if (retryCount < retryConfig.maxNumRetry) {
  10006. // Network retry is skipped when level switch is preferred
  10007. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  10008. errorAction.resolved = true;
  10009. }
  10010. } else {
  10011. logger.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  10012. return;
  10013. }
  10014. } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) {
  10015. this.state = State.WAITING_LEVEL;
  10016. } else {
  10017. this.state = State.ERROR;
  10018. }
  10019. // Perform next async tick sooner to speed up error action resolution
  10020. this.tickImmediate();
  10021. }
  10022. reduceLengthAndFlushBuffer(data) {
  10023. // if in appending state
  10024. if (this.state === State.PARSING || this.state === State.PARSED) {
  10025. const frag = data.frag;
  10026. const playlistType = data.parent;
  10027. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  10028. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  10029. // reduce max buf len if current position is buffered
  10030. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  10031. if (buffered) {
  10032. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  10033. }
  10034. const flushBuffer = !buffered;
  10035. if (flushBuffer) {
  10036. // current position is not buffered, but browser is still complaining about buffer full error
  10037. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  10038. // in that case flush the whole audio buffer to recover
  10039. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  10040. }
  10041. if (frag) {
  10042. this.fragmentTracker.removeFragment(frag);
  10043. this.nextLoadPosition = frag.start;
  10044. }
  10045. this.resetLoadingState();
  10046. return flushBuffer;
  10047. }
  10048. return false;
  10049. }
  10050. resetFragmentErrors(filterType) {
  10051. if (filterType === PlaylistLevelType.AUDIO) {
  10052. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  10053. this.fragCurrent = null;
  10054. }
  10055. // Fragment errors that result in a level switch or redundant fail-over
  10056. // should reset the stream controller state to idle
  10057. if (!this.loadedmetadata) {
  10058. this.startFragRequested = false;
  10059. }
  10060. if (this.state !== State.STOPPED) {
  10061. this.state = State.IDLE;
  10062. }
  10063. }
  10064. afterBufferFlushed(media, bufferType, playlistType) {
  10065. if (!media) {
  10066. return;
  10067. }
  10068. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  10069. // (so that we will check against video.buffered ranges in case of alt audio track)
  10070. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  10071. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  10072. if (this.state === State.ENDED) {
  10073. this.resetLoadingState();
  10074. }
  10075. }
  10076. resetLoadingState() {
  10077. this.log('Reset loading state');
  10078. this.fragCurrent = null;
  10079. this.fragPrevious = null;
  10080. this.state = State.IDLE;
  10081. }
  10082. resetStartWhenNotLoaded(level) {
  10083. // if loadedmetadata is not set, it means that first frag request failed
  10084. // in that case, reset startFragRequested flag
  10085. if (!this.loadedmetadata) {
  10086. this.startFragRequested = false;
  10087. const details = level ? level.details : null;
  10088. if (details != null && details.live) {
  10089. // Update the start position and return to IDLE to recover live start
  10090. this.startPosition = -1;
  10091. this.setStartPosition(details, 0);
  10092. this.resetLoadingState();
  10093. } else {
  10094. this.nextLoadPosition = this.startPosition;
  10095. }
  10096. }
  10097. }
  10098. resetWhenMissingContext(chunkMeta) {
  10099. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`);
  10100. this.removeUnbufferedFrags();
  10101. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10102. this.resetLoadingState();
  10103. }
  10104. removeUnbufferedFrags(start = 0) {
  10105. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  10106. }
  10107. updateLevelTiming(frag, part, level, partial) {
  10108. var _this$transmuxer;
  10109. const details = level.details;
  10110. if (!details) {
  10111. this.warn('level.details undefined');
  10112. return;
  10113. }
  10114. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  10115. const info = frag.elementaryStreams[type];
  10116. if (info) {
  10117. const parsedDuration = info.endPTS - info.startPTS;
  10118. if (parsedDuration <= 0) {
  10119. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  10120. // The new transmuxer will be configured with a time offset matching the next fragment start,
  10121. // preventing the timeline from shifting.
  10122. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  10123. return result || false;
  10124. }
  10125. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  10126. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  10127. details,
  10128. level,
  10129. drift,
  10130. type,
  10131. frag,
  10132. start: info.startPTS,
  10133. end: info.endPTS
  10134. });
  10135. return true;
  10136. }
  10137. return result;
  10138. }, false);
  10139. if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  10140. const error = new Error(`Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`);
  10141. if (level.fragmentError === 0) {
  10142. // Mark and track the odd empty segment as a gap to avoid reloading
  10143. level.fragmentError++;
  10144. frag.gap = true;
  10145. this.fragmentTracker.removeFragment(frag);
  10146. this.fragmentTracker.fragBuffered(frag, true);
  10147. }
  10148. this.warn(error.message);
  10149. this.hls.trigger(Events.ERROR, {
  10150. type: ErrorTypes.MEDIA_ERROR,
  10151. details: ErrorDetails.FRAG_PARSING_ERROR,
  10152. fatal: false,
  10153. error,
  10154. frag,
  10155. reason: `Found no media in msn ${frag.sn} of level "${level.url}"`
  10156. });
  10157. if (!this.hls) {
  10158. return;
  10159. }
  10160. this.resetTransmuxer();
  10161. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  10162. }
  10163. this.state = State.PARSED;
  10164. this.hls.trigger(Events.FRAG_PARSED, {
  10165. frag,
  10166. part
  10167. });
  10168. }
  10169. resetTransmuxer() {
  10170. if (this.transmuxer) {
  10171. this.transmuxer.destroy();
  10172. this.transmuxer = null;
  10173. }
  10174. }
  10175. recoverWorkerError(data) {
  10176. if (data.event === 'demuxerWorker') {
  10177. this.fragmentTracker.removeAllFragments();
  10178. this.resetTransmuxer();
  10179. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10180. this.resetLoadingState();
  10181. }
  10182. }
  10183. set state(nextState) {
  10184. const previousState = this._state;
  10185. if (previousState !== nextState) {
  10186. this._state = nextState;
  10187. this.log(`${previousState}->${nextState}`);
  10188. }
  10189. }
  10190. get state() {
  10191. return this._state;
  10192. }
  10193. }
  10194. class ChunkCache {
  10195. constructor() {
  10196. this.chunks = [];
  10197. this.dataLength = 0;
  10198. }
  10199. push(chunk) {
  10200. this.chunks.push(chunk);
  10201. this.dataLength += chunk.length;
  10202. }
  10203. flush() {
  10204. const {
  10205. chunks,
  10206. dataLength
  10207. } = this;
  10208. let result;
  10209. if (!chunks.length) {
  10210. return new Uint8Array(0);
  10211. } else if (chunks.length === 1) {
  10212. result = chunks[0];
  10213. } else {
  10214. result = concatUint8Arrays(chunks, dataLength);
  10215. }
  10216. this.reset();
  10217. return result;
  10218. }
  10219. reset() {
  10220. this.chunks.length = 0;
  10221. this.dataLength = 0;
  10222. }
  10223. }
  10224. function concatUint8Arrays(chunks, dataLength) {
  10225. const result = new Uint8Array(dataLength);
  10226. let offset = 0;
  10227. for (let i = 0; i < chunks.length; i++) {
  10228. const chunk = chunks[i];
  10229. result.set(chunk, offset);
  10230. offset += chunk.length;
  10231. }
  10232. return result;
  10233. }
  10234. // ensure the worker ends up in the bundle
  10235. // If the worker should not be included this gets aliased to empty.js
  10236. function hasUMDWorker() {
  10237. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  10238. }
  10239. function injectWorker() {
  10240. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  10241. type: 'text/javascript'
  10242. });
  10243. const objectURL = self.URL.createObjectURL(blob);
  10244. const worker = new self.Worker(objectURL);
  10245. return {
  10246. worker,
  10247. objectURL
  10248. };
  10249. }
  10250. function loadWorker(path) {
  10251. const scriptURL = new self.URL(path, self.location.href).href;
  10252. const worker = new self.Worker(scriptURL);
  10253. return {
  10254. worker,
  10255. scriptURL
  10256. };
  10257. }
  10258. function dummyTrack(type = '', inputTimeScale = 90000) {
  10259. return {
  10260. type,
  10261. id: -1,
  10262. pid: -1,
  10263. inputTimeScale,
  10264. sequenceNumber: -1,
  10265. samples: [],
  10266. dropped: 0
  10267. };
  10268. }
  10269. class BaseAudioDemuxer {
  10270. constructor() {
  10271. this._audioTrack = void 0;
  10272. this._id3Track = void 0;
  10273. this.frameIndex = 0;
  10274. this.cachedData = null;
  10275. this.basePTS = null;
  10276. this.initPTS = null;
  10277. this.lastPTS = null;
  10278. }
  10279. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10280. this._id3Track = {
  10281. type: 'id3',
  10282. id: 3,
  10283. pid: -1,
  10284. inputTimeScale: 90000,
  10285. sequenceNumber: 0,
  10286. samples: [],
  10287. dropped: 0
  10288. };
  10289. }
  10290. resetTimeStamp(deaultTimestamp) {
  10291. this.initPTS = deaultTimestamp;
  10292. this.resetContiguity();
  10293. }
  10294. resetContiguity() {
  10295. this.basePTS = null;
  10296. this.lastPTS = null;
  10297. this.frameIndex = 0;
  10298. }
  10299. canParse(data, offset) {
  10300. return false;
  10301. }
  10302. appendFrame(track, data, offset) {}
  10303. // feed incoming data to the front of the parsing pipeline
  10304. demux(data, timeOffset) {
  10305. if (this.cachedData) {
  10306. data = appendUint8Array(this.cachedData, data);
  10307. this.cachedData = null;
  10308. }
  10309. let id3Data = getID3Data(data, 0);
  10310. let offset = id3Data ? id3Data.length : 0;
  10311. let lastDataIndex;
  10312. const track = this._audioTrack;
  10313. const id3Track = this._id3Track;
  10314. const timestamp = id3Data ? getTimeStamp(id3Data) : undefined;
  10315. const length = data.length;
  10316. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  10317. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  10318. this.lastPTS = this.basePTS;
  10319. }
  10320. if (this.lastPTS === null) {
  10321. this.lastPTS = this.basePTS;
  10322. }
  10323. // more expressive than alternative: id3Data?.length
  10324. if (id3Data && id3Data.length > 0) {
  10325. id3Track.samples.push({
  10326. pts: this.lastPTS,
  10327. dts: this.lastPTS,
  10328. data: id3Data,
  10329. type: MetadataSchema.audioId3,
  10330. duration: Number.POSITIVE_INFINITY
  10331. });
  10332. }
  10333. while (offset < length) {
  10334. if (this.canParse(data, offset)) {
  10335. const frame = this.appendFrame(track, data, offset);
  10336. if (frame) {
  10337. this.frameIndex++;
  10338. this.lastPTS = frame.sample.pts;
  10339. offset += frame.length;
  10340. lastDataIndex = offset;
  10341. } else {
  10342. offset = length;
  10343. }
  10344. } else if (canParse$2(data, offset)) {
  10345. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  10346. id3Data = getID3Data(data, offset);
  10347. id3Track.samples.push({
  10348. pts: this.lastPTS,
  10349. dts: this.lastPTS,
  10350. data: id3Data,
  10351. type: MetadataSchema.audioId3,
  10352. duration: Number.POSITIVE_INFINITY
  10353. });
  10354. offset += id3Data.length;
  10355. lastDataIndex = offset;
  10356. } else {
  10357. offset++;
  10358. }
  10359. if (offset === length && lastDataIndex !== length) {
  10360. const partialData = sliceUint8(data, lastDataIndex);
  10361. if (this.cachedData) {
  10362. this.cachedData = appendUint8Array(this.cachedData, partialData);
  10363. } else {
  10364. this.cachedData = partialData;
  10365. }
  10366. }
  10367. }
  10368. return {
  10369. audioTrack: track,
  10370. videoTrack: dummyTrack(),
  10371. id3Track,
  10372. textTrack: dummyTrack()
  10373. };
  10374. }
  10375. demuxSampleAes(data, keyData, timeOffset) {
  10376. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  10377. }
  10378. flush(timeOffset) {
  10379. // Parse cache in case of remaining frames.
  10380. const cachedData = this.cachedData;
  10381. if (cachedData) {
  10382. this.cachedData = null;
  10383. this.demux(cachedData, 0);
  10384. }
  10385. return {
  10386. audioTrack: this._audioTrack,
  10387. videoTrack: dummyTrack(),
  10388. id3Track: this._id3Track,
  10389. textTrack: dummyTrack()
  10390. };
  10391. }
  10392. destroy() {}
  10393. }
  10394. /**
  10395. * Initialize PTS
  10396. * <p>
  10397. * use timestamp unless it is undefined, NaN or Infinity
  10398. * </p>
  10399. */
  10400. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  10401. if (isFiniteNumber(timestamp)) {
  10402. return timestamp * 90;
  10403. }
  10404. const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  10405. return timeOffset * 90000 + init90kHz;
  10406. };
  10407. /**
  10408. * ADTS parser helper
  10409. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  10410. */
  10411. function getAudioConfig(observer, data, offset, audioCodec) {
  10412. let adtsObjectType;
  10413. let adtsExtensionSamplingIndex;
  10414. let adtsChannelConfig;
  10415. let config;
  10416. const userAgent = navigator.userAgent.toLowerCase();
  10417. const manifestCodec = audioCodec;
  10418. const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  10419. // byte 2
  10420. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  10421. const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  10422. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  10423. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  10424. observer.emit(Events.ERROR, Events.ERROR, {
  10425. type: ErrorTypes.MEDIA_ERROR,
  10426. details: ErrorDetails.FRAG_PARSING_ERROR,
  10427. fatal: true,
  10428. error,
  10429. reason: error.message
  10430. });
  10431. return;
  10432. }
  10433. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  10434. // byte 3
  10435. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  10436. logger.log(`manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`);
  10437. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  10438. if (/firefox/i.test(userAgent)) {
  10439. if (adtsSamplingIndex >= 6) {
  10440. adtsObjectType = 5;
  10441. config = new Array(4);
  10442. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10443. // there is a factor 2 between frame sample rate and output sample rate
  10444. // multiply frequency by 2 (see table below, equivalent to substract 3)
  10445. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  10446. } else {
  10447. adtsObjectType = 2;
  10448. config = new Array(2);
  10449. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10450. }
  10451. // Android : always use AAC
  10452. } else if (userAgent.indexOf('android') !== -1) {
  10453. adtsObjectType = 2;
  10454. config = new Array(2);
  10455. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10456. } else {
  10457. /* for other browsers (Chrome/Vivaldi/Opera ...)
  10458. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  10459. */
  10460. adtsObjectType = 5;
  10461. config = new Array(4);
  10462. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  10463. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  10464. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10465. // there is a factor 2 between frame sample rate and output sample rate
  10466. // multiply frequency by 2 (see table below, equivalent to substract 3)
  10467. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  10468. } else {
  10469. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  10470. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  10471. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  10472. adtsObjectType = 2;
  10473. config = new Array(2);
  10474. }
  10475. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10476. }
  10477. }
  10478. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  10479. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  10480. Audio Profile / Audio Object Type
  10481. 0: Null
  10482. 1: AAC Main
  10483. 2: AAC LC (Low Complexity)
  10484. 3: AAC SSR (Scalable Sample Rate)
  10485. 4: AAC LTP (Long Term Prediction)
  10486. 5: SBR (Spectral Band Replication)
  10487. 6: AAC Scalable
  10488. sampling freq
  10489. 0: 96000 Hz
  10490. 1: 88200 Hz
  10491. 2: 64000 Hz
  10492. 3: 48000 Hz
  10493. 4: 44100 Hz
  10494. 5: 32000 Hz
  10495. 6: 24000 Hz
  10496. 7: 22050 Hz
  10497. 8: 16000 Hz
  10498. 9: 12000 Hz
  10499. 10: 11025 Hz
  10500. 11: 8000 Hz
  10501. 12: 7350 Hz
  10502. 13: Reserved
  10503. 14: Reserved
  10504. 15: frequency is written explictly
  10505. Channel Configurations
  10506. These are the channel configurations:
  10507. 0: Defined in AOT Specifc Config
  10508. 1: 1 channel: front-center
  10509. 2: 2 channels: front-left, front-right
  10510. */
  10511. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  10512. config[0] = adtsObjectType << 3;
  10513. // samplingFrequencyIndex
  10514. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  10515. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  10516. // channelConfiguration
  10517. config[1] |= adtsChannelConfig << 3;
  10518. if (adtsObjectType === 5) {
  10519. // adtsExtensionSamplingIndex
  10520. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  10521. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  10522. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  10523. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  10524. config[2] |= 2 << 2;
  10525. config[3] = 0;
  10526. }
  10527. return {
  10528. config,
  10529. samplerate: adtsSamplingRates[adtsSamplingIndex],
  10530. channelCount: adtsChannelConfig,
  10531. codec: 'mp4a.40.' + adtsObjectType,
  10532. manifestCodec
  10533. };
  10534. }
  10535. function isHeaderPattern$1(data, offset) {
  10536. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  10537. }
  10538. function getHeaderLength(data, offset) {
  10539. return data[offset + 1] & 0x01 ? 7 : 9;
  10540. }
  10541. function getFullFrameLength(data, offset) {
  10542. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  10543. }
  10544. function canGetFrameLength(data, offset) {
  10545. return offset + 5 < data.length;
  10546. }
  10547. function isHeader$1(data, offset) {
  10548. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10549. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10550. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10551. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  10552. }
  10553. function canParse$1(data, offset) {
  10554. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  10555. }
  10556. function probe$1(data, offset) {
  10557. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  10558. // or end of data is reached
  10559. if (isHeader$1(data, offset)) {
  10560. // ADTS header Length
  10561. const headerLength = getHeaderLength(data, offset);
  10562. if (offset + headerLength >= data.length) {
  10563. return false;
  10564. }
  10565. // ADTS frame Length
  10566. const frameLength = getFullFrameLength(data, offset);
  10567. if (frameLength <= headerLength) {
  10568. return false;
  10569. }
  10570. const newOffset = offset + frameLength;
  10571. return newOffset === data.length || isHeader$1(data, newOffset);
  10572. }
  10573. return false;
  10574. }
  10575. function initTrackConfig(track, observer, data, offset, audioCodec) {
  10576. if (!track.samplerate) {
  10577. const config = getAudioConfig(observer, data, offset, audioCodec);
  10578. if (!config) {
  10579. return;
  10580. }
  10581. track.config = config.config;
  10582. track.samplerate = config.samplerate;
  10583. track.channelCount = config.channelCount;
  10584. track.codec = config.codec;
  10585. track.manifestCodec = config.manifestCodec;
  10586. logger.log(`parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`);
  10587. }
  10588. }
  10589. function getFrameDuration(samplerate) {
  10590. return 1024 * 90000 / samplerate;
  10591. }
  10592. function parseFrameHeader(data, offset) {
  10593. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  10594. const headerLength = getHeaderLength(data, offset);
  10595. if (offset + headerLength <= data.length) {
  10596. // retrieve frame size
  10597. const frameLength = getFullFrameLength(data, offset) - headerLength;
  10598. if (frameLength > 0) {
  10599. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  10600. return {
  10601. headerLength,
  10602. frameLength
  10603. };
  10604. }
  10605. }
  10606. }
  10607. function appendFrame$2(track, data, offset, pts, frameIndex) {
  10608. const frameDuration = getFrameDuration(track.samplerate);
  10609. const stamp = pts + frameIndex * frameDuration;
  10610. const header = parseFrameHeader(data, offset);
  10611. let unit;
  10612. if (header) {
  10613. const {
  10614. frameLength,
  10615. headerLength
  10616. } = header;
  10617. const _length = headerLength + frameLength;
  10618. const missing = Math.max(0, offset + _length - data.length);
  10619. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  10620. if (missing) {
  10621. unit = new Uint8Array(_length - headerLength);
  10622. unit.set(data.subarray(offset + headerLength, data.length), 0);
  10623. } else {
  10624. unit = data.subarray(offset + headerLength, offset + _length);
  10625. }
  10626. const _sample = {
  10627. unit,
  10628. pts: stamp
  10629. };
  10630. if (!missing) {
  10631. track.samples.push(_sample);
  10632. }
  10633. return {
  10634. sample: _sample,
  10635. length: _length,
  10636. missing
  10637. };
  10638. }
  10639. // overflow incomplete header
  10640. const length = data.length - offset;
  10641. unit = new Uint8Array(length);
  10642. unit.set(data.subarray(offset, data.length), 0);
  10643. const sample = {
  10644. unit,
  10645. pts: stamp
  10646. };
  10647. return {
  10648. sample,
  10649. length,
  10650. missing: -1
  10651. };
  10652. }
  10653. /**
  10654. * MPEG parser helper
  10655. */
  10656. let chromeVersion$1 = null;
  10657. 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];
  10658. const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  10659. const SamplesCoefficients = [
  10660. // MPEG 2.5
  10661. [0,
  10662. // Reserved
  10663. 72,
  10664. // Layer3
  10665. 144,
  10666. // Layer2
  10667. 12 // Layer1
  10668. ],
  10669. // Reserved
  10670. [0,
  10671. // Reserved
  10672. 0,
  10673. // Layer3
  10674. 0,
  10675. // Layer2
  10676. 0 // Layer1
  10677. ],
  10678. // MPEG 2
  10679. [0,
  10680. // Reserved
  10681. 72,
  10682. // Layer3
  10683. 144,
  10684. // Layer2
  10685. 12 // Layer1
  10686. ],
  10687. // MPEG 1
  10688. [0,
  10689. // Reserved
  10690. 144,
  10691. // Layer3
  10692. 144,
  10693. // Layer2
  10694. 12 // Layer1
  10695. ]];
  10696. const BytesInSlot = [0,
  10697. // Reserved
  10698. 1,
  10699. // Layer3
  10700. 1,
  10701. // Layer2
  10702. 4 // Layer1
  10703. ];
  10704. function appendFrame$1(track, data, offset, pts, frameIndex) {
  10705. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  10706. if (offset + 24 > data.length) {
  10707. return;
  10708. }
  10709. const header = parseHeader(data, offset);
  10710. if (header && offset + header.frameLength <= data.length) {
  10711. const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  10712. const stamp = pts + frameIndex * frameDuration;
  10713. const sample = {
  10714. unit: data.subarray(offset, offset + header.frameLength),
  10715. pts: stamp,
  10716. dts: stamp
  10717. };
  10718. track.config = [];
  10719. track.channelCount = header.channelCount;
  10720. track.samplerate = header.sampleRate;
  10721. track.samples.push(sample);
  10722. return {
  10723. sample,
  10724. length: header.frameLength,
  10725. missing: 0
  10726. };
  10727. }
  10728. }
  10729. function parseHeader(data, offset) {
  10730. const mpegVersion = data[offset + 1] >> 3 & 3;
  10731. const mpegLayer = data[offset + 1] >> 1 & 3;
  10732. const bitRateIndex = data[offset + 2] >> 4 & 15;
  10733. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  10734. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  10735. const paddingBit = data[offset + 2] >> 1 & 1;
  10736. const channelMode = data[offset + 3] >> 6;
  10737. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  10738. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  10739. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  10740. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  10741. const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  10742. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  10743. const bytesInSlot = BytesInSlot[mpegLayer];
  10744. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  10745. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  10746. if (chromeVersion$1 === null) {
  10747. const userAgent = navigator.userAgent || '';
  10748. const result = userAgent.match(/Chrome\/(\d+)/i);
  10749. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  10750. }
  10751. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  10752. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  10753. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  10754. data[offset + 3] = data[offset + 3] | 0x80;
  10755. }
  10756. return {
  10757. sampleRate,
  10758. channelCount,
  10759. frameLength,
  10760. samplesPerFrame
  10761. };
  10762. }
  10763. }
  10764. function isHeaderPattern(data, offset) {
  10765. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  10766. }
  10767. function isHeader(data, offset) {
  10768. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10769. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10770. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10771. return offset + 1 < data.length && isHeaderPattern(data, offset);
  10772. }
  10773. function canParse(data, offset) {
  10774. const headerSize = 4;
  10775. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  10776. }
  10777. function probe(data, offset) {
  10778. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  10779. // or end of data is reached
  10780. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  10781. // MPEG header Length
  10782. const headerLength = 4;
  10783. // MPEG frame Length
  10784. const header = parseHeader(data, offset);
  10785. let frameLength = headerLength;
  10786. if (header != null && header.frameLength) {
  10787. frameLength = header.frameLength;
  10788. }
  10789. const newOffset = offset + frameLength;
  10790. return newOffset === data.length || isHeader(data, newOffset);
  10791. }
  10792. return false;
  10793. }
  10794. /**
  10795. * AAC demuxer
  10796. */
  10797. class AACDemuxer extends BaseAudioDemuxer {
  10798. constructor(observer, config) {
  10799. super();
  10800. this.observer = void 0;
  10801. this.config = void 0;
  10802. this.observer = observer;
  10803. this.config = config;
  10804. }
  10805. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10806. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10807. this._audioTrack = {
  10808. container: 'audio/adts',
  10809. type: 'audio',
  10810. id: 2,
  10811. pid: -1,
  10812. sequenceNumber: 0,
  10813. segmentCodec: 'aac',
  10814. samples: [],
  10815. manifestCodec: audioCodec,
  10816. duration: trackDuration,
  10817. inputTimeScale: 90000,
  10818. dropped: 0
  10819. };
  10820. }
  10821. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  10822. static probe(data) {
  10823. if (!data) {
  10824. return false;
  10825. }
  10826. // Check for the ADTS sync word
  10827. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10828. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10829. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10830. const id3Data = getID3Data(data, 0);
  10831. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10832. if (probe(data, offset)) {
  10833. return false;
  10834. }
  10835. for (let length = data.length; offset < length; offset++) {
  10836. if (probe$1(data, offset)) {
  10837. logger.log('ADTS sync word found !');
  10838. return true;
  10839. }
  10840. }
  10841. return false;
  10842. }
  10843. canParse(data, offset) {
  10844. return canParse$1(data, offset);
  10845. }
  10846. appendFrame(track, data, offset) {
  10847. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  10848. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  10849. if (frame && frame.missing === 0) {
  10850. return frame;
  10851. }
  10852. }
  10853. }
  10854. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  10855. class MP4Demuxer {
  10856. constructor(observer, config) {
  10857. this.remainderData = null;
  10858. this.timeOffset = 0;
  10859. this.config = void 0;
  10860. this.videoTrack = void 0;
  10861. this.audioTrack = void 0;
  10862. this.id3Track = void 0;
  10863. this.txtTrack = void 0;
  10864. this.config = config;
  10865. }
  10866. resetTimeStamp() {}
  10867. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10868. const videoTrack = this.videoTrack = dummyTrack('video', 1);
  10869. const audioTrack = this.audioTrack = dummyTrack('audio', 1);
  10870. const captionTrack = this.txtTrack = dummyTrack('text', 1);
  10871. this.id3Track = dummyTrack('id3', 1);
  10872. this.timeOffset = 0;
  10873. if (!(initSegment != null && initSegment.byteLength)) {
  10874. return;
  10875. }
  10876. const initData = parseInitSegment(initSegment);
  10877. if (initData.video) {
  10878. const {
  10879. id,
  10880. timescale,
  10881. codec
  10882. } = initData.video;
  10883. videoTrack.id = id;
  10884. videoTrack.timescale = captionTrack.timescale = timescale;
  10885. videoTrack.codec = codec;
  10886. }
  10887. if (initData.audio) {
  10888. const {
  10889. id,
  10890. timescale,
  10891. codec
  10892. } = initData.audio;
  10893. audioTrack.id = id;
  10894. audioTrack.timescale = timescale;
  10895. audioTrack.codec = codec;
  10896. }
  10897. captionTrack.id = RemuxerTrackIdConfig.text;
  10898. videoTrack.sampleDuration = 0;
  10899. videoTrack.duration = audioTrack.duration = trackDuration;
  10900. }
  10901. resetContiguity() {
  10902. this.remainderData = null;
  10903. }
  10904. static probe(data) {
  10905. return hasMoofData(data);
  10906. }
  10907. demux(data, timeOffset) {
  10908. this.timeOffset = timeOffset;
  10909. // 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
  10910. let videoSamples = data;
  10911. const videoTrack = this.videoTrack;
  10912. const textTrack = this.txtTrack;
  10913. if (this.config.progressive) {
  10914. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  10915. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  10916. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  10917. if (this.remainderData) {
  10918. videoSamples = appendUint8Array(this.remainderData, data);
  10919. }
  10920. const segmentedData = segmentValidRange(videoSamples);
  10921. this.remainderData = segmentedData.remainder;
  10922. videoTrack.samples = segmentedData.valid || new Uint8Array();
  10923. } else {
  10924. videoTrack.samples = videoSamples;
  10925. }
  10926. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  10927. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10928. return {
  10929. videoTrack,
  10930. audioTrack: this.audioTrack,
  10931. id3Track,
  10932. textTrack: this.txtTrack
  10933. };
  10934. }
  10935. flush() {
  10936. const timeOffset = this.timeOffset;
  10937. const videoTrack = this.videoTrack;
  10938. const textTrack = this.txtTrack;
  10939. videoTrack.samples = this.remainderData || new Uint8Array();
  10940. this.remainderData = null;
  10941. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  10942. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10943. return {
  10944. videoTrack,
  10945. audioTrack: dummyTrack(),
  10946. id3Track,
  10947. textTrack: dummyTrack()
  10948. };
  10949. }
  10950. extractID3Track(videoTrack, timeOffset) {
  10951. const id3Track = this.id3Track;
  10952. if (videoTrack.samples.length) {
  10953. const emsgs = findBox(videoTrack.samples, ['emsg']);
  10954. if (emsgs) {
  10955. emsgs.forEach(data => {
  10956. const emsgInfo = parseEmsg(data);
  10957. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  10958. const pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  10959. let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  10960. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  10961. if (duration <= 0.001) {
  10962. duration = Number.POSITIVE_INFINITY;
  10963. }
  10964. const payload = emsgInfo.payload;
  10965. id3Track.samples.push({
  10966. data: payload,
  10967. len: payload.byteLength,
  10968. dts: pts,
  10969. pts: pts,
  10970. type: MetadataSchema.emsg,
  10971. duration: duration
  10972. });
  10973. }
  10974. });
  10975. }
  10976. }
  10977. return id3Track;
  10978. }
  10979. demuxSampleAes(data, keyData, timeOffset) {
  10980. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  10981. }
  10982. destroy() {}
  10983. }
  10984. const getAudioBSID = (data, offset) => {
  10985. // check the bsid to confirm ac-3 | ec-3
  10986. let bsid = 0;
  10987. let numBits = 5;
  10988. offset += numBits;
  10989. const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  10990. const mask = new Uint32Array(1); // unsigned 32 bit mask value
  10991. const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  10992. while (numBits > 0) {
  10993. byte[0] = data[offset];
  10994. // read remaining bits, upto 8 bits at a time
  10995. const bits = Math.min(numBits, 8);
  10996. const shift = 8 - bits;
  10997. mask[0] = 0xff000000 >>> 24 + shift << shift;
  10998. temp[0] = (byte[0] & mask[0]) >> shift;
  10999. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  11000. offset += 1;
  11001. numBits -= bits;
  11002. }
  11003. return bsid;
  11004. };
  11005. class AC3Demuxer extends BaseAudioDemuxer {
  11006. constructor(observer) {
  11007. super();
  11008. this.observer = void 0;
  11009. this.observer = observer;
  11010. }
  11011. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11012. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  11013. this._audioTrack = {
  11014. container: 'audio/ac-3',
  11015. type: 'audio',
  11016. id: 2,
  11017. pid: -1,
  11018. sequenceNumber: 0,
  11019. segmentCodec: 'ac3',
  11020. samples: [],
  11021. manifestCodec: audioCodec,
  11022. duration: trackDuration,
  11023. inputTimeScale: 90000,
  11024. dropped: 0
  11025. };
  11026. }
  11027. canParse(data, offset) {
  11028. return offset + 64 < data.length;
  11029. }
  11030. appendFrame(track, data, offset) {
  11031. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  11032. if (frameLength !== -1) {
  11033. const sample = track.samples[track.samples.length - 1];
  11034. return {
  11035. sample,
  11036. length: frameLength,
  11037. missing: 0
  11038. };
  11039. }
  11040. }
  11041. static probe(data) {
  11042. if (!data) {
  11043. return false;
  11044. }
  11045. const id3Data = getID3Data(data, 0);
  11046. if (!id3Data) {
  11047. return false;
  11048. }
  11049. // look for the ac-3 sync bytes
  11050. const offset = id3Data.length;
  11051. if (data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  11052. // check the bsid to confirm ac-3
  11053. getAudioBSID(data, offset) < 16) {
  11054. return true;
  11055. }
  11056. return false;
  11057. }
  11058. }
  11059. function appendFrame(track, data, start, pts, frameIndex) {
  11060. if (start + 8 > data.length) {
  11061. return -1; // not enough bytes left
  11062. }
  11063. if (data[start] !== 0x0b || data[start + 1] !== 0x77) {
  11064. return -1; // invalid magic
  11065. }
  11066. // get sample rate
  11067. const samplingRateCode = data[start + 4] >> 6;
  11068. if (samplingRateCode >= 3) {
  11069. return -1; // invalid sampling rate
  11070. }
  11071. const samplingRateMap = [48000, 44100, 32000];
  11072. const sampleRate = samplingRateMap[samplingRateCode];
  11073. // get frame size
  11074. const frameSizeCode = data[start + 4] & 0x3f;
  11075. 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];
  11076. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  11077. if (start + frameLength > data.length) {
  11078. return -1;
  11079. }
  11080. // get channel count
  11081. const channelMode = data[start + 6] >> 5;
  11082. let skipCount = 0;
  11083. if (channelMode === 2) {
  11084. skipCount += 2;
  11085. } else {
  11086. if (channelMode & 1 && channelMode !== 1) {
  11087. skipCount += 2;
  11088. }
  11089. if (channelMode & 4) {
  11090. skipCount += 2;
  11091. }
  11092. }
  11093. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  11094. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  11095. const channelCount = channelsMap[channelMode] + lfeon;
  11096. // build dac3 box
  11097. const bsid = data[start + 5] >> 3;
  11098. const bsmod = data[start + 5] & 7;
  11099. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 0xe0]);
  11100. const frameDuration = 1536 / sampleRate * 90000;
  11101. const stamp = pts + frameIndex * frameDuration;
  11102. const unit = data.subarray(start, start + frameLength);
  11103. track.config = config;
  11104. track.channelCount = channelCount;
  11105. track.samplerate = sampleRate;
  11106. track.samples.push({
  11107. unit,
  11108. pts: stamp
  11109. });
  11110. return frameLength;
  11111. }
  11112. class BaseVideoParser {
  11113. constructor() {
  11114. this.VideoSample = null;
  11115. }
  11116. createVideoSample(key, pts, dts, debug) {
  11117. return {
  11118. key,
  11119. frame: false,
  11120. pts,
  11121. dts,
  11122. units: [],
  11123. debug,
  11124. length: 0
  11125. };
  11126. }
  11127. getLastNalUnit(samples) {
  11128. var _VideoSample;
  11129. let VideoSample = this.VideoSample;
  11130. let lastUnit;
  11131. // try to fallback to previous sample if current one is empty
  11132. if (!VideoSample || VideoSample.units.length === 0) {
  11133. VideoSample = samples[samples.length - 1];
  11134. }
  11135. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  11136. const units = VideoSample.units;
  11137. lastUnit = units[units.length - 1];
  11138. }
  11139. return lastUnit;
  11140. }
  11141. pushAccessUnit(VideoSample, videoTrack) {
  11142. if (VideoSample.units.length && VideoSample.frame) {
  11143. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  11144. if (VideoSample.pts === undefined) {
  11145. const samples = videoTrack.samples;
  11146. const nbSamples = samples.length;
  11147. if (nbSamples) {
  11148. const lastSample = samples[nbSamples - 1];
  11149. VideoSample.pts = lastSample.pts;
  11150. VideoSample.dts = lastSample.dts;
  11151. } else {
  11152. // dropping samples, no timestamp found
  11153. videoTrack.dropped++;
  11154. return;
  11155. }
  11156. }
  11157. videoTrack.samples.push(VideoSample);
  11158. }
  11159. if (VideoSample.debug.length) {
  11160. logger.log(VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug);
  11161. }
  11162. }
  11163. }
  11164. /**
  11165. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  11166. */
  11167. class ExpGolomb {
  11168. constructor(data) {
  11169. this.data = void 0;
  11170. this.bytesAvailable = void 0;
  11171. this.word = void 0;
  11172. this.bitsAvailable = void 0;
  11173. this.data = data;
  11174. // the number of bytes left to examine in this.data
  11175. this.bytesAvailable = data.byteLength;
  11176. // the current word being examined
  11177. this.word = 0; // :uint
  11178. // the number of bits left to examine in the current word
  11179. this.bitsAvailable = 0; // :uint
  11180. }
  11181. // ():void
  11182. loadWord() {
  11183. const data = this.data;
  11184. const bytesAvailable = this.bytesAvailable;
  11185. const position = data.byteLength - bytesAvailable;
  11186. const workingBytes = new Uint8Array(4);
  11187. const availableBytes = Math.min(4, bytesAvailable);
  11188. if (availableBytes === 0) {
  11189. throw new Error('no bytes available');
  11190. }
  11191. workingBytes.set(data.subarray(position, position + availableBytes));
  11192. this.word = new DataView(workingBytes.buffer).getUint32(0);
  11193. // track the amount of this.data that has been processed
  11194. this.bitsAvailable = availableBytes * 8;
  11195. this.bytesAvailable -= availableBytes;
  11196. }
  11197. // (count:int):void
  11198. skipBits(count) {
  11199. let skipBytes; // :int
  11200. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  11201. if (this.bitsAvailable > count) {
  11202. this.word <<= count;
  11203. this.bitsAvailable -= count;
  11204. } else {
  11205. count -= this.bitsAvailable;
  11206. skipBytes = count >> 3;
  11207. count -= skipBytes << 3;
  11208. this.bytesAvailable -= skipBytes;
  11209. this.loadWord();
  11210. this.word <<= count;
  11211. this.bitsAvailable -= count;
  11212. }
  11213. }
  11214. // (size:int):uint
  11215. readBits(size) {
  11216. let bits = Math.min(this.bitsAvailable, size); // :uint
  11217. const valu = this.word >>> 32 - bits; // :uint
  11218. if (size > 32) {
  11219. logger.error('Cannot read more than 32 bits at a time');
  11220. }
  11221. this.bitsAvailable -= bits;
  11222. if (this.bitsAvailable > 0) {
  11223. this.word <<= bits;
  11224. } else if (this.bytesAvailable > 0) {
  11225. this.loadWord();
  11226. } else {
  11227. throw new Error('no bits available');
  11228. }
  11229. bits = size - bits;
  11230. if (bits > 0 && this.bitsAvailable) {
  11231. return valu << bits | this.readBits(bits);
  11232. } else {
  11233. return valu;
  11234. }
  11235. }
  11236. // ():uint
  11237. skipLZ() {
  11238. let leadingZeroCount; // :uint
  11239. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  11240. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  11241. // the first bit of working word is 1
  11242. this.word <<= leadingZeroCount;
  11243. this.bitsAvailable -= leadingZeroCount;
  11244. return leadingZeroCount;
  11245. }
  11246. }
  11247. // we exhausted word and still have not found a 1
  11248. this.loadWord();
  11249. return leadingZeroCount + this.skipLZ();
  11250. }
  11251. // ():void
  11252. skipUEG() {
  11253. this.skipBits(1 + this.skipLZ());
  11254. }
  11255. // ():void
  11256. skipEG() {
  11257. this.skipBits(1 + this.skipLZ());
  11258. }
  11259. // ():uint
  11260. readUEG() {
  11261. const clz = this.skipLZ(); // :uint
  11262. return this.readBits(clz + 1) - 1;
  11263. }
  11264. // ():int
  11265. readEG() {
  11266. const valu = this.readUEG(); // :int
  11267. if (0x01 & valu) {
  11268. // the number is odd if the low order bit is set
  11269. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  11270. } else {
  11271. return -1 * (valu >>> 1); // divide by two then make it negative
  11272. }
  11273. }
  11274. // Some convenience functions
  11275. // :Boolean
  11276. readBoolean() {
  11277. return this.readBits(1) === 1;
  11278. }
  11279. // ():int
  11280. readUByte() {
  11281. return this.readBits(8);
  11282. }
  11283. // ():int
  11284. readUShort() {
  11285. return this.readBits(16);
  11286. }
  11287. // ():int
  11288. readUInt() {
  11289. return this.readBits(32);
  11290. }
  11291. /**
  11292. * Advance the ExpGolomb decoder past a scaling list. The scaling
  11293. * list is optionally transmitted as part of a sequence parameter
  11294. * set and is not relevant to transmuxing.
  11295. * @param count the number of entries in this scaling list
  11296. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  11297. */
  11298. skipScalingList(count) {
  11299. let lastScale = 8;
  11300. let nextScale = 8;
  11301. let deltaScale;
  11302. for (let j = 0; j < count; j++) {
  11303. if (nextScale !== 0) {
  11304. deltaScale = this.readEG();
  11305. nextScale = (lastScale + deltaScale + 256) % 256;
  11306. }
  11307. lastScale = nextScale === 0 ? lastScale : nextScale;
  11308. }
  11309. }
  11310. /**
  11311. * Read a sequence parameter set and return some interesting video
  11312. * properties. A sequence parameter set is the H264 metadata that
  11313. * describes the properties of upcoming video frames.
  11314. * @returns an object with configuration parsed from the
  11315. * sequence parameter set, including the dimensions of the
  11316. * associated video frames.
  11317. */
  11318. readSPS() {
  11319. let frameCropLeftOffset = 0;
  11320. let frameCropRightOffset = 0;
  11321. let frameCropTopOffset = 0;
  11322. let frameCropBottomOffset = 0;
  11323. let numRefFramesInPicOrderCntCycle;
  11324. let scalingListCount;
  11325. let i;
  11326. const readUByte = this.readUByte.bind(this);
  11327. const readBits = this.readBits.bind(this);
  11328. const readUEG = this.readUEG.bind(this);
  11329. const readBoolean = this.readBoolean.bind(this);
  11330. const skipBits = this.skipBits.bind(this);
  11331. const skipEG = this.skipEG.bind(this);
  11332. const skipUEG = this.skipUEG.bind(this);
  11333. const skipScalingList = this.skipScalingList.bind(this);
  11334. readUByte();
  11335. const profileIdc = readUByte(); // profile_idc
  11336. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  11337. skipBits(3); // reserved_zero_3bits u(3),
  11338. readUByte(); // level_idc u(8)
  11339. skipUEG(); // seq_parameter_set_id
  11340. // some profiles have more optional data we don't need
  11341. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  11342. const chromaFormatIdc = readUEG();
  11343. if (chromaFormatIdc === 3) {
  11344. skipBits(1);
  11345. } // separate_colour_plane_flag
  11346. skipUEG(); // bit_depth_luma_minus8
  11347. skipUEG(); // bit_depth_chroma_minus8
  11348. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  11349. if (readBoolean()) {
  11350. // seq_scaling_matrix_present_flag
  11351. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  11352. for (i = 0; i < scalingListCount; i++) {
  11353. if (readBoolean()) {
  11354. // seq_scaling_list_present_flag[ i ]
  11355. if (i < 6) {
  11356. skipScalingList(16);
  11357. } else {
  11358. skipScalingList(64);
  11359. }
  11360. }
  11361. }
  11362. }
  11363. }
  11364. skipUEG(); // log2_max_frame_num_minus4
  11365. const picOrderCntType = readUEG();
  11366. if (picOrderCntType === 0) {
  11367. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  11368. } else if (picOrderCntType === 1) {
  11369. skipBits(1); // delta_pic_order_always_zero_flag
  11370. skipEG(); // offset_for_non_ref_pic
  11371. skipEG(); // offset_for_top_to_bottom_field
  11372. numRefFramesInPicOrderCntCycle = readUEG();
  11373. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  11374. skipEG();
  11375. } // offset_for_ref_frame[ i ]
  11376. }
  11377. skipUEG(); // max_num_ref_frames
  11378. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  11379. const picWidthInMbsMinus1 = readUEG();
  11380. const picHeightInMapUnitsMinus1 = readUEG();
  11381. const frameMbsOnlyFlag = readBits(1);
  11382. if (frameMbsOnlyFlag === 0) {
  11383. skipBits(1);
  11384. } // mb_adaptive_frame_field_flag
  11385. skipBits(1); // direct_8x8_inference_flag
  11386. if (readBoolean()) {
  11387. // frame_cropping_flag
  11388. frameCropLeftOffset = readUEG();
  11389. frameCropRightOffset = readUEG();
  11390. frameCropTopOffset = readUEG();
  11391. frameCropBottomOffset = readUEG();
  11392. }
  11393. let pixelRatio = [1, 1];
  11394. if (readBoolean()) {
  11395. // vui_parameters_present_flag
  11396. if (readBoolean()) {
  11397. // aspect_ratio_info_present_flag
  11398. const aspectRatioIdc = readUByte();
  11399. switch (aspectRatioIdc) {
  11400. case 1:
  11401. pixelRatio = [1, 1];
  11402. break;
  11403. case 2:
  11404. pixelRatio = [12, 11];
  11405. break;
  11406. case 3:
  11407. pixelRatio = [10, 11];
  11408. break;
  11409. case 4:
  11410. pixelRatio = [16, 11];
  11411. break;
  11412. case 5:
  11413. pixelRatio = [40, 33];
  11414. break;
  11415. case 6:
  11416. pixelRatio = [24, 11];
  11417. break;
  11418. case 7:
  11419. pixelRatio = [20, 11];
  11420. break;
  11421. case 8:
  11422. pixelRatio = [32, 11];
  11423. break;
  11424. case 9:
  11425. pixelRatio = [80, 33];
  11426. break;
  11427. case 10:
  11428. pixelRatio = [18, 11];
  11429. break;
  11430. case 11:
  11431. pixelRatio = [15, 11];
  11432. break;
  11433. case 12:
  11434. pixelRatio = [64, 33];
  11435. break;
  11436. case 13:
  11437. pixelRatio = [160, 99];
  11438. break;
  11439. case 14:
  11440. pixelRatio = [4, 3];
  11441. break;
  11442. case 15:
  11443. pixelRatio = [3, 2];
  11444. break;
  11445. case 16:
  11446. pixelRatio = [2, 1];
  11447. break;
  11448. case 255:
  11449. {
  11450. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  11451. break;
  11452. }
  11453. }
  11454. }
  11455. }
  11456. return {
  11457. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  11458. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  11459. pixelRatio: pixelRatio
  11460. };
  11461. }
  11462. readSliceType() {
  11463. // skip NALu type
  11464. this.readUByte();
  11465. // discard first_mb_in_slice
  11466. this.readUEG();
  11467. // return slice_type
  11468. return this.readUEG();
  11469. }
  11470. }
  11471. class AvcVideoParser extends BaseVideoParser {
  11472. parseAVCPES(track, textTrack, pes, last, duration) {
  11473. const units = this.parseAVCNALu(track, pes.data);
  11474. let VideoSample = this.VideoSample;
  11475. let push;
  11476. let spsfound = false;
  11477. // free pes.data to save up some memory
  11478. pes.data = null;
  11479. // if new NAL units found and last sample still there, let's push ...
  11480. // this helps parsing streams with missing AUD (only do this if AUD never found)
  11481. if (VideoSample && units.length && !track.audFound) {
  11482. this.pushAccessUnit(VideoSample, track);
  11483. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  11484. }
  11485. units.forEach(unit => {
  11486. var _VideoSample2;
  11487. switch (unit.type) {
  11488. // NDR
  11489. case 1:
  11490. {
  11491. let iskey = false;
  11492. push = true;
  11493. const data = unit.data;
  11494. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  11495. if (spsfound && data.length > 4) {
  11496. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  11497. const sliceType = new ExpGolomb(data).readSliceType();
  11498. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  11499. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  11500. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  11501. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  11502. // if (sliceType === 2 || sliceType === 7) {
  11503. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  11504. iskey = true;
  11505. }
  11506. }
  11507. if (iskey) {
  11508. var _VideoSample;
  11509. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  11510. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  11511. this.pushAccessUnit(VideoSample, track);
  11512. VideoSample = this.VideoSample = null;
  11513. }
  11514. }
  11515. if (!VideoSample) {
  11516. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  11517. }
  11518. VideoSample.frame = true;
  11519. VideoSample.key = iskey;
  11520. break;
  11521. // IDR
  11522. }
  11523. case 5:
  11524. push = true;
  11525. // handle PES not starting with AUD
  11526. // if we have frame data already, that cannot belong to the same frame, so force a push
  11527. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  11528. this.pushAccessUnit(VideoSample, track);
  11529. VideoSample = this.VideoSample = null;
  11530. }
  11531. if (!VideoSample) {
  11532. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  11533. }
  11534. VideoSample.key = true;
  11535. VideoSample.frame = true;
  11536. break;
  11537. // SEI
  11538. case 6:
  11539. {
  11540. push = true;
  11541. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  11542. break;
  11543. // SPS
  11544. }
  11545. case 7:
  11546. {
  11547. var _track$pixelRatio, _track$pixelRatio2;
  11548. push = true;
  11549. spsfound = true;
  11550. const sps = unit.data;
  11551. const expGolombDecoder = new ExpGolomb(sps);
  11552. const config = expGolombDecoder.readSPS();
  11553. 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]) {
  11554. track.width = config.width;
  11555. track.height = config.height;
  11556. track.pixelRatio = config.pixelRatio;
  11557. track.sps = [sps];
  11558. track.duration = duration;
  11559. const codecarray = sps.subarray(1, 4);
  11560. let codecstring = 'avc1.';
  11561. for (let i = 0; i < 3; i++) {
  11562. let h = codecarray[i].toString(16);
  11563. if (h.length < 2) {
  11564. h = '0' + h;
  11565. }
  11566. codecstring += h;
  11567. }
  11568. track.codec = codecstring;
  11569. }
  11570. break;
  11571. }
  11572. // PPS
  11573. case 8:
  11574. push = true;
  11575. track.pps = [unit.data];
  11576. break;
  11577. // AUD
  11578. case 9:
  11579. push = true;
  11580. track.audFound = true;
  11581. if (VideoSample) {
  11582. this.pushAccessUnit(VideoSample, track);
  11583. }
  11584. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  11585. break;
  11586. // Filler Data
  11587. case 12:
  11588. push = true;
  11589. break;
  11590. default:
  11591. push = false;
  11592. if (VideoSample) {
  11593. VideoSample.debug += 'unknown NAL ' + unit.type + ' ';
  11594. }
  11595. break;
  11596. }
  11597. if (VideoSample && push) {
  11598. const units = VideoSample.units;
  11599. units.push(unit);
  11600. }
  11601. });
  11602. // if last PES packet, push samples
  11603. if (last && VideoSample) {
  11604. this.pushAccessUnit(VideoSample, track);
  11605. this.VideoSample = null;
  11606. }
  11607. }
  11608. parseAVCNALu(track, array) {
  11609. const len = array.byteLength;
  11610. let state = track.naluState || 0;
  11611. const lastState = state;
  11612. const units = [];
  11613. let i = 0;
  11614. let value;
  11615. let overflow;
  11616. let unitType;
  11617. let lastUnitStart = -1;
  11618. let lastUnitType = 0;
  11619. // logger.log('PES:' + Hex.hexDump(array));
  11620. if (state === -1) {
  11621. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  11622. lastUnitStart = 0;
  11623. // NALu type is value read from offset 0
  11624. lastUnitType = array[0] & 0x1f;
  11625. state = 0;
  11626. i = 1;
  11627. }
  11628. while (i < len) {
  11629. value = array[i++];
  11630. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  11631. if (!state) {
  11632. state = value ? 0 : 1;
  11633. continue;
  11634. }
  11635. if (state === 1) {
  11636. state = value ? 0 : 2;
  11637. continue;
  11638. }
  11639. // here we have state either equal to 2 or 3
  11640. if (!value) {
  11641. state = 3;
  11642. } else if (value === 1) {
  11643. overflow = i - state - 1;
  11644. if (lastUnitStart >= 0) {
  11645. const unit = {
  11646. data: array.subarray(lastUnitStart, overflow),
  11647. type: lastUnitType
  11648. };
  11649. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  11650. units.push(unit);
  11651. } else {
  11652. // lastUnitStart is undefined => this is the first start code found in this PES packet
  11653. // first check if start code delimiter is overlapping between 2 PES packets,
  11654. // ie it started in last packet (lastState not zero)
  11655. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  11656. const lastUnit = this.getLastNalUnit(track.samples);
  11657. if (lastUnit) {
  11658. if (lastState && i <= 4 - lastState) {
  11659. // start delimiter overlapping between PES packets
  11660. // strip start delimiter bytes from the end of last NAL unit
  11661. // check if lastUnit had a state different from zero
  11662. if (lastUnit.state) {
  11663. // strip last bytes
  11664. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  11665. }
  11666. }
  11667. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  11668. if (overflow > 0) {
  11669. // logger.log('first NALU found with overflow:' + overflow);
  11670. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  11671. lastUnit.state = 0;
  11672. }
  11673. }
  11674. }
  11675. // check if we can read unit type
  11676. if (i < len) {
  11677. unitType = array[i] & 0x1f;
  11678. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  11679. lastUnitStart = i;
  11680. lastUnitType = unitType;
  11681. state = 0;
  11682. } else {
  11683. // not enough byte to read unit type. let's read it on next PES parsing
  11684. state = -1;
  11685. }
  11686. } else {
  11687. state = 0;
  11688. }
  11689. }
  11690. if (lastUnitStart >= 0 && state >= 0) {
  11691. const unit = {
  11692. data: array.subarray(lastUnitStart, len),
  11693. type: lastUnitType,
  11694. state: state
  11695. };
  11696. units.push(unit);
  11697. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  11698. }
  11699. // no NALu found
  11700. if (units.length === 0) {
  11701. // append pes.data to previous NAL unit
  11702. const lastUnit = this.getLastNalUnit(track.samples);
  11703. if (lastUnit) {
  11704. lastUnit.data = appendUint8Array(lastUnit.data, array);
  11705. }
  11706. }
  11707. track.naluState = state;
  11708. return units;
  11709. }
  11710. }
  11711. /**
  11712. * SAMPLE-AES decrypter
  11713. */
  11714. class SampleAesDecrypter {
  11715. constructor(observer, config, keyData) {
  11716. this.keyData = void 0;
  11717. this.decrypter = void 0;
  11718. this.keyData = keyData;
  11719. this.decrypter = new Decrypter(config, {
  11720. removePKCS7Padding: false
  11721. });
  11722. }
  11723. decryptBuffer(encryptedData) {
  11724. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  11725. }
  11726. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  11727. decryptAacSample(samples, sampleIndex, callback) {
  11728. const curUnit = samples[sampleIndex].unit;
  11729. if (curUnit.length <= 16) {
  11730. // No encrypted portion in this sample (first 16 bytes is not
  11731. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  11732. return;
  11733. }
  11734. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  11735. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  11736. this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {
  11737. const decryptedData = new Uint8Array(decryptedBuffer);
  11738. curUnit.set(decryptedData, 16);
  11739. if (!this.decrypter.isSync()) {
  11740. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  11741. }
  11742. });
  11743. }
  11744. decryptAacSamples(samples, sampleIndex, callback) {
  11745. for (;; sampleIndex++) {
  11746. if (sampleIndex >= samples.length) {
  11747. callback();
  11748. return;
  11749. }
  11750. if (samples[sampleIndex].unit.length < 32) {
  11751. continue;
  11752. }
  11753. this.decryptAacSample(samples, sampleIndex, callback);
  11754. if (!this.decrypter.isSync()) {
  11755. return;
  11756. }
  11757. }
  11758. }
  11759. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  11760. getAvcEncryptedData(decodedData) {
  11761. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  11762. const encryptedData = new Int8Array(encryptedDataLen);
  11763. let outputPos = 0;
  11764. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  11765. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  11766. }
  11767. return encryptedData;
  11768. }
  11769. getAvcDecryptedUnit(decodedData, decryptedData) {
  11770. const uint8DecryptedData = new Uint8Array(decryptedData);
  11771. let inputPos = 0;
  11772. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  11773. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  11774. }
  11775. return decodedData;
  11776. }
  11777. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  11778. const decodedData = discardEPB(curUnit.data);
  11779. const encryptedData = this.getAvcEncryptedData(decodedData);
  11780. this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {
  11781. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  11782. if (!this.decrypter.isSync()) {
  11783. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  11784. }
  11785. });
  11786. }
  11787. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  11788. if (samples instanceof Uint8Array) {
  11789. throw new Error('Cannot decrypt samples of type Uint8Array');
  11790. }
  11791. for (;; sampleIndex++, unitIndex = 0) {
  11792. if (sampleIndex >= samples.length) {
  11793. callback();
  11794. return;
  11795. }
  11796. const curUnits = samples[sampleIndex].units;
  11797. for (;; unitIndex++) {
  11798. if (unitIndex >= curUnits.length) {
  11799. break;
  11800. }
  11801. const curUnit = curUnits[unitIndex];
  11802. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  11803. continue;
  11804. }
  11805. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  11806. if (!this.decrypter.isSync()) {
  11807. return;
  11808. }
  11809. }
  11810. }
  11811. }
  11812. }
  11813. const PACKET_LENGTH = 188;
  11814. class TSDemuxer {
  11815. constructor(observer, config, typeSupported) {
  11816. this.observer = void 0;
  11817. this.config = void 0;
  11818. this.typeSupported = void 0;
  11819. this.sampleAes = null;
  11820. this.pmtParsed = false;
  11821. this.audioCodec = void 0;
  11822. this.videoCodec = void 0;
  11823. this._duration = 0;
  11824. this._pmtId = -1;
  11825. this._videoTrack = void 0;
  11826. this._audioTrack = void 0;
  11827. this._id3Track = void 0;
  11828. this._txtTrack = void 0;
  11829. this.aacOverFlow = null;
  11830. this.remainderData = null;
  11831. this.videoParser = void 0;
  11832. this.observer = observer;
  11833. this.config = config;
  11834. this.typeSupported = typeSupported;
  11835. this.videoParser = new AvcVideoParser();
  11836. }
  11837. static probe(data) {
  11838. const syncOffset = TSDemuxer.syncOffset(data);
  11839. if (syncOffset > 0) {
  11840. logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  11841. }
  11842. return syncOffset !== -1;
  11843. }
  11844. static syncOffset(data) {
  11845. const length = data.length;
  11846. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11847. let i = 0;
  11848. while (i < scanwindow) {
  11849. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  11850. let foundPat = false;
  11851. let packetStart = -1;
  11852. let tsPackets = 0;
  11853. for (let j = i; j < length; j += PACKET_LENGTH) {
  11854. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  11855. tsPackets++;
  11856. if (packetStart === -1) {
  11857. packetStart = j;
  11858. // First sync word found at offset, increase scan length (#5251)
  11859. if (packetStart !== 0) {
  11860. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11861. }
  11862. }
  11863. if (!foundPat) {
  11864. foundPat = parsePID(data, j) === 0;
  11865. }
  11866. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  11867. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11868. return packetStart;
  11869. }
  11870. } else if (tsPackets) {
  11871. // Exit if sync word found, but does not contain contiguous packets
  11872. return -1;
  11873. } else {
  11874. break;
  11875. }
  11876. }
  11877. i++;
  11878. }
  11879. return -1;
  11880. }
  11881. /**
  11882. * Creates a track model internal to demuxer used to drive remuxing input
  11883. */
  11884. static createTrack(type, duration) {
  11885. return {
  11886. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  11887. type,
  11888. id: RemuxerTrackIdConfig[type],
  11889. pid: -1,
  11890. inputTimeScale: 90000,
  11891. sequenceNumber: 0,
  11892. samples: [],
  11893. dropped: 0,
  11894. duration: type === 'audio' ? duration : undefined
  11895. };
  11896. }
  11897. /**
  11898. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  11899. * Resets all internal track instances of the demuxer.
  11900. */
  11901. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11902. this.pmtParsed = false;
  11903. this._pmtId = -1;
  11904. this._videoTrack = TSDemuxer.createTrack('video');
  11905. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  11906. this._id3Track = TSDemuxer.createTrack('id3');
  11907. this._txtTrack = TSDemuxer.createTrack('text');
  11908. this._audioTrack.segmentCodec = 'aac';
  11909. // flush any partial content
  11910. this.aacOverFlow = null;
  11911. this.remainderData = null;
  11912. this.audioCodec = audioCodec;
  11913. this.videoCodec = videoCodec;
  11914. this._duration = trackDuration;
  11915. }
  11916. resetTimeStamp() {}
  11917. resetContiguity() {
  11918. const {
  11919. _audioTrack,
  11920. _videoTrack,
  11921. _id3Track
  11922. } = this;
  11923. if (_audioTrack) {
  11924. _audioTrack.pesData = null;
  11925. }
  11926. if (_videoTrack) {
  11927. _videoTrack.pesData = null;
  11928. }
  11929. if (_id3Track) {
  11930. _id3Track.pesData = null;
  11931. }
  11932. this.aacOverFlow = null;
  11933. this.remainderData = null;
  11934. }
  11935. demux(data, timeOffset, isSampleAes = false, flush = false) {
  11936. if (!isSampleAes) {
  11937. this.sampleAes = null;
  11938. }
  11939. let pes;
  11940. const videoTrack = this._videoTrack;
  11941. const audioTrack = this._audioTrack;
  11942. const id3Track = this._id3Track;
  11943. const textTrack = this._txtTrack;
  11944. let videoPid = videoTrack.pid;
  11945. let videoData = videoTrack.pesData;
  11946. let audioPid = audioTrack.pid;
  11947. let id3Pid = id3Track.pid;
  11948. let audioData = audioTrack.pesData;
  11949. let id3Data = id3Track.pesData;
  11950. let unknownPID = null;
  11951. let pmtParsed = this.pmtParsed;
  11952. let pmtId = this._pmtId;
  11953. let len = data.length;
  11954. if (this.remainderData) {
  11955. data = appendUint8Array(this.remainderData, data);
  11956. len = data.length;
  11957. this.remainderData = null;
  11958. }
  11959. if (len < PACKET_LENGTH && !flush) {
  11960. this.remainderData = data;
  11961. return {
  11962. audioTrack,
  11963. videoTrack,
  11964. id3Track,
  11965. textTrack
  11966. };
  11967. }
  11968. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  11969. len -= (len - syncOffset) % PACKET_LENGTH;
  11970. if (len < data.byteLength && !flush) {
  11971. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11972. }
  11973. // loop through TS packets
  11974. let tsPacketErrors = 0;
  11975. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  11976. if (data[start] === 0x47) {
  11977. const stt = !!(data[start + 1] & 0x40);
  11978. const pid = parsePID(data, start);
  11979. const atf = (data[start + 3] & 0x30) >> 4;
  11980. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  11981. let offset;
  11982. if (atf > 1) {
  11983. offset = start + 5 + data[start + 4];
  11984. // continue if there is only adaptation field
  11985. if (offset === start + PACKET_LENGTH) {
  11986. continue;
  11987. }
  11988. } else {
  11989. offset = start + 4;
  11990. }
  11991. switch (pid) {
  11992. case videoPid:
  11993. if (stt) {
  11994. if (videoData && (pes = parsePES(videoData))) {
  11995. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration);
  11996. }
  11997. videoData = {
  11998. data: [],
  11999. size: 0
  12000. };
  12001. }
  12002. if (videoData) {
  12003. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12004. videoData.size += start + PACKET_LENGTH - offset;
  12005. }
  12006. break;
  12007. case audioPid:
  12008. if (stt) {
  12009. if (audioData && (pes = parsePES(audioData))) {
  12010. switch (audioTrack.segmentCodec) {
  12011. case 'aac':
  12012. this.parseAACPES(audioTrack, pes);
  12013. break;
  12014. case 'mp3':
  12015. this.parseMPEGPES(audioTrack, pes);
  12016. break;
  12017. case 'ac3':
  12018. {
  12019. this.parseAC3PES(audioTrack, pes);
  12020. }
  12021. break;
  12022. }
  12023. }
  12024. audioData = {
  12025. data: [],
  12026. size: 0
  12027. };
  12028. }
  12029. if (audioData) {
  12030. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12031. audioData.size += start + PACKET_LENGTH - offset;
  12032. }
  12033. break;
  12034. case id3Pid:
  12035. if (stt) {
  12036. if (id3Data && (pes = parsePES(id3Data))) {
  12037. this.parseID3PES(id3Track, pes);
  12038. }
  12039. id3Data = {
  12040. data: [],
  12041. size: 0
  12042. };
  12043. }
  12044. if (id3Data) {
  12045. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12046. id3Data.size += start + PACKET_LENGTH - offset;
  12047. }
  12048. break;
  12049. case 0:
  12050. if (stt) {
  12051. offset += data[offset] + 1;
  12052. }
  12053. pmtId = this._pmtId = parsePAT(data, offset);
  12054. // logger.log('PMT PID:' + this._pmtId);
  12055. break;
  12056. case pmtId:
  12057. {
  12058. if (stt) {
  12059. offset += data[offset] + 1;
  12060. }
  12061. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer);
  12062. // only update track id if track PID found while parsing PMT
  12063. // this is to avoid resetting the PID to -1 in case
  12064. // track PID transiently disappears from the stream
  12065. // this could happen in case of transient missing audio samples for example
  12066. // NOTE this is only the PID of the track as found in TS,
  12067. // but we are not using this for MP4 track IDs.
  12068. videoPid = parsedPIDs.videoPid;
  12069. if (videoPid > 0) {
  12070. videoTrack.pid = videoPid;
  12071. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  12072. }
  12073. audioPid = parsedPIDs.audioPid;
  12074. if (audioPid > 0) {
  12075. audioTrack.pid = audioPid;
  12076. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  12077. }
  12078. id3Pid = parsedPIDs.id3Pid;
  12079. if (id3Pid > 0) {
  12080. id3Track.pid = id3Pid;
  12081. }
  12082. if (unknownPID !== null && !pmtParsed) {
  12083. logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  12084. unknownPID = null;
  12085. // we set it to -188, the += 188 in the for loop will reset start to 0
  12086. start = syncOffset - 188;
  12087. }
  12088. pmtParsed = this.pmtParsed = true;
  12089. break;
  12090. }
  12091. case 0x11:
  12092. case 0x1fff:
  12093. break;
  12094. default:
  12095. unknownPID = pid;
  12096. break;
  12097. }
  12098. } else {
  12099. tsPacketErrors++;
  12100. }
  12101. }
  12102. if (tsPacketErrors > 0) {
  12103. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`));
  12104. }
  12105. videoTrack.pesData = videoData;
  12106. audioTrack.pesData = audioData;
  12107. id3Track.pesData = id3Data;
  12108. const demuxResult = {
  12109. audioTrack,
  12110. videoTrack,
  12111. id3Track,
  12112. textTrack
  12113. };
  12114. if (flush) {
  12115. this.extractRemainingSamples(demuxResult);
  12116. }
  12117. return demuxResult;
  12118. }
  12119. flush() {
  12120. const {
  12121. remainderData
  12122. } = this;
  12123. this.remainderData = null;
  12124. let result;
  12125. if (remainderData) {
  12126. result = this.demux(remainderData, -1, false, true);
  12127. } else {
  12128. result = {
  12129. videoTrack: this._videoTrack,
  12130. audioTrack: this._audioTrack,
  12131. id3Track: this._id3Track,
  12132. textTrack: this._txtTrack
  12133. };
  12134. }
  12135. this.extractRemainingSamples(result);
  12136. if (this.sampleAes) {
  12137. return this.decrypt(result, this.sampleAes);
  12138. }
  12139. return result;
  12140. }
  12141. extractRemainingSamples(demuxResult) {
  12142. const {
  12143. audioTrack,
  12144. videoTrack,
  12145. id3Track,
  12146. textTrack
  12147. } = demuxResult;
  12148. const videoData = videoTrack.pesData;
  12149. const audioData = audioTrack.pesData;
  12150. const id3Data = id3Track.pesData;
  12151. // try to parse last PES packets
  12152. let pes;
  12153. if (videoData && (pes = parsePES(videoData))) {
  12154. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration);
  12155. videoTrack.pesData = null;
  12156. } else {
  12157. // either avcData null or PES truncated, keep it for next frag parsing
  12158. videoTrack.pesData = videoData;
  12159. }
  12160. if (audioData && (pes = parsePES(audioData))) {
  12161. switch (audioTrack.segmentCodec) {
  12162. case 'aac':
  12163. this.parseAACPES(audioTrack, pes);
  12164. break;
  12165. case 'mp3':
  12166. this.parseMPEGPES(audioTrack, pes);
  12167. break;
  12168. case 'ac3':
  12169. {
  12170. this.parseAC3PES(audioTrack, pes);
  12171. }
  12172. break;
  12173. }
  12174. audioTrack.pesData = null;
  12175. } else {
  12176. if (audioData != null && audioData.size) {
  12177. logger.log('last AAC PES packet truncated,might overlap between fragments');
  12178. }
  12179. // either audioData null or PES truncated, keep it for next frag parsing
  12180. audioTrack.pesData = audioData;
  12181. }
  12182. if (id3Data && (pes = parsePES(id3Data))) {
  12183. this.parseID3PES(id3Track, pes);
  12184. id3Track.pesData = null;
  12185. } else {
  12186. // either id3Data null or PES truncated, keep it for next frag parsing
  12187. id3Track.pesData = id3Data;
  12188. }
  12189. }
  12190. demuxSampleAes(data, keyData, timeOffset) {
  12191. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  12192. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  12193. return this.decrypt(demuxResult, sampleAes);
  12194. }
  12195. decrypt(demuxResult, sampleAes) {
  12196. return new Promise(resolve => {
  12197. const {
  12198. audioTrack,
  12199. videoTrack
  12200. } = demuxResult;
  12201. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  12202. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  12203. if (videoTrack.samples) {
  12204. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  12205. resolve(demuxResult);
  12206. });
  12207. } else {
  12208. resolve(demuxResult);
  12209. }
  12210. });
  12211. } else if (videoTrack.samples) {
  12212. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  12213. resolve(demuxResult);
  12214. });
  12215. }
  12216. });
  12217. }
  12218. destroy() {
  12219. this._duration = 0;
  12220. }
  12221. parseAACPES(track, pes) {
  12222. let startOffset = 0;
  12223. const aacOverFlow = this.aacOverFlow;
  12224. let data = pes.data;
  12225. if (aacOverFlow) {
  12226. this.aacOverFlow = null;
  12227. const frameMissingBytes = aacOverFlow.missing;
  12228. const sampleLength = aacOverFlow.sample.unit.byteLength;
  12229. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  12230. if (frameMissingBytes === -1) {
  12231. data = appendUint8Array(aacOverFlow.sample.unit, data);
  12232. } else {
  12233. const frameOverflowBytes = sampleLength - frameMissingBytes;
  12234. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  12235. track.samples.push(aacOverFlow.sample);
  12236. startOffset = aacOverFlow.missing;
  12237. }
  12238. }
  12239. // look for ADTS header (0xFFFx)
  12240. let offset;
  12241. let len;
  12242. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  12243. if (isHeader$1(data, offset)) {
  12244. break;
  12245. }
  12246. }
  12247. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  12248. if (offset !== startOffset) {
  12249. let reason;
  12250. const recoverable = offset < len - 1;
  12251. if (recoverable) {
  12252. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  12253. } else {
  12254. reason = 'No ADTS header found in AAC PES';
  12255. }
  12256. emitParsingError(this.observer, new Error(reason), recoverable);
  12257. if (!recoverable) {
  12258. return;
  12259. }
  12260. }
  12261. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  12262. let pts;
  12263. if (pes.pts !== undefined) {
  12264. pts = pes.pts;
  12265. } else if (aacOverFlow) {
  12266. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  12267. // first sample PTS should be equal to last sample PTS + frameDuration
  12268. const frameDuration = getFrameDuration(track.samplerate);
  12269. pts = aacOverFlow.sample.pts + frameDuration;
  12270. } else {
  12271. logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  12272. return;
  12273. }
  12274. // scan for aac samples
  12275. let frameIndex = 0;
  12276. let frame;
  12277. while (offset < len) {
  12278. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  12279. offset += frame.length;
  12280. if (!frame.missing) {
  12281. frameIndex++;
  12282. for (; offset < len - 1; offset++) {
  12283. if (isHeader$1(data, offset)) {
  12284. break;
  12285. }
  12286. }
  12287. } else {
  12288. this.aacOverFlow = frame;
  12289. break;
  12290. }
  12291. }
  12292. }
  12293. parseMPEGPES(track, pes) {
  12294. const data = pes.data;
  12295. const length = data.length;
  12296. let frameIndex = 0;
  12297. let offset = 0;
  12298. const pts = pes.pts;
  12299. if (pts === undefined) {
  12300. logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  12301. return;
  12302. }
  12303. while (offset < length) {
  12304. if (isHeader(data, offset)) {
  12305. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  12306. if (frame) {
  12307. offset += frame.length;
  12308. frameIndex++;
  12309. } else {
  12310. // logger.log('Unable to parse Mpeg audio frame');
  12311. break;
  12312. }
  12313. } else {
  12314. // nothing found, keep looking
  12315. offset++;
  12316. }
  12317. }
  12318. }
  12319. parseAC3PES(track, pes) {
  12320. {
  12321. const data = pes.data;
  12322. const pts = pes.pts;
  12323. if (pts === undefined) {
  12324. logger.warn('[tsdemuxer]: AC3 PES unknown PTS');
  12325. return;
  12326. }
  12327. const length = data.length;
  12328. let frameIndex = 0;
  12329. let offset = 0;
  12330. let parsed;
  12331. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  12332. offset += parsed;
  12333. }
  12334. }
  12335. }
  12336. parseID3PES(id3Track, pes) {
  12337. if (pes.pts === undefined) {
  12338. logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  12339. return;
  12340. }
  12341. const id3Sample = _extends({}, pes, {
  12342. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  12343. duration: Number.POSITIVE_INFINITY
  12344. });
  12345. id3Track.samples.push(id3Sample);
  12346. }
  12347. }
  12348. function parsePID(data, offset) {
  12349. // pid is a 13-bit field starting at the last bit of TS[1]
  12350. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  12351. }
  12352. function parsePAT(data, offset) {
  12353. // skip the PSI header and parse the first PMT entry
  12354. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  12355. }
  12356. function parsePMT(data, offset, typeSupported, isSampleAes, observer) {
  12357. const result = {
  12358. audioPid: -1,
  12359. videoPid: -1,
  12360. id3Pid: -1,
  12361. segmentVideoCodec: 'avc',
  12362. segmentAudioCodec: 'aac'
  12363. };
  12364. const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  12365. const tableEnd = offset + 3 + sectionLength - 4;
  12366. // to determine where the table is, we have to figure out how
  12367. // long the program info descriptors are
  12368. const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  12369. // advance the offset to the first entry in the mapping table
  12370. offset += 12 + programInfoLength;
  12371. while (offset < tableEnd) {
  12372. const pid = parsePID(data, offset);
  12373. const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  12374. switch (data[offset]) {
  12375. case 0xcf:
  12376. // SAMPLE-AES AAC
  12377. if (!isSampleAes) {
  12378. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');
  12379. break;
  12380. }
  12381. /* falls through */
  12382. case 0x0f:
  12383. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  12384. // logger.log('AAC PID:' + pid);
  12385. if (result.audioPid === -1) {
  12386. result.audioPid = pid;
  12387. }
  12388. break;
  12389. // Packetized metadata (ID3)
  12390. case 0x15:
  12391. // logger.log('ID3 PID:' + pid);
  12392. if (result.id3Pid === -1) {
  12393. result.id3Pid = pid;
  12394. }
  12395. break;
  12396. case 0xdb:
  12397. // SAMPLE-AES AVC
  12398. if (!isSampleAes) {
  12399. logEncryptedSamplesFoundInUnencryptedStream('H.264');
  12400. break;
  12401. }
  12402. /* falls through */
  12403. case 0x1b:
  12404. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  12405. // logger.log('AVC PID:' + pid);
  12406. if (result.videoPid === -1) {
  12407. result.videoPid = pid;
  12408. result.segmentVideoCodec = 'avc';
  12409. }
  12410. break;
  12411. // ISO/IEC 11172-3 (MPEG-1 audio)
  12412. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  12413. case 0x03:
  12414. case 0x04:
  12415. // logger.log('MPEG PID:' + pid);
  12416. if (!typeSupported.mpeg && !typeSupported.mp3) {
  12417. logger.log('MPEG audio found, not supported in this browser');
  12418. } else if (result.audioPid === -1) {
  12419. result.audioPid = pid;
  12420. result.segmentAudioCodec = 'mp3';
  12421. }
  12422. break;
  12423. case 0xc1:
  12424. // SAMPLE-AES AC3
  12425. if (!isSampleAes) {
  12426. logEncryptedSamplesFoundInUnencryptedStream('AC-3');
  12427. break;
  12428. }
  12429. /* falls through */
  12430. case 0x81:
  12431. {
  12432. if (!typeSupported.ac3) {
  12433. logger.log('AC-3 audio found, not supported in this browser');
  12434. } else if (result.audioPid === -1) {
  12435. result.audioPid = pid;
  12436. result.segmentAudioCodec = 'ac3';
  12437. }
  12438. }
  12439. break;
  12440. case 0x06:
  12441. // stream_type 6 can mean a lot of different things in case of DVB.
  12442. // We need to look at the descriptors. Right now, we're only interested
  12443. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  12444. // an audio PID yet.
  12445. if (result.audioPid === -1 && esInfoLength > 0) {
  12446. let parsePos = offset + 5;
  12447. let remaining = esInfoLength;
  12448. while (remaining > 2) {
  12449. const descriptorId = data[parsePos];
  12450. switch (descriptorId) {
  12451. case 0x6a:
  12452. // DVB Descriptor for AC-3
  12453. {
  12454. if (typeSupported.ac3 !== true) {
  12455. logger.log('AC-3 audio found, not supported in this browser for now');
  12456. } else {
  12457. result.audioPid = pid;
  12458. result.segmentAudioCodec = 'ac3';
  12459. }
  12460. }
  12461. break;
  12462. }
  12463. const descriptorLen = data[parsePos + 1] + 2;
  12464. parsePos += descriptorLen;
  12465. remaining -= descriptorLen;
  12466. }
  12467. }
  12468. break;
  12469. case 0xc2: // SAMPLE-AES EC3
  12470. /* falls through */
  12471. case 0x87:
  12472. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));
  12473. return result;
  12474. case 0x24:
  12475. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));
  12476. return result;
  12477. }
  12478. // move to the next table entry
  12479. // skip past the elementary stream descriptors, if present
  12480. offset += esInfoLength + 5;
  12481. }
  12482. return result;
  12483. }
  12484. function emitParsingError(observer, error, levelRetry) {
  12485. logger.warn(`parsing error: ${error.message}`);
  12486. observer.emit(Events.ERROR, Events.ERROR, {
  12487. type: ErrorTypes.MEDIA_ERROR,
  12488. details: ErrorDetails.FRAG_PARSING_ERROR,
  12489. fatal: false,
  12490. levelRetry,
  12491. error,
  12492. reason: error.message
  12493. });
  12494. }
  12495. function logEncryptedSamplesFoundInUnencryptedStream(type) {
  12496. logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  12497. }
  12498. function parsePES(stream) {
  12499. let i = 0;
  12500. let frag;
  12501. let pesLen;
  12502. let pesHdrLen;
  12503. let pesPts;
  12504. let pesDts;
  12505. const data = stream.data;
  12506. // safety check
  12507. if (!stream || stream.size === 0) {
  12508. return null;
  12509. }
  12510. // we might need up to 19 bytes to read PES header
  12511. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  12512. // usually only one merge is needed (and this is rare ...)
  12513. while (data[0].length < 19 && data.length > 1) {
  12514. data[0] = appendUint8Array(data[0], data[1]);
  12515. data.splice(1, 1);
  12516. }
  12517. // retrieve PTS/DTS from first fragment
  12518. frag = data[0];
  12519. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  12520. if (pesPrefix === 1) {
  12521. pesLen = (frag[4] << 8) + frag[5];
  12522. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  12523. // minus 6 : PES header size
  12524. if (pesLen && pesLen > stream.size - 6) {
  12525. return null;
  12526. }
  12527. const pesFlags = frag[7];
  12528. if (pesFlags & 0xc0) {
  12529. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  12530. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  12531. as Bitwise operators treat their operands as a sequence of 32 bits */
  12532. pesPts = (frag[9] & 0x0e) * 536870912 +
  12533. // 1 << 29
  12534. (frag[10] & 0xff) * 4194304 +
  12535. // 1 << 22
  12536. (frag[11] & 0xfe) * 16384 +
  12537. // 1 << 14
  12538. (frag[12] & 0xff) * 128 +
  12539. // 1 << 7
  12540. (frag[13] & 0xfe) / 2;
  12541. if (pesFlags & 0x40) {
  12542. pesDts = (frag[14] & 0x0e) * 536870912 +
  12543. // 1 << 29
  12544. (frag[15] & 0xff) * 4194304 +
  12545. // 1 << 22
  12546. (frag[16] & 0xfe) * 16384 +
  12547. // 1 << 14
  12548. (frag[17] & 0xff) * 128 +
  12549. // 1 << 7
  12550. (frag[18] & 0xfe) / 2;
  12551. if (pesPts - pesDts > 60 * 90000) {
  12552. logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);
  12553. pesPts = pesDts;
  12554. }
  12555. } else {
  12556. pesDts = pesPts;
  12557. }
  12558. }
  12559. pesHdrLen = frag[8];
  12560. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  12561. let payloadStartOffset = pesHdrLen + 9;
  12562. if (stream.size <= payloadStartOffset) {
  12563. return null;
  12564. }
  12565. stream.size -= payloadStartOffset;
  12566. // reassemble PES packet
  12567. const pesData = new Uint8Array(stream.size);
  12568. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  12569. frag = data[j];
  12570. let len = frag.byteLength;
  12571. if (payloadStartOffset) {
  12572. if (payloadStartOffset > len) {
  12573. // trim full frag if PES header bigger than frag
  12574. payloadStartOffset -= len;
  12575. continue;
  12576. } else {
  12577. // trim partial frag if PES header smaller than frag
  12578. frag = frag.subarray(payloadStartOffset);
  12579. len -= payloadStartOffset;
  12580. payloadStartOffset = 0;
  12581. }
  12582. }
  12583. pesData.set(frag, i);
  12584. i += len;
  12585. }
  12586. if (pesLen) {
  12587. // payload size : remove PES header + PES extension
  12588. pesLen -= pesHdrLen + 3;
  12589. }
  12590. return {
  12591. data: pesData,
  12592. pts: pesPts,
  12593. dts: pesDts,
  12594. len: pesLen
  12595. };
  12596. }
  12597. return null;
  12598. }
  12599. /**
  12600. * MP3 demuxer
  12601. */
  12602. class MP3Demuxer extends BaseAudioDemuxer {
  12603. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12604. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  12605. this._audioTrack = {
  12606. container: 'audio/mpeg',
  12607. type: 'audio',
  12608. id: 2,
  12609. pid: -1,
  12610. sequenceNumber: 0,
  12611. segmentCodec: 'mp3',
  12612. samples: [],
  12613. manifestCodec: audioCodec,
  12614. duration: trackDuration,
  12615. inputTimeScale: 90000,
  12616. dropped: 0
  12617. };
  12618. }
  12619. static probe(data) {
  12620. if (!data) {
  12621. return false;
  12622. }
  12623. // check if data contains ID3 timestamp and MPEG sync word
  12624. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  12625. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  12626. // More info http://www.mp3-tech.org/programmer/frame_header.html
  12627. const id3Data = getID3Data(data, 0);
  12628. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  12629. // Check for ac-3|ec-3 sync bytes and return false if present
  12630. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  12631. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  12632. getAudioBSID(data, offset) <= 16) {
  12633. return false;
  12634. }
  12635. for (let length = data.length; offset < length; offset++) {
  12636. if (probe(data, offset)) {
  12637. logger.log('MPEG Audio sync word found !');
  12638. return true;
  12639. }
  12640. }
  12641. return false;
  12642. }
  12643. canParse(data, offset) {
  12644. return canParse(data, offset);
  12645. }
  12646. appendFrame(track, data, offset) {
  12647. if (this.basePTS === null) {
  12648. return;
  12649. }
  12650. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  12651. }
  12652. }
  12653. /**
  12654. * AAC helper
  12655. */
  12656. class AAC {
  12657. static getSilentFrame(codec, channelCount) {
  12658. switch (codec) {
  12659. case 'mp4a.40.2':
  12660. if (channelCount === 1) {
  12661. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  12662. } else if (channelCount === 2) {
  12663. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  12664. } else if (channelCount === 3) {
  12665. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  12666. } else if (channelCount === 4) {
  12667. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  12668. } else if (channelCount === 5) {
  12669. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  12670. } else if (channelCount === 6) {
  12671. 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]);
  12672. }
  12673. break;
  12674. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  12675. default:
  12676. if (channelCount === 1) {
  12677. // 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
  12678. 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]);
  12679. } else if (channelCount === 2) {
  12680. // 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
  12681. 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]);
  12682. } else if (channelCount === 3) {
  12683. // 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
  12684. 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]);
  12685. }
  12686. break;
  12687. }
  12688. return undefined;
  12689. }
  12690. }
  12691. /**
  12692. * Generate MP4 Box
  12693. */
  12694. const UINT32_MAX = Math.pow(2, 32) - 1;
  12695. class MP4 {
  12696. static init() {
  12697. MP4.types = {
  12698. avc1: [],
  12699. // codingname
  12700. avcC: [],
  12701. btrt: [],
  12702. dinf: [],
  12703. dref: [],
  12704. esds: [],
  12705. ftyp: [],
  12706. hdlr: [],
  12707. mdat: [],
  12708. mdhd: [],
  12709. mdia: [],
  12710. mfhd: [],
  12711. minf: [],
  12712. moof: [],
  12713. moov: [],
  12714. mp4a: [],
  12715. '.mp3': [],
  12716. dac3: [],
  12717. 'ac-3': [],
  12718. mvex: [],
  12719. mvhd: [],
  12720. pasp: [],
  12721. sdtp: [],
  12722. stbl: [],
  12723. stco: [],
  12724. stsc: [],
  12725. stsd: [],
  12726. stsz: [],
  12727. stts: [],
  12728. tfdt: [],
  12729. tfhd: [],
  12730. traf: [],
  12731. trak: [],
  12732. trun: [],
  12733. trex: [],
  12734. tkhd: [],
  12735. vmhd: [],
  12736. smhd: []
  12737. };
  12738. let i;
  12739. for (i in MP4.types) {
  12740. if (MP4.types.hasOwnProperty(i)) {
  12741. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  12742. }
  12743. }
  12744. const videoHdlr = new Uint8Array([0x00,
  12745. // version 0
  12746. 0x00, 0x00, 0x00,
  12747. // flags
  12748. 0x00, 0x00, 0x00, 0x00,
  12749. // pre_defined
  12750. 0x76, 0x69, 0x64, 0x65,
  12751. // handler_type: 'vide'
  12752. 0x00, 0x00, 0x00, 0x00,
  12753. // reserved
  12754. 0x00, 0x00, 0x00, 0x00,
  12755. // reserved
  12756. 0x00, 0x00, 0x00, 0x00,
  12757. // reserved
  12758. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  12759. ]);
  12760. const audioHdlr = new Uint8Array([0x00,
  12761. // version 0
  12762. 0x00, 0x00, 0x00,
  12763. // flags
  12764. 0x00, 0x00, 0x00, 0x00,
  12765. // pre_defined
  12766. 0x73, 0x6f, 0x75, 0x6e,
  12767. // handler_type: 'soun'
  12768. 0x00, 0x00, 0x00, 0x00,
  12769. // reserved
  12770. 0x00, 0x00, 0x00, 0x00,
  12771. // reserved
  12772. 0x00, 0x00, 0x00, 0x00,
  12773. // reserved
  12774. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  12775. ]);
  12776. MP4.HDLR_TYPES = {
  12777. video: videoHdlr,
  12778. audio: audioHdlr
  12779. };
  12780. const dref = new Uint8Array([0x00,
  12781. // version 0
  12782. 0x00, 0x00, 0x00,
  12783. // flags
  12784. 0x00, 0x00, 0x00, 0x01,
  12785. // entry_count
  12786. 0x00, 0x00, 0x00, 0x0c,
  12787. // entry_size
  12788. 0x75, 0x72, 0x6c, 0x20,
  12789. // 'url' type
  12790. 0x00,
  12791. // version 0
  12792. 0x00, 0x00, 0x01 // entry_flags
  12793. ]);
  12794. const stco = new Uint8Array([0x00,
  12795. // version
  12796. 0x00, 0x00, 0x00,
  12797. // flags
  12798. 0x00, 0x00, 0x00, 0x00 // entry_count
  12799. ]);
  12800. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  12801. MP4.STSZ = new Uint8Array([0x00,
  12802. // version
  12803. 0x00, 0x00, 0x00,
  12804. // flags
  12805. 0x00, 0x00, 0x00, 0x00,
  12806. // sample_size
  12807. 0x00, 0x00, 0x00, 0x00 // sample_count
  12808. ]);
  12809. MP4.VMHD = new Uint8Array([0x00,
  12810. // version
  12811. 0x00, 0x00, 0x01,
  12812. // flags
  12813. 0x00, 0x00,
  12814. // graphicsmode
  12815. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  12816. ]);
  12817. MP4.SMHD = new Uint8Array([0x00,
  12818. // version
  12819. 0x00, 0x00, 0x00,
  12820. // flags
  12821. 0x00, 0x00,
  12822. // balance
  12823. 0x00, 0x00 // reserved
  12824. ]);
  12825. MP4.STSD = new Uint8Array([0x00,
  12826. // version 0
  12827. 0x00, 0x00, 0x00,
  12828. // flags
  12829. 0x00, 0x00, 0x00, 0x01]); // entry_count
  12830. const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  12831. const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  12832. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  12833. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  12834. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  12835. }
  12836. static box(type, ...payload) {
  12837. let size = 8;
  12838. let i = payload.length;
  12839. const len = i;
  12840. // calculate the total size we need to allocate
  12841. while (i--) {
  12842. size += payload[i].byteLength;
  12843. }
  12844. const result = new Uint8Array(size);
  12845. result[0] = size >> 24 & 0xff;
  12846. result[1] = size >> 16 & 0xff;
  12847. result[2] = size >> 8 & 0xff;
  12848. result[3] = size & 0xff;
  12849. result.set(type, 4);
  12850. // copy the payload into the result
  12851. for (i = 0, size = 8; i < len; i++) {
  12852. // copy payload[i] array @ offset size
  12853. result.set(payload[i], size);
  12854. size += payload[i].byteLength;
  12855. }
  12856. return result;
  12857. }
  12858. static hdlr(type) {
  12859. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  12860. }
  12861. static mdat(data) {
  12862. return MP4.box(MP4.types.mdat, data);
  12863. }
  12864. static mdhd(timescale, duration) {
  12865. duration *= timescale;
  12866. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12867. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12868. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  12869. // version 1
  12870. 0x00, 0x00, 0x00,
  12871. // flags
  12872. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12873. // creation_time
  12874. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12875. // modification_time
  12876. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12877. // timescale
  12878. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  12879. // 'und' language (undetermined)
  12880. 0x00, 0x00]));
  12881. }
  12882. static mdia(track) {
  12883. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  12884. }
  12885. static mfhd(sequenceNumber) {
  12886. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  12887. // flags
  12888. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  12889. ]));
  12890. }
  12891. static minf(track) {
  12892. if (track.type === 'audio') {
  12893. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  12894. } else {
  12895. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  12896. }
  12897. }
  12898. static moof(sn, baseMediaDecodeTime, track) {
  12899. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  12900. }
  12901. static moov(tracks) {
  12902. let i = tracks.length;
  12903. const boxes = [];
  12904. while (i--) {
  12905. boxes[i] = MP4.trak(tracks[i]);
  12906. }
  12907. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  12908. }
  12909. static mvex(tracks) {
  12910. let i = tracks.length;
  12911. const boxes = [];
  12912. while (i--) {
  12913. boxes[i] = MP4.trex(tracks[i]);
  12914. }
  12915. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  12916. }
  12917. static mvhd(timescale, duration) {
  12918. duration *= timescale;
  12919. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12920. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12921. const bytes = new Uint8Array([0x01,
  12922. // version 1
  12923. 0x00, 0x00, 0x00,
  12924. // flags
  12925. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12926. // creation_time
  12927. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12928. // modification_time
  12929. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12930. // timescale
  12931. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  12932. // 1.0 rate
  12933. 0x01, 0x00,
  12934. // 1.0 volume
  12935. 0x00, 0x00,
  12936. // reserved
  12937. 0x00, 0x00, 0x00, 0x00,
  12938. // reserved
  12939. 0x00, 0x00, 0x00, 0x00,
  12940. // reserved
  12941. 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,
  12942. // transformation: unity matrix
  12943. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12944. // pre_defined
  12945. 0xff, 0xff, 0xff, 0xff // next_track_ID
  12946. ]);
  12947. return MP4.box(MP4.types.mvhd, bytes);
  12948. }
  12949. static sdtp(track) {
  12950. const samples = track.samples || [];
  12951. const bytes = new Uint8Array(4 + samples.length);
  12952. let i;
  12953. let flags;
  12954. // leave the full box header (4 bytes) all zero
  12955. // write the sample table
  12956. for (i = 0; i < samples.length; i++) {
  12957. flags = samples[i].flags;
  12958. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12959. }
  12960. return MP4.box(MP4.types.sdtp, bytes);
  12961. }
  12962. static stbl(track) {
  12963. 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));
  12964. }
  12965. static avc1(track) {
  12966. let sps = [];
  12967. let pps = [];
  12968. let i;
  12969. let data;
  12970. let len;
  12971. // assemble the SPSs
  12972. for (i = 0; i < track.sps.length; i++) {
  12973. data = track.sps[i];
  12974. len = data.byteLength;
  12975. sps.push(len >>> 8 & 0xff);
  12976. sps.push(len & 0xff);
  12977. // SPS
  12978. sps = sps.concat(Array.prototype.slice.call(data));
  12979. }
  12980. // assemble the PPSs
  12981. for (i = 0; i < track.pps.length; i++) {
  12982. data = track.pps[i];
  12983. len = data.byteLength;
  12984. pps.push(len >>> 8 & 0xff);
  12985. pps.push(len & 0xff);
  12986. pps = pps.concat(Array.prototype.slice.call(data));
  12987. }
  12988. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  12989. // version
  12990. sps[3],
  12991. // profile
  12992. sps[4],
  12993. // profile compat
  12994. sps[5],
  12995. // level
  12996. 0xfc | 3,
  12997. // lengthSizeMinusOne, hard-coded to 4 bytes
  12998. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  12999. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  13000. ]).concat(pps))); // "PPS"
  13001. const width = track.width;
  13002. const height = track.height;
  13003. const hSpacing = track.pixelRatio[0];
  13004. const vSpacing = track.pixelRatio[1];
  13005. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  13006. // reserved
  13007. 0x00, 0x00, 0x00,
  13008. // reserved
  13009. 0x00, 0x01,
  13010. // data_reference_index
  13011. 0x00, 0x00,
  13012. // pre_defined
  13013. 0x00, 0x00,
  13014. // reserved
  13015. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13016. // pre_defined
  13017. width >> 8 & 0xff, width & 0xff,
  13018. // width
  13019. height >> 8 & 0xff, height & 0xff,
  13020. // height
  13021. 0x00, 0x48, 0x00, 0x00,
  13022. // horizresolution
  13023. 0x00, 0x48, 0x00, 0x00,
  13024. // vertresolution
  13025. 0x00, 0x00, 0x00, 0x00,
  13026. // reserved
  13027. 0x00, 0x01,
  13028. // frame_count
  13029. 0x12, 0x64, 0x61, 0x69, 0x6c,
  13030. // dailymotion/hls.js
  13031. 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,
  13032. // compressorname
  13033. 0x00, 0x18,
  13034. // depth = 24
  13035. 0x11, 0x11]),
  13036. // pre_defined = -1
  13037. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  13038. // bufferSizeDB
  13039. 0x00, 0x2d, 0xc6, 0xc0,
  13040. // maxBitrate
  13041. 0x00, 0x2d, 0xc6, 0xc0])),
  13042. // avgBitrate
  13043. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  13044. // hSpacing
  13045. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  13046. // vSpacing
  13047. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  13048. }
  13049. static esds(track) {
  13050. const configlen = track.config.length;
  13051. return new Uint8Array([0x00,
  13052. // version 0
  13053. 0x00, 0x00, 0x00,
  13054. // flags
  13055. 0x03,
  13056. // descriptor_type
  13057. 0x17 + configlen,
  13058. // length
  13059. 0x00, 0x01,
  13060. // es_id
  13061. 0x00,
  13062. // stream_priority
  13063. 0x04,
  13064. // descriptor_type
  13065. 0x0f + configlen,
  13066. // length
  13067. 0x40,
  13068. // codec : mpeg4_audio
  13069. 0x15,
  13070. // stream_type
  13071. 0x00, 0x00, 0x00,
  13072. // buffer_size
  13073. 0x00, 0x00, 0x00, 0x00,
  13074. // maxBitrate
  13075. 0x00, 0x00, 0x00, 0x00,
  13076. // avgBitrate
  13077. 0x05 // descriptor_type
  13078. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  13079. }
  13080. static audioStsd(track) {
  13081. const samplerate = track.samplerate;
  13082. return new Uint8Array([0x00, 0x00, 0x00,
  13083. // reserved
  13084. 0x00, 0x00, 0x00,
  13085. // reserved
  13086. 0x00, 0x01,
  13087. // data_reference_index
  13088. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13089. // reserved
  13090. 0x00, track.channelCount,
  13091. // channelcount
  13092. 0x00, 0x10,
  13093. // sampleSize:16bits
  13094. 0x00, 0x00, 0x00, 0x00,
  13095. // reserved2
  13096. samplerate >> 8 & 0xff, samplerate & 0xff,
  13097. //
  13098. 0x00, 0x00]);
  13099. }
  13100. static mp4a(track) {
  13101. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  13102. }
  13103. static mp3(track) {
  13104. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  13105. }
  13106. static ac3(track) {
  13107. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  13108. }
  13109. static stsd(track) {
  13110. if (track.type === 'audio') {
  13111. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  13112. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  13113. }
  13114. if (track.segmentCodec === 'ac3') {
  13115. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  13116. }
  13117. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  13118. } else {
  13119. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  13120. }
  13121. }
  13122. static tkhd(track) {
  13123. const id = track.id;
  13124. const duration = track.duration * track.timescale;
  13125. const width = track.width;
  13126. const height = track.height;
  13127. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13128. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13129. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  13130. // version 1
  13131. 0x00, 0x00, 0x07,
  13132. // flags
  13133. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13134. // creation_time
  13135. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13136. // modification_time
  13137. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  13138. // track_ID
  13139. 0x00, 0x00, 0x00, 0x00,
  13140. // reserved
  13141. 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,
  13142. // reserved
  13143. 0x00, 0x00,
  13144. // layer
  13145. 0x00, 0x00,
  13146. // alternate_group
  13147. 0x00, 0x00,
  13148. // non-audio track volume
  13149. 0x00, 0x00,
  13150. // reserved
  13151. 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,
  13152. // transformation: unity matrix
  13153. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  13154. // width
  13155. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  13156. ]));
  13157. }
  13158. static traf(track, baseMediaDecodeTime) {
  13159. const sampleDependencyTable = MP4.sdtp(track);
  13160. const id = track.id;
  13161. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  13162. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  13163. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  13164. // version 0
  13165. 0x00, 0x00, 0x00,
  13166. // flags
  13167. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  13168. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  13169. // version 1
  13170. 0x00, 0x00, 0x00,
  13171. // flags
  13172. 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 +
  13173. // tfhd
  13174. 20 +
  13175. // tfdt
  13176. 8 +
  13177. // traf header
  13178. 16 +
  13179. // mfhd
  13180. 8 +
  13181. // moof header
  13182. 8),
  13183. // mdat header
  13184. sampleDependencyTable);
  13185. }
  13186. /**
  13187. * Generate a track box.
  13188. * @param track a track definition
  13189. */
  13190. static trak(track) {
  13191. track.duration = track.duration || 0xffffffff;
  13192. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  13193. }
  13194. static trex(track) {
  13195. const id = track.id;
  13196. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  13197. // version 0
  13198. 0x00, 0x00, 0x00,
  13199. // flags
  13200. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  13201. // track_ID
  13202. 0x00, 0x00, 0x00, 0x01,
  13203. // default_sample_description_index
  13204. 0x00, 0x00, 0x00, 0x00,
  13205. // default_sample_duration
  13206. 0x00, 0x00, 0x00, 0x00,
  13207. // default_sample_size
  13208. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  13209. ]));
  13210. }
  13211. static trun(track, offset) {
  13212. const samples = track.samples || [];
  13213. const len = samples.length;
  13214. const arraylen = 12 + 16 * len;
  13215. const array = new Uint8Array(arraylen);
  13216. let i;
  13217. let sample;
  13218. let duration;
  13219. let size;
  13220. let flags;
  13221. let cts;
  13222. offset += 8 + arraylen;
  13223. array.set([track.type === 'video' ? 0x01 : 0x00,
  13224. // version 1 for video with signed-int sample_composition_time_offset
  13225. 0x00, 0x0f, 0x01,
  13226. // flags
  13227. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  13228. // sample_count
  13229. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  13230. ], 0);
  13231. for (i = 0; i < len; i++) {
  13232. sample = samples[i];
  13233. duration = sample.duration;
  13234. size = sample.size;
  13235. flags = sample.flags;
  13236. cts = sample.cts;
  13237. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  13238. // sample_duration
  13239. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  13240. // sample_size
  13241. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  13242. // sample_flags
  13243. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  13244. ], 12 + 16 * i);
  13245. }
  13246. return MP4.box(MP4.types.trun, array);
  13247. }
  13248. static initSegment(tracks) {
  13249. if (!MP4.types) {
  13250. MP4.init();
  13251. }
  13252. const movie = MP4.moov(tracks);
  13253. const result = appendUint8Array(MP4.FTYP, movie);
  13254. return result;
  13255. }
  13256. }
  13257. MP4.types = void 0;
  13258. MP4.HDLR_TYPES = void 0;
  13259. MP4.STTS = void 0;
  13260. MP4.STSC = void 0;
  13261. MP4.STCO = void 0;
  13262. MP4.STSZ = void 0;
  13263. MP4.VMHD = void 0;
  13264. MP4.SMHD = void 0;
  13265. MP4.STSD = void 0;
  13266. MP4.FTYP = void 0;
  13267. MP4.DINF = void 0;
  13268. const MPEG_TS_CLOCK_FREQ_HZ = 90000;
  13269. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  13270. const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  13271. return round ? Math.round(result) : result;
  13272. }
  13273. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  13274. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  13275. }
  13276. function toMsFromMpegTsClock(baseTime, round = false) {
  13277. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  13278. }
  13279. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  13280. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  13281. }
  13282. const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  13283. const AAC_SAMPLES_PER_FRAME = 1024;
  13284. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  13285. const AC3_SAMPLES_PER_FRAME = 1536;
  13286. let chromeVersion = null;
  13287. let safariWebkitVersion = null;
  13288. class MP4Remuxer {
  13289. constructor(observer, config, typeSupported, vendor = '') {
  13290. this.observer = void 0;
  13291. this.config = void 0;
  13292. this.typeSupported = void 0;
  13293. this.ISGenerated = false;
  13294. this._initPTS = null;
  13295. this._initDTS = null;
  13296. this.nextAvcDts = null;
  13297. this.nextAudioPts = null;
  13298. this.videoSampleDuration = null;
  13299. this.isAudioContiguous = false;
  13300. this.isVideoContiguous = false;
  13301. this.videoTrackConfig = void 0;
  13302. this.observer = observer;
  13303. this.config = config;
  13304. this.typeSupported = typeSupported;
  13305. this.ISGenerated = false;
  13306. if (chromeVersion === null) {
  13307. const userAgent = navigator.userAgent || '';
  13308. const result = userAgent.match(/Chrome\/(\d+)/i);
  13309. chromeVersion = result ? parseInt(result[1]) : 0;
  13310. }
  13311. if (safariWebkitVersion === null) {
  13312. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  13313. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  13314. }
  13315. }
  13316. destroy() {
  13317. // @ts-ignore
  13318. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  13319. }
  13320. resetTimeStamp(defaultTimeStamp) {
  13321. logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  13322. this._initPTS = this._initDTS = defaultTimeStamp;
  13323. }
  13324. resetNextTimestamp() {
  13325. logger.log('[mp4-remuxer]: reset next timestamp');
  13326. this.isVideoContiguous = false;
  13327. this.isAudioContiguous = false;
  13328. }
  13329. resetInitSegment() {
  13330. logger.log('[mp4-remuxer]: ISGenerated flag reset');
  13331. this.ISGenerated = false;
  13332. this.videoTrackConfig = undefined;
  13333. }
  13334. getVideoStartPts(videoSamples) {
  13335. let rolloverDetected = false;
  13336. const startPTS = videoSamples.reduce((minPTS, sample) => {
  13337. const delta = sample.pts - minPTS;
  13338. if (delta < -4294967296) {
  13339. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  13340. rolloverDetected = true;
  13341. return normalizePts(minPTS, sample.pts);
  13342. } else if (delta > 0) {
  13343. return minPTS;
  13344. } else {
  13345. return sample.pts;
  13346. }
  13347. }, videoSamples[0].pts);
  13348. if (rolloverDetected) {
  13349. logger.debug('PTS rollover detected');
  13350. }
  13351. return startPTS;
  13352. }
  13353. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  13354. let video;
  13355. let audio;
  13356. let initSegment;
  13357. let text;
  13358. let id3;
  13359. let independent;
  13360. let audioTimeOffset = timeOffset;
  13361. let videoTimeOffset = timeOffset;
  13362. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  13363. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  13364. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  13365. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  13366. // then we can remux one track without waiting for the other.
  13367. const hasAudio = audioTrack.pid > -1;
  13368. const hasVideo = videoTrack.pid > -1;
  13369. const length = videoTrack.samples.length;
  13370. const enoughAudioSamples = audioTrack.samples.length > 0;
  13371. const enoughVideoSamples = flush && length > 0 || length > 1;
  13372. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  13373. if (canRemuxAvc) {
  13374. if (this.ISGenerated) {
  13375. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  13376. const config = this.videoTrackConfig;
  13377. 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]))) {
  13378. this.resetInitSegment();
  13379. }
  13380. } else {
  13381. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13382. }
  13383. const isVideoContiguous = this.isVideoContiguous;
  13384. let firstKeyFrameIndex = -1;
  13385. let firstKeyFramePTS;
  13386. if (enoughVideoSamples) {
  13387. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  13388. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  13389. independent = true;
  13390. if (firstKeyFrameIndex > 0) {
  13391. logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  13392. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13393. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  13394. videoTrack.dropped += firstKeyFrameIndex;
  13395. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  13396. firstKeyFramePTS = videoTimeOffset;
  13397. } else if (firstKeyFrameIndex === -1) {
  13398. logger.warn(`[mp4-remuxer]: No keyframe found out of ${length} video samples`);
  13399. independent = false;
  13400. }
  13401. }
  13402. }
  13403. if (this.ISGenerated) {
  13404. if (enoughAudioSamples && enoughVideoSamples) {
  13405. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  13406. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  13407. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  13408. // drift between audio and video streams
  13409. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13410. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  13411. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13412. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13413. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13414. }
  13415. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  13416. if (enoughAudioSamples) {
  13417. // if initSegment was generated without audio samples, regenerate it again
  13418. if (!audioTrack.samplerate) {
  13419. logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  13420. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13421. }
  13422. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  13423. if (enoughVideoSamples) {
  13424. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13425. // if initSegment was generated without video samples, regenerate it again
  13426. if (!videoTrack.inputTimeScale) {
  13427. logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  13428. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13429. }
  13430. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13431. }
  13432. } else if (enoughVideoSamples) {
  13433. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13434. }
  13435. if (video) {
  13436. video.firstKeyFrame = firstKeyFrameIndex;
  13437. video.independent = firstKeyFrameIndex !== -1;
  13438. video.firstKeyFramePTS = firstKeyFramePTS;
  13439. }
  13440. }
  13441. }
  13442. // Allow ID3 and text to remux, even if more audio/video samples are required
  13443. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13444. if (id3Track.samples.length) {
  13445. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13446. }
  13447. if (textTrack.samples.length) {
  13448. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13449. }
  13450. }
  13451. return {
  13452. audio,
  13453. video,
  13454. initSegment,
  13455. independent,
  13456. text,
  13457. id3
  13458. };
  13459. }
  13460. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13461. const audioSamples = audioTrack.samples;
  13462. const videoSamples = videoTrack.samples;
  13463. const typeSupported = this.typeSupported;
  13464. const tracks = {};
  13465. const _initPTS = this._initPTS;
  13466. let computePTSDTS = !_initPTS || accurateTimeOffset;
  13467. let container = 'audio/mp4';
  13468. let initPTS;
  13469. let initDTS;
  13470. let timescale;
  13471. if (computePTSDTS) {
  13472. initPTS = initDTS = Infinity;
  13473. }
  13474. if (audioTrack.config && audioSamples.length) {
  13475. // let's use audio sampling rate as MP4 time scale.
  13476. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  13477. // using audio sampling rate here helps having an integer MP4 frame duration
  13478. // this avoids potential rounding issue and AV sync issue
  13479. audioTrack.timescale = audioTrack.samplerate;
  13480. switch (audioTrack.segmentCodec) {
  13481. case 'mp3':
  13482. if (typeSupported.mpeg) {
  13483. // Chrome and Safari
  13484. container = 'audio/mpeg';
  13485. audioTrack.codec = '';
  13486. } else if (typeSupported.mp3) {
  13487. // Firefox
  13488. audioTrack.codec = 'mp3';
  13489. }
  13490. break;
  13491. case 'ac3':
  13492. audioTrack.codec = 'ac-3';
  13493. break;
  13494. }
  13495. tracks.audio = {
  13496. id: 'audio',
  13497. container: container,
  13498. codec: audioTrack.codec,
  13499. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13500. metadata: {
  13501. channelCount: audioTrack.channelCount
  13502. }
  13503. };
  13504. if (computePTSDTS) {
  13505. timescale = audioTrack.inputTimeScale;
  13506. if (!_initPTS || timescale !== _initPTS.timescale) {
  13507. // remember first PTS of this demuxing context. for audio, PTS = DTS
  13508. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  13509. } else {
  13510. computePTSDTS = false;
  13511. }
  13512. }
  13513. }
  13514. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13515. // let's use input time scale as MP4 video timescale
  13516. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  13517. videoTrack.timescale = videoTrack.inputTimeScale;
  13518. tracks.video = {
  13519. id: 'main',
  13520. container: 'video/mp4',
  13521. codec: videoTrack.codec,
  13522. initSegment: MP4.initSegment([videoTrack]),
  13523. metadata: {
  13524. width: videoTrack.width,
  13525. height: videoTrack.height
  13526. }
  13527. };
  13528. if (computePTSDTS) {
  13529. timescale = videoTrack.inputTimeScale;
  13530. if (!_initPTS || timescale !== _initPTS.timescale) {
  13531. const startPTS = this.getVideoStartPts(videoSamples);
  13532. const startOffset = Math.round(timescale * timeOffset);
  13533. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  13534. initPTS = Math.min(initPTS, startPTS - startOffset);
  13535. } else {
  13536. computePTSDTS = false;
  13537. }
  13538. }
  13539. this.videoTrackConfig = {
  13540. width: videoTrack.width,
  13541. height: videoTrack.height,
  13542. pixelRatio: videoTrack.pixelRatio
  13543. };
  13544. }
  13545. if (Object.keys(tracks).length) {
  13546. this.ISGenerated = true;
  13547. if (computePTSDTS) {
  13548. this._initPTS = {
  13549. baseTime: initPTS,
  13550. timescale: timescale
  13551. };
  13552. this._initDTS = {
  13553. baseTime: initDTS,
  13554. timescale: timescale
  13555. };
  13556. } else {
  13557. initPTS = timescale = undefined;
  13558. }
  13559. return {
  13560. tracks,
  13561. initPTS,
  13562. timescale
  13563. };
  13564. }
  13565. }
  13566. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13567. const timeScale = track.inputTimeScale;
  13568. const inputSamples = track.samples;
  13569. const outputSamples = [];
  13570. const nbSamples = inputSamples.length;
  13571. const initPTS = this._initPTS;
  13572. let nextAvcDts = this.nextAvcDts;
  13573. let offset = 8;
  13574. let mp4SampleDuration = this.videoSampleDuration;
  13575. let firstDTS;
  13576. let lastDTS;
  13577. let minPTS = Number.POSITIVE_INFINITY;
  13578. let maxPTS = Number.NEGATIVE_INFINITY;
  13579. let sortSamples = false;
  13580. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  13581. if (!contiguous || nextAvcDts === null) {
  13582. const pts = timeOffset * timeScale;
  13583. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13584. if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {
  13585. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  13586. contiguous = true;
  13587. } else {
  13588. // if not contiguous, let's use target timeOffset
  13589. nextAvcDts = pts - cts;
  13590. }
  13591. }
  13592. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  13593. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  13594. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13595. for (let i = 0; i < nbSamples; i++) {
  13596. const sample = inputSamples[i];
  13597. sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
  13598. sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
  13599. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13600. sortSamples = true;
  13601. }
  13602. }
  13603. // sort video samples by DTS then PTS then demux id order
  13604. if (sortSamples) {
  13605. inputSamples.sort(function (a, b) {
  13606. const deltadts = a.dts - b.dts;
  13607. const deltapts = a.pts - b.pts;
  13608. return deltadts || deltapts;
  13609. });
  13610. }
  13611. // Get first/last DTS
  13612. firstDTS = inputSamples[0].dts;
  13613. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13614. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  13615. // set this constant duration as being the avg delta between consecutive DTS.
  13616. const inputDuration = lastDTS - firstDTS;
  13617. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13618. // if fragment are contiguous, detect hole/overlapping between fragments
  13619. if (contiguous) {
  13620. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  13621. const delta = firstDTS - nextAvcDts;
  13622. const foundHole = delta > averageSampleDuration;
  13623. const foundOverlap = delta < -1;
  13624. if (foundHole || foundOverlap) {
  13625. if (foundHole) {
  13626. logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  13627. } else {
  13628. logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  13629. }
  13630. if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
  13631. firstDTS = nextAvcDts;
  13632. const firstPTS = inputSamples[0].pts - delta;
  13633. if (foundHole) {
  13634. inputSamples[0].dts = firstDTS;
  13635. inputSamples[0].pts = firstPTS;
  13636. } else {
  13637. for (let i = 0; i < inputSamples.length; i++) {
  13638. if (inputSamples[i].dts > firstPTS) {
  13639. break;
  13640. }
  13641. inputSamples[i].dts -= delta;
  13642. inputSamples[i].pts -= delta;
  13643. }
  13644. }
  13645. logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  13646. }
  13647. }
  13648. }
  13649. firstDTS = Math.max(0, firstDTS);
  13650. let nbNalu = 0;
  13651. let naluLen = 0;
  13652. let dtsStep = firstDTS;
  13653. for (let i = 0; i < nbSamples; i++) {
  13654. // compute total/avc sample length and nb of NAL units
  13655. const sample = inputSamples[i];
  13656. const units = sample.units;
  13657. const nbUnits = units.length;
  13658. let sampleLen = 0;
  13659. for (let j = 0; j < nbUnits; j++) {
  13660. sampleLen += units[j].data.length;
  13661. }
  13662. naluLen += sampleLen;
  13663. nbNalu += nbUnits;
  13664. sample.length = sampleLen;
  13665. // ensure sample monotonic DTS
  13666. if (sample.dts < dtsStep) {
  13667. sample.dts = dtsStep;
  13668. dtsStep += averageSampleDuration / 4 | 0 || 1;
  13669. } else {
  13670. dtsStep = sample.dts;
  13671. }
  13672. minPTS = Math.min(sample.pts, minPTS);
  13673. maxPTS = Math.max(sample.pts, maxPTS);
  13674. }
  13675. lastDTS = inputSamples[nbSamples - 1].dts;
  13676. /* concatenate the video data and construct the mdat in place
  13677. (need 8 more bytes to fill length and mpdat type) */
  13678. const mdatSize = naluLen + 4 * nbNalu + 8;
  13679. let mdat;
  13680. try {
  13681. mdat = new Uint8Array(mdatSize);
  13682. } catch (err) {
  13683. this.observer.emit(Events.ERROR, Events.ERROR, {
  13684. type: ErrorTypes.MUX_ERROR,
  13685. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13686. fatal: false,
  13687. error: err,
  13688. bytes: mdatSize,
  13689. reason: `fail allocating video mdat ${mdatSize}`
  13690. });
  13691. return;
  13692. }
  13693. const view = new DataView(mdat.buffer);
  13694. view.setUint32(0, mdatSize);
  13695. mdat.set(MP4.types.mdat, 4);
  13696. let stretchedLastFrame = false;
  13697. let minDtsDelta = Number.POSITIVE_INFINITY;
  13698. let minPtsDelta = Number.POSITIVE_INFINITY;
  13699. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  13700. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  13701. for (let i = 0; i < nbSamples; i++) {
  13702. const VideoSample = inputSamples[i];
  13703. const VideoSampleUnits = VideoSample.units;
  13704. let mp4SampleLength = 0;
  13705. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  13706. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  13707. const unit = VideoSampleUnits[j];
  13708. const unitData = unit.data;
  13709. const unitDataLen = unit.data.byteLength;
  13710. view.setUint32(offset, unitDataLen);
  13711. offset += 4;
  13712. mdat.set(unitData, offset);
  13713. offset += unitDataLen;
  13714. mp4SampleLength += 4 + unitDataLen;
  13715. }
  13716. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  13717. let ptsDelta;
  13718. if (i < nbSamples - 1) {
  13719. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  13720. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  13721. } else {
  13722. const config = this.config;
  13723. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  13724. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  13725. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  13726. // In some cases, a segment's audio track duration may exceed the video track duration.
  13727. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  13728. // see if the delta to the next segment is longer than maxBufferHole.
  13729. // If so, playback would potentially get stuck, so we artificially inflate
  13730. // the duration of the last frame to minimize any potential gap between segments.
  13731. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  13732. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts;
  13733. if (deltaToFrameEnd > gapTolerance) {
  13734. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  13735. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  13736. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  13737. if (mp4SampleDuration < 0) {
  13738. mp4SampleDuration = lastFrameDuration;
  13739. } else {
  13740. stretchedLastFrame = true;
  13741. }
  13742. logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  13743. } else {
  13744. mp4SampleDuration = lastFrameDuration;
  13745. }
  13746. } else {
  13747. mp4SampleDuration = lastFrameDuration;
  13748. }
  13749. }
  13750. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  13751. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  13752. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  13753. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  13754. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  13755. outputSamples.push(new Mp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  13756. }
  13757. if (outputSamples.length) {
  13758. if (chromeVersion) {
  13759. if (chromeVersion < 70) {
  13760. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  13761. // https://code.google.com/p/chromium/issues/detail?id=229412
  13762. const flags = outputSamples[0].flags;
  13763. flags.dependsOn = 2;
  13764. flags.isNonSync = 0;
  13765. }
  13766. } else if (safariWebkitVersion) {
  13767. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  13768. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  13769. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  13770. logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  13771. let dts = firstDTS;
  13772. for (let i = 0, len = outputSamples.length; i < len; i++) {
  13773. const nextDts = dts + outputSamples[i].duration;
  13774. const pts = dts + outputSamples[i].cts;
  13775. if (i < len - 1) {
  13776. const nextPts = nextDts + outputSamples[i + 1].cts;
  13777. outputSamples[i].duration = nextPts - pts;
  13778. } else {
  13779. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  13780. }
  13781. outputSamples[i].cts = 0;
  13782. dts = nextDts;
  13783. }
  13784. }
  13785. }
  13786. }
  13787. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  13788. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  13789. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  13790. this.videoSampleDuration = mp4SampleDuration;
  13791. this.isVideoContiguous = true;
  13792. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  13793. samples: outputSamples
  13794. }));
  13795. const type = 'video';
  13796. const data = {
  13797. data1: moof,
  13798. data2: mdat,
  13799. startPTS: minPTS / timeScale,
  13800. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  13801. startDTS: firstDTS / timeScale,
  13802. endDTS: nextAvcDts / timeScale,
  13803. type,
  13804. hasAudio: false,
  13805. hasVideo: true,
  13806. nb: outputSamples.length,
  13807. dropped: track.dropped
  13808. };
  13809. track.samples = [];
  13810. track.dropped = 0;
  13811. return data;
  13812. }
  13813. getSamplesPerFrame(track) {
  13814. switch (track.segmentCodec) {
  13815. case 'mp3':
  13816. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  13817. case 'ac3':
  13818. return AC3_SAMPLES_PER_FRAME;
  13819. default:
  13820. return AAC_SAMPLES_PER_FRAME;
  13821. }
  13822. }
  13823. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  13824. const inputTimeScale = track.inputTimeScale;
  13825. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13826. const scaleFactor = inputTimeScale / mp4timeScale;
  13827. const mp4SampleDuration = this.getSamplesPerFrame(track);
  13828. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  13829. const initPTS = this._initPTS;
  13830. const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  13831. const outputSamples = [];
  13832. const alignedWithVideo = videoTimeOffset !== undefined;
  13833. let inputSamples = track.samples;
  13834. let offset = rawMPEG ? 0 : 8;
  13835. let nextAudioPts = this.nextAudioPts || -1;
  13836. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  13837. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  13838. // for sake of clarity:
  13839. // consecutive fragments are frags with
  13840. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  13841. // - less than 20 audio frames distance
  13842. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  13843. // this helps ensuring audio continuity
  13844. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  13845. const timeOffsetMpegTS = timeOffset * inputTimeScale;
  13846. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  13847. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);
  13848. // compute normalized PTS
  13849. inputSamples.forEach(function (sample) {
  13850. sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
  13851. });
  13852. if (!contiguous || nextAudioPts < 0) {
  13853. // filter out sample with negative PTS that are not playable anyway
  13854. // if we don't remove these negative samples, they will shift all audio samples forward.
  13855. // leading to audio overlap between current / next fragment
  13856. inputSamples = inputSamples.filter(sample => sample.pts >= 0);
  13857. // in case all samples have negative PTS, and have been filtered out, return now
  13858. if (!inputSamples.length) {
  13859. return;
  13860. }
  13861. if (videoTimeOffset === 0) {
  13862. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  13863. nextAudioPts = 0;
  13864. } else if (accurateTimeOffset && !alignedWithVideo) {
  13865. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  13866. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  13867. } else {
  13868. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  13869. nextAudioPts = inputSamples[0].pts;
  13870. }
  13871. }
  13872. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  13873. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  13874. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  13875. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  13876. // frame.
  13877. if (track.segmentCodec === 'aac') {
  13878. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  13879. for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  13880. // First, let's see how far off this frame is from where we expect it to be
  13881. const sample = inputSamples[i];
  13882. const pts = sample.pts;
  13883. const delta = pts - nextPts;
  13884. const duration = Math.abs(1000 * delta / inputTimeScale);
  13885. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  13886. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  13887. if (i === 0) {
  13888. logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1000 * delta / inputTimeScale)} ms.`);
  13889. this.nextAudioPts = nextAudioPts = nextPts = pts;
  13890. }
  13891. } // eslint-disable-line brace-style
  13892. // Insert missing frames if:
  13893. // 1: We're more than maxAudioFramesDrift frame away
  13894. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  13895. // 3: currentTime (aka nextPtsNorm) is not 0
  13896. // 4: remuxing with video (videoTimeOffset !== undefined)
  13897. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  13898. let missing = Math.round(delta / inputSampleDuration);
  13899. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  13900. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  13901. nextPts = pts - missing * inputSampleDuration;
  13902. if (nextPts < 0) {
  13903. missing--;
  13904. nextPts += inputSampleDuration;
  13905. }
  13906. if (i === 0) {
  13907. this.nextAudioPts = nextAudioPts = nextPts;
  13908. }
  13909. logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);
  13910. for (let j = 0; j < missing; j++) {
  13911. const newStamp = Math.max(nextPts, 0);
  13912. let fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  13913. if (!fillFrame) {
  13914. logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  13915. fillFrame = sample.unit.subarray();
  13916. }
  13917. inputSamples.splice(i, 0, {
  13918. unit: fillFrame,
  13919. pts: newStamp
  13920. });
  13921. nextPts += inputSampleDuration;
  13922. i++;
  13923. }
  13924. }
  13925. sample.pts = nextPts;
  13926. nextPts += inputSampleDuration;
  13927. }
  13928. }
  13929. let firstPTS = null;
  13930. let lastPTS = null;
  13931. let mdat;
  13932. let mdatSize = 0;
  13933. let sampleLength = inputSamples.length;
  13934. while (sampleLength--) {
  13935. mdatSize += inputSamples[sampleLength].unit.byteLength;
  13936. }
  13937. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  13938. const audioSample = inputSamples[j];
  13939. const unit = audioSample.unit;
  13940. let pts = audioSample.pts;
  13941. if (lastPTS !== null) {
  13942. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  13943. // the previous sample
  13944. const prevSample = outputSamples[j - 1];
  13945. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  13946. } else {
  13947. if (contiguous && track.segmentCodec === 'aac') {
  13948. // set PTS/DTS to expected PTS/DTS
  13949. pts = nextAudioPts;
  13950. }
  13951. // remember first PTS of our audioSamples
  13952. firstPTS = pts;
  13953. if (mdatSize > 0) {
  13954. /* concatenate the audio data and construct the mdat in place
  13955. (need 8 more bytes to fill length and mdat type) */
  13956. mdatSize += offset;
  13957. try {
  13958. mdat = new Uint8Array(mdatSize);
  13959. } catch (err) {
  13960. this.observer.emit(Events.ERROR, Events.ERROR, {
  13961. type: ErrorTypes.MUX_ERROR,
  13962. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13963. fatal: false,
  13964. error: err,
  13965. bytes: mdatSize,
  13966. reason: `fail allocating audio mdat ${mdatSize}`
  13967. });
  13968. return;
  13969. }
  13970. if (!rawMPEG) {
  13971. const view = new DataView(mdat.buffer);
  13972. view.setUint32(0, mdatSize);
  13973. mdat.set(MP4.types.mdat, 4);
  13974. }
  13975. } else {
  13976. // no audio samples
  13977. return;
  13978. }
  13979. }
  13980. mdat.set(unit, offset);
  13981. const unitLen = unit.byteLength;
  13982. offset += unitLen;
  13983. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  13984. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  13985. // becomes the PTS diff with the previous sample
  13986. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  13987. lastPTS = pts;
  13988. }
  13989. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  13990. const nbSamples = outputSamples.length;
  13991. if (!nbSamples) {
  13992. return;
  13993. }
  13994. // The next audio sample PTS should be equal to last sample PTS + duration
  13995. const lastSample = outputSamples[outputSamples.length - 1];
  13996. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  13997. // Set the track samples from inputSamples to outputSamples before remuxing
  13998. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  13999. samples: outputSamples
  14000. }));
  14001. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  14002. track.samples = [];
  14003. const start = firstPTS / inputTimeScale;
  14004. const end = nextAudioPts / inputTimeScale;
  14005. const type = 'audio';
  14006. const audioData = {
  14007. data1: moof,
  14008. data2: mdat,
  14009. startPTS: start,
  14010. endPTS: end,
  14011. startDTS: start,
  14012. endDTS: end,
  14013. type,
  14014. hasAudio: true,
  14015. hasVideo: false,
  14016. nb: nbSamples
  14017. };
  14018. this.isAudioContiguous = true;
  14019. return audioData;
  14020. }
  14021. remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  14022. const inputTimeScale = track.inputTimeScale;
  14023. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  14024. const scaleFactor = inputTimeScale / mp4timeScale;
  14025. const nextAudioPts = this.nextAudioPts;
  14026. // sync with video's timestamp
  14027. const initDTS = this._initDTS;
  14028. const init90kHz = initDTS.baseTime * 90000 / initDTS.timescale;
  14029. const startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz;
  14030. const endDTS = videoData.endDTS * inputTimeScale + init90kHz;
  14031. // one sample's duration value
  14032. const frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  14033. // samples count of this segment's duration
  14034. const nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  14035. // silent frame
  14036. const silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  14037. logger.warn('[mp4-remuxer]: remux empty Audio');
  14038. // Can't remux if we can't generate a silent frame...
  14039. if (!silentFrame) {
  14040. logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  14041. return;
  14042. }
  14043. const samples = [];
  14044. for (let i = 0; i < nbSamples; i++) {
  14045. const stamp = startDTS + i * frameDuration;
  14046. samples.push({
  14047. unit: silentFrame,
  14048. pts: stamp,
  14049. dts: stamp
  14050. });
  14051. }
  14052. track.samples = samples;
  14053. return this.remuxAudio(track, timeOffset, contiguous, false);
  14054. }
  14055. }
  14056. function normalizePts(value, reference) {
  14057. let offset;
  14058. if (reference === null) {
  14059. return value;
  14060. }
  14061. if (reference < value) {
  14062. // - 2^33
  14063. offset = -8589934592;
  14064. } else {
  14065. // + 2^33
  14066. offset = 8589934592;
  14067. }
  14068. /* PTS is 33bit (from 0 to 2^33 -1)
  14069. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  14070. PTS looping occured. fill the gap */
  14071. while (Math.abs(value - reference) > 4294967296) {
  14072. value += offset;
  14073. }
  14074. return value;
  14075. }
  14076. function findKeyframeIndex(samples) {
  14077. for (let i = 0; i < samples.length; i++) {
  14078. if (samples[i].key) {
  14079. return i;
  14080. }
  14081. }
  14082. return -1;
  14083. }
  14084. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  14085. const length = track.samples.length;
  14086. if (!length) {
  14087. return;
  14088. }
  14089. const inputTimeScale = track.inputTimeScale;
  14090. for (let index = 0; index < length; index++) {
  14091. const sample = track.samples[index];
  14092. // setting id3 pts, dts to relative time
  14093. // using this._initPTS and this._initDTS to calculate relative time
  14094. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14095. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14096. }
  14097. const samples = track.samples;
  14098. track.samples = [];
  14099. return {
  14100. samples
  14101. };
  14102. }
  14103. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  14104. const length = track.samples.length;
  14105. if (!length) {
  14106. return;
  14107. }
  14108. const inputTimeScale = track.inputTimeScale;
  14109. for (let index = 0; index < length; index++) {
  14110. const sample = track.samples[index];
  14111. // setting text pts, dts to relative time
  14112. // using this._initPTS and this._initDTS to calculate relative time
  14113. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14114. }
  14115. track.samples.sort((a, b) => a.pts - b.pts);
  14116. const samples = track.samples;
  14117. track.samples = [];
  14118. return {
  14119. samples
  14120. };
  14121. }
  14122. class Mp4Sample {
  14123. constructor(isKeyframe, duration, size, cts) {
  14124. this.size = void 0;
  14125. this.duration = void 0;
  14126. this.cts = void 0;
  14127. this.flags = void 0;
  14128. this.duration = duration;
  14129. this.size = size;
  14130. this.cts = cts;
  14131. this.flags = {
  14132. isLeading: 0,
  14133. isDependedOn: 0,
  14134. hasRedundancy: 0,
  14135. degradPrio: 0,
  14136. dependsOn: isKeyframe ? 2 : 1,
  14137. isNonSync: isKeyframe ? 0 : 1
  14138. };
  14139. }
  14140. }
  14141. class PassThroughRemuxer {
  14142. constructor() {
  14143. this.emitInitSegment = false;
  14144. this.audioCodec = void 0;
  14145. this.videoCodec = void 0;
  14146. this.initData = void 0;
  14147. this.initPTS = null;
  14148. this.initTracks = void 0;
  14149. this.lastEndTime = null;
  14150. }
  14151. destroy() {}
  14152. resetTimeStamp(defaultInitPTS) {
  14153. this.initPTS = defaultInitPTS;
  14154. this.lastEndTime = null;
  14155. }
  14156. resetNextTimestamp() {
  14157. this.lastEndTime = null;
  14158. }
  14159. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  14160. this.audioCodec = audioCodec;
  14161. this.videoCodec = videoCodec;
  14162. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  14163. this.emitInitSegment = true;
  14164. }
  14165. generateInitSegment(initSegment) {
  14166. let {
  14167. audioCodec,
  14168. videoCodec
  14169. } = this;
  14170. if (!(initSegment != null && initSegment.byteLength)) {
  14171. this.initTracks = undefined;
  14172. this.initData = undefined;
  14173. return;
  14174. }
  14175. const initData = this.initData = parseInitSegment(initSegment);
  14176. // Get codec from initSegment or fallback to default
  14177. if (initData.audio) {
  14178. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
  14179. }
  14180. if (initData.video) {
  14181. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
  14182. }
  14183. const tracks = {};
  14184. if (initData.audio && initData.video) {
  14185. tracks.audiovideo = {
  14186. container: 'video/mp4',
  14187. codec: audioCodec + ',' + videoCodec,
  14188. initSegment,
  14189. id: 'main'
  14190. };
  14191. } else if (initData.audio) {
  14192. tracks.audio = {
  14193. container: 'audio/mp4',
  14194. codec: audioCodec,
  14195. initSegment,
  14196. id: 'audio'
  14197. };
  14198. } else if (initData.video) {
  14199. tracks.video = {
  14200. container: 'video/mp4',
  14201. codec: videoCodec,
  14202. initSegment,
  14203. id: 'main'
  14204. };
  14205. } else {
  14206. logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  14207. }
  14208. this.initTracks = tracks;
  14209. }
  14210. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  14211. var _initData, _initData2;
  14212. let {
  14213. initPTS,
  14214. lastEndTime
  14215. } = this;
  14216. const result = {
  14217. audio: undefined,
  14218. video: undefined,
  14219. text: textTrack,
  14220. id3: id3Track,
  14221. initSegment: undefined
  14222. };
  14223. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  14224. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  14225. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  14226. if (!isFiniteNumber(lastEndTime)) {
  14227. lastEndTime = this.lastEndTime = timeOffset || 0;
  14228. }
  14229. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  14230. // audio or video (or both); adding it to video was an arbitrary choice.
  14231. const data = videoTrack.samples;
  14232. if (!(data != null && data.length)) {
  14233. return result;
  14234. }
  14235. const initSegment = {
  14236. initPTS: undefined,
  14237. timescale: 1
  14238. };
  14239. let initData = this.initData;
  14240. if (!((_initData = initData) != null && _initData.length)) {
  14241. this.generateInitSegment(data);
  14242. initData = this.initData;
  14243. }
  14244. if (!((_initData2 = initData) != null && _initData2.length)) {
  14245. // We can't remux if the initSegment could not be generated
  14246. logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  14247. return result;
  14248. }
  14249. if (this.emitInitSegment) {
  14250. initSegment.tracks = this.initTracks;
  14251. this.emitInitSegment = false;
  14252. }
  14253. const duration = getDuration(data, initData);
  14254. const startDTS = getStartDTS(initData, data);
  14255. const decodeTime = startDTS === null ? timeOffset : startDTS;
  14256. if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) {
  14257. initSegment.initPTS = decodeTime - timeOffset;
  14258. if (initPTS && initPTS.timescale === 1) {
  14259. logger.warn(`Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`);
  14260. }
  14261. this.initPTS = initPTS = {
  14262. baseTime: initSegment.initPTS,
  14263. timescale: 1
  14264. };
  14265. }
  14266. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  14267. const endTime = startTime + duration;
  14268. offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
  14269. if (duration > 0) {
  14270. this.lastEndTime = endTime;
  14271. } else {
  14272. logger.warn('Duration parsed from mp4 should be greater than zero');
  14273. this.resetNextTimestamp();
  14274. }
  14275. const hasAudio = !!initData.audio;
  14276. const hasVideo = !!initData.video;
  14277. let type = '';
  14278. if (hasAudio) {
  14279. type += 'audio';
  14280. }
  14281. if (hasVideo) {
  14282. type += 'video';
  14283. }
  14284. const track = {
  14285. data1: data,
  14286. startPTS: startTime,
  14287. startDTS: startTime,
  14288. endPTS: endTime,
  14289. endDTS: endTime,
  14290. type,
  14291. hasAudio,
  14292. hasVideo,
  14293. nb: 1,
  14294. dropped: 0
  14295. };
  14296. result.audio = track.type === 'audio' ? track : undefined;
  14297. result.video = track.type !== 'audio' ? track : undefined;
  14298. result.initSegment = initSegment;
  14299. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  14300. if (textTrack.samples.length) {
  14301. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  14302. }
  14303. return result;
  14304. }
  14305. }
  14306. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  14307. if (initPTS === null) {
  14308. return true;
  14309. }
  14310. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  14311. const minDuration = Math.max(duration, 1);
  14312. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  14313. return Math.abs(startTime - timeOffset) > minDuration;
  14314. }
  14315. function getParsedTrackCodec(track, type) {
  14316. const parsedCodec = track == null ? void 0 : track.codec;
  14317. if (parsedCodec && parsedCodec.length > 4) {
  14318. return parsedCodec;
  14319. }
  14320. if (type === ElementaryStreamTypes.AUDIO) {
  14321. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  14322. return parsedCodec;
  14323. }
  14324. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  14325. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  14326. const preferManagedMediaSource = false;
  14327. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  14328. }
  14329. const result = 'mp4a.40.5';
  14330. logger.info(`Parsed audio codec "${parsedCodec}" or audio object type not handled. Using "${result}"`);
  14331. return result;
  14332. }
  14333. // Provide defaults based on codec type
  14334. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  14335. logger.warn(`Unhandled video codec "${parsedCodec}"`);
  14336. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  14337. return 'hvc1.1.6.L120.90';
  14338. }
  14339. if (parsedCodec === 'av01') {
  14340. return 'av01.0.04M.08';
  14341. }
  14342. return 'avc1.42e01e';
  14343. }
  14344. let now;
  14345. // performance.now() not available on WebWorker, at least on Safari Desktop
  14346. try {
  14347. now = self.performance.now.bind(self.performance);
  14348. } catch (err) {
  14349. logger.debug('Unable to use Performance API on this environment');
  14350. now = optionalSelf == null ? void 0 : optionalSelf.Date.now;
  14351. }
  14352. const muxConfig = [{
  14353. demux: MP4Demuxer,
  14354. remux: PassThroughRemuxer
  14355. }, {
  14356. demux: TSDemuxer,
  14357. remux: MP4Remuxer
  14358. }, {
  14359. demux: AACDemuxer,
  14360. remux: MP4Remuxer
  14361. }, {
  14362. demux: MP3Demuxer,
  14363. remux: MP4Remuxer
  14364. }];
  14365. {
  14366. muxConfig.splice(2, 0, {
  14367. demux: AC3Demuxer,
  14368. remux: MP4Remuxer
  14369. });
  14370. }
  14371. class Transmuxer {
  14372. constructor(observer, typeSupported, config, vendor, id) {
  14373. this.async = false;
  14374. this.observer = void 0;
  14375. this.typeSupported = void 0;
  14376. this.config = void 0;
  14377. this.vendor = void 0;
  14378. this.id = void 0;
  14379. this.demuxer = void 0;
  14380. this.remuxer = void 0;
  14381. this.decrypter = void 0;
  14382. this.probe = void 0;
  14383. this.decryptionPromise = null;
  14384. this.transmuxConfig = void 0;
  14385. this.currentTransmuxState = void 0;
  14386. this.observer = observer;
  14387. this.typeSupported = typeSupported;
  14388. this.config = config;
  14389. this.vendor = vendor;
  14390. this.id = id;
  14391. }
  14392. configure(transmuxConfig) {
  14393. this.transmuxConfig = transmuxConfig;
  14394. if (this.decrypter) {
  14395. this.decrypter.reset();
  14396. }
  14397. }
  14398. push(data, decryptdata, chunkMeta, state) {
  14399. const stats = chunkMeta.transmuxing;
  14400. stats.executeStart = now();
  14401. let uintData = new Uint8Array(data);
  14402. const {
  14403. currentTransmuxState,
  14404. transmuxConfig
  14405. } = this;
  14406. if (state) {
  14407. this.currentTransmuxState = state;
  14408. }
  14409. const {
  14410. contiguous,
  14411. discontinuity,
  14412. trackSwitch,
  14413. accurateTimeOffset,
  14414. timeOffset,
  14415. initSegmentChange
  14416. } = state || currentTransmuxState;
  14417. const {
  14418. audioCodec,
  14419. videoCodec,
  14420. defaultInitPts,
  14421. duration,
  14422. initSegmentData
  14423. } = transmuxConfig;
  14424. const keyData = getEncryptionType(uintData, decryptdata);
  14425. if (keyData && keyData.method === 'AES-128') {
  14426. const decrypter = this.getDecrypter();
  14427. // Software decryption is synchronous; webCrypto is not
  14428. if (decrypter.isSync()) {
  14429. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  14430. // data is handled in the flush() call
  14431. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  14432. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  14433. const loadingParts = chunkMeta.part > -1;
  14434. if (loadingParts) {
  14435. decryptedData = decrypter.flush();
  14436. }
  14437. if (!decryptedData) {
  14438. stats.executeEnd = now();
  14439. return emptyResult(chunkMeta);
  14440. }
  14441. uintData = new Uint8Array(decryptedData);
  14442. } else {
  14443. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(decryptedData => {
  14444. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  14445. // the decrypted data has been transmuxed
  14446. const result = this.push(decryptedData, null, chunkMeta);
  14447. this.decryptionPromise = null;
  14448. return result;
  14449. });
  14450. return this.decryptionPromise;
  14451. }
  14452. }
  14453. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  14454. if (resetMuxers) {
  14455. const error = this.configureTransmuxer(uintData);
  14456. if (error) {
  14457. logger.warn(`[transmuxer] ${error.message}`);
  14458. this.observer.emit(Events.ERROR, Events.ERROR, {
  14459. type: ErrorTypes.MEDIA_ERROR,
  14460. details: ErrorDetails.FRAG_PARSING_ERROR,
  14461. fatal: false,
  14462. error,
  14463. reason: error.message
  14464. });
  14465. stats.executeEnd = now();
  14466. return emptyResult(chunkMeta);
  14467. }
  14468. }
  14469. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  14470. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  14471. }
  14472. if (discontinuity || initSegmentChange || resetMuxers) {
  14473. this.resetInitialTimestamp(defaultInitPts);
  14474. }
  14475. if (!contiguous) {
  14476. this.resetContiguity();
  14477. }
  14478. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14479. const currentState = this.currentTransmuxState;
  14480. currentState.contiguous = true;
  14481. currentState.discontinuity = false;
  14482. currentState.trackSwitch = false;
  14483. stats.executeEnd = now();
  14484. return result;
  14485. }
  14486. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  14487. flush(chunkMeta) {
  14488. const stats = chunkMeta.transmuxing;
  14489. stats.executeStart = now();
  14490. const {
  14491. decrypter,
  14492. currentTransmuxState,
  14493. decryptionPromise
  14494. } = this;
  14495. if (decryptionPromise) {
  14496. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  14497. // only flushing is required for async decryption
  14498. return decryptionPromise.then(() => {
  14499. return this.flush(chunkMeta);
  14500. });
  14501. }
  14502. const transmuxResults = [];
  14503. const {
  14504. timeOffset
  14505. } = currentTransmuxState;
  14506. if (decrypter) {
  14507. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  14508. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  14509. // or for progressive downloads with small segments)
  14510. const decryptedData = decrypter.flush();
  14511. if (decryptedData) {
  14512. // Push always returns a TransmuxerResult if decryptdata is null
  14513. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  14514. }
  14515. }
  14516. const {
  14517. demuxer,
  14518. remuxer
  14519. } = this;
  14520. if (!demuxer || !remuxer) {
  14521. // If probing failed, then Hls.js has been given content its not able to handle
  14522. stats.executeEnd = now();
  14523. return [emptyResult(chunkMeta)];
  14524. }
  14525. const demuxResultOrPromise = demuxer.flush(timeOffset);
  14526. if (isPromise(demuxResultOrPromise)) {
  14527. // Decrypt final SAMPLE-AES samples
  14528. return demuxResultOrPromise.then(demuxResult => {
  14529. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14530. return transmuxResults;
  14531. });
  14532. }
  14533. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14534. return transmuxResults;
  14535. }
  14536. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14537. const {
  14538. audioTrack,
  14539. videoTrack,
  14540. id3Track,
  14541. textTrack
  14542. } = demuxResult;
  14543. const {
  14544. accurateTimeOffset,
  14545. timeOffset
  14546. } = this.currentTransmuxState;
  14547. logger.log(`[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''} of level ${chunkMeta.level}`);
  14548. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14549. transmuxResults.push({
  14550. remuxResult,
  14551. chunkMeta
  14552. });
  14553. chunkMeta.transmuxing.executeEnd = now();
  14554. }
  14555. resetInitialTimestamp(defaultInitPts) {
  14556. const {
  14557. demuxer,
  14558. remuxer
  14559. } = this;
  14560. if (!demuxer || !remuxer) {
  14561. return;
  14562. }
  14563. demuxer.resetTimeStamp(defaultInitPts);
  14564. remuxer.resetTimeStamp(defaultInitPts);
  14565. }
  14566. resetContiguity() {
  14567. const {
  14568. demuxer,
  14569. remuxer
  14570. } = this;
  14571. if (!demuxer || !remuxer) {
  14572. return;
  14573. }
  14574. demuxer.resetContiguity();
  14575. remuxer.resetNextTimestamp();
  14576. }
  14577. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14578. const {
  14579. demuxer,
  14580. remuxer
  14581. } = this;
  14582. if (!demuxer || !remuxer) {
  14583. return;
  14584. }
  14585. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14586. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14587. }
  14588. destroy() {
  14589. if (this.demuxer) {
  14590. this.demuxer.destroy();
  14591. this.demuxer = undefined;
  14592. }
  14593. if (this.remuxer) {
  14594. this.remuxer.destroy();
  14595. this.remuxer = undefined;
  14596. }
  14597. }
  14598. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14599. let result;
  14600. if (keyData && keyData.method === 'SAMPLE-AES') {
  14601. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14602. } else {
  14603. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14604. }
  14605. return result;
  14606. }
  14607. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14608. const {
  14609. audioTrack,
  14610. videoTrack,
  14611. id3Track,
  14612. textTrack
  14613. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  14614. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14615. return {
  14616. remuxResult,
  14617. chunkMeta
  14618. };
  14619. }
  14620. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14621. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {
  14622. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14623. return {
  14624. remuxResult,
  14625. chunkMeta
  14626. };
  14627. });
  14628. }
  14629. configureTransmuxer(data) {
  14630. const {
  14631. config,
  14632. observer,
  14633. typeSupported,
  14634. vendor
  14635. } = this;
  14636. // probe for content type
  14637. let mux;
  14638. for (let i = 0, len = muxConfig.length; i < len; i++) {
  14639. var _muxConfig$i$demux;
  14640. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data)) {
  14641. mux = muxConfig[i];
  14642. break;
  14643. }
  14644. }
  14645. if (!mux) {
  14646. return new Error('Failed to find demuxer by probing fragment data');
  14647. }
  14648. // so let's check that current remuxer and demuxer are still valid
  14649. const demuxer = this.demuxer;
  14650. const remuxer = this.remuxer;
  14651. const Remuxer = mux.remux;
  14652. const Demuxer = mux.demux;
  14653. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14654. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  14655. }
  14656. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14657. this.demuxer = new Demuxer(observer, config, typeSupported);
  14658. this.probe = Demuxer.probe;
  14659. }
  14660. }
  14661. needsProbing(discontinuity, trackSwitch) {
  14662. // in case of continuity change, or track switch
  14663. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  14664. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14665. }
  14666. getDecrypter() {
  14667. let decrypter = this.decrypter;
  14668. if (!decrypter) {
  14669. decrypter = this.decrypter = new Decrypter(this.config);
  14670. }
  14671. return decrypter;
  14672. }
  14673. }
  14674. function getEncryptionType(data, decryptData) {
  14675. let encryptionType = null;
  14676. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14677. encryptionType = decryptData;
  14678. }
  14679. return encryptionType;
  14680. }
  14681. const emptyResult = chunkMeta => ({
  14682. remuxResult: {},
  14683. chunkMeta
  14684. });
  14685. function isPromise(p) {
  14686. return 'then' in p && p.then instanceof Function;
  14687. }
  14688. class TransmuxConfig {
  14689. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14690. this.audioCodec = void 0;
  14691. this.videoCodec = void 0;
  14692. this.initSegmentData = void 0;
  14693. this.duration = void 0;
  14694. this.defaultInitPts = void 0;
  14695. this.audioCodec = audioCodec;
  14696. this.videoCodec = videoCodec;
  14697. this.initSegmentData = initSegmentData;
  14698. this.duration = duration;
  14699. this.defaultInitPts = defaultInitPts || null;
  14700. }
  14701. }
  14702. class TransmuxState {
  14703. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14704. this.discontinuity = void 0;
  14705. this.contiguous = void 0;
  14706. this.accurateTimeOffset = void 0;
  14707. this.trackSwitch = void 0;
  14708. this.timeOffset = void 0;
  14709. this.initSegmentChange = void 0;
  14710. this.discontinuity = discontinuity;
  14711. this.contiguous = contiguous;
  14712. this.accurateTimeOffset = accurateTimeOffset;
  14713. this.trackSwitch = trackSwitch;
  14714. this.timeOffset = timeOffset;
  14715. this.initSegmentChange = initSegmentChange;
  14716. }
  14717. }
  14718. var eventemitter3 = {exports: {}};
  14719. (function (module) {
  14720. var has = Object.prototype.hasOwnProperty
  14721. , prefix = '~';
  14722. /**
  14723. * Constructor to create a storage for our `EE` objects.
  14724. * An `Events` instance is a plain object whose properties are event names.
  14725. *
  14726. * @constructor
  14727. * @private
  14728. */
  14729. function Events() {}
  14730. //
  14731. // We try to not inherit from `Object.prototype`. In some engines creating an
  14732. // instance in this way is faster than calling `Object.create(null)` directly.
  14733. // If `Object.create(null)` is not supported we prefix the event names with a
  14734. // character to make sure that the built-in object properties are not
  14735. // overridden or used as an attack vector.
  14736. //
  14737. if (Object.create) {
  14738. Events.prototype = Object.create(null);
  14739. //
  14740. // This hack is needed because the `__proto__` property is still inherited in
  14741. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  14742. //
  14743. if (!new Events().__proto__) prefix = false;
  14744. }
  14745. /**
  14746. * Representation of a single event listener.
  14747. *
  14748. * @param {Function} fn The listener function.
  14749. * @param {*} context The context to invoke the listener with.
  14750. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  14751. * @constructor
  14752. * @private
  14753. */
  14754. function EE(fn, context, once) {
  14755. this.fn = fn;
  14756. this.context = context;
  14757. this.once = once || false;
  14758. }
  14759. /**
  14760. * Add a listener for a given event.
  14761. *
  14762. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  14763. * @param {(String|Symbol)} event The event name.
  14764. * @param {Function} fn The listener function.
  14765. * @param {*} context The context to invoke the listener with.
  14766. * @param {Boolean} once Specify if the listener is a one-time listener.
  14767. * @returns {EventEmitter}
  14768. * @private
  14769. */
  14770. function addListener(emitter, event, fn, context, once) {
  14771. if (typeof fn !== 'function') {
  14772. throw new TypeError('The listener must be a function');
  14773. }
  14774. var listener = new EE(fn, context || emitter, once)
  14775. , evt = prefix ? prefix + event : event;
  14776. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  14777. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  14778. else emitter._events[evt] = [emitter._events[evt], listener];
  14779. return emitter;
  14780. }
  14781. /**
  14782. * Clear event by name.
  14783. *
  14784. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  14785. * @param {(String|Symbol)} evt The Event name.
  14786. * @private
  14787. */
  14788. function clearEvent(emitter, evt) {
  14789. if (--emitter._eventsCount === 0) emitter._events = new Events();
  14790. else delete emitter._events[evt];
  14791. }
  14792. /**
  14793. * Minimal `EventEmitter` interface that is molded against the Node.js
  14794. * `EventEmitter` interface.
  14795. *
  14796. * @constructor
  14797. * @public
  14798. */
  14799. function EventEmitter() {
  14800. this._events = new Events();
  14801. this._eventsCount = 0;
  14802. }
  14803. /**
  14804. * Return an array listing the events for which the emitter has registered
  14805. * listeners.
  14806. *
  14807. * @returns {Array}
  14808. * @public
  14809. */
  14810. EventEmitter.prototype.eventNames = function eventNames() {
  14811. var names = []
  14812. , events
  14813. , name;
  14814. if (this._eventsCount === 0) return names;
  14815. for (name in (events = this._events)) {
  14816. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  14817. }
  14818. if (Object.getOwnPropertySymbols) {
  14819. return names.concat(Object.getOwnPropertySymbols(events));
  14820. }
  14821. return names;
  14822. };
  14823. /**
  14824. * Return the listeners registered for a given event.
  14825. *
  14826. * @param {(String|Symbol)} event The event name.
  14827. * @returns {Array} The registered listeners.
  14828. * @public
  14829. */
  14830. EventEmitter.prototype.listeners = function listeners(event) {
  14831. var evt = prefix ? prefix + event : event
  14832. , handlers = this._events[evt];
  14833. if (!handlers) return [];
  14834. if (handlers.fn) return [handlers.fn];
  14835. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  14836. ee[i] = handlers[i].fn;
  14837. }
  14838. return ee;
  14839. };
  14840. /**
  14841. * Return the number of listeners listening to a given event.
  14842. *
  14843. * @param {(String|Symbol)} event The event name.
  14844. * @returns {Number} The number of listeners.
  14845. * @public
  14846. */
  14847. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  14848. var evt = prefix ? prefix + event : event
  14849. , listeners = this._events[evt];
  14850. if (!listeners) return 0;
  14851. if (listeners.fn) return 1;
  14852. return listeners.length;
  14853. };
  14854. /**
  14855. * Calls each of the listeners registered for a given event.
  14856. *
  14857. * @param {(String|Symbol)} event The event name.
  14858. * @returns {Boolean} `true` if the event had listeners, else `false`.
  14859. * @public
  14860. */
  14861. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  14862. var evt = prefix ? prefix + event : event;
  14863. if (!this._events[evt]) return false;
  14864. var listeners = this._events[evt]
  14865. , len = arguments.length
  14866. , args
  14867. , i;
  14868. if (listeners.fn) {
  14869. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  14870. switch (len) {
  14871. case 1: return listeners.fn.call(listeners.context), true;
  14872. case 2: return listeners.fn.call(listeners.context, a1), true;
  14873. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  14874. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  14875. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  14876. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  14877. }
  14878. for (i = 1, args = new Array(len -1); i < len; i++) {
  14879. args[i - 1] = arguments[i];
  14880. }
  14881. listeners.fn.apply(listeners.context, args);
  14882. } else {
  14883. var length = listeners.length
  14884. , j;
  14885. for (i = 0; i < length; i++) {
  14886. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  14887. switch (len) {
  14888. case 1: listeners[i].fn.call(listeners[i].context); break;
  14889. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  14890. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  14891. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  14892. default:
  14893. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  14894. args[j - 1] = arguments[j];
  14895. }
  14896. listeners[i].fn.apply(listeners[i].context, args);
  14897. }
  14898. }
  14899. }
  14900. return true;
  14901. };
  14902. /**
  14903. * Add a listener for a given event.
  14904. *
  14905. * @param {(String|Symbol)} event The event name.
  14906. * @param {Function} fn The listener function.
  14907. * @param {*} [context=this] The context to invoke the listener with.
  14908. * @returns {EventEmitter} `this`.
  14909. * @public
  14910. */
  14911. EventEmitter.prototype.on = function on(event, fn, context) {
  14912. return addListener(this, event, fn, context, false);
  14913. };
  14914. /**
  14915. * Add a one-time listener for a given event.
  14916. *
  14917. * @param {(String|Symbol)} event The event name.
  14918. * @param {Function} fn The listener function.
  14919. * @param {*} [context=this] The context to invoke the listener with.
  14920. * @returns {EventEmitter} `this`.
  14921. * @public
  14922. */
  14923. EventEmitter.prototype.once = function once(event, fn, context) {
  14924. return addListener(this, event, fn, context, true);
  14925. };
  14926. /**
  14927. * Remove the listeners of a given event.
  14928. *
  14929. * @param {(String|Symbol)} event The event name.
  14930. * @param {Function} fn Only remove the listeners that match this function.
  14931. * @param {*} context Only remove the listeners that have this context.
  14932. * @param {Boolean} once Only remove one-time listeners.
  14933. * @returns {EventEmitter} `this`.
  14934. * @public
  14935. */
  14936. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  14937. var evt = prefix ? prefix + event : event;
  14938. if (!this._events[evt]) return this;
  14939. if (!fn) {
  14940. clearEvent(this, evt);
  14941. return this;
  14942. }
  14943. var listeners = this._events[evt];
  14944. if (listeners.fn) {
  14945. if (
  14946. listeners.fn === fn &&
  14947. (!once || listeners.once) &&
  14948. (!context || listeners.context === context)
  14949. ) {
  14950. clearEvent(this, evt);
  14951. }
  14952. } else {
  14953. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  14954. if (
  14955. listeners[i].fn !== fn ||
  14956. (once && !listeners[i].once) ||
  14957. (context && listeners[i].context !== context)
  14958. ) {
  14959. events.push(listeners[i]);
  14960. }
  14961. }
  14962. //
  14963. // Reset the array, or remove it completely if we have no more listeners.
  14964. //
  14965. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  14966. else clearEvent(this, evt);
  14967. }
  14968. return this;
  14969. };
  14970. /**
  14971. * Remove all listeners, or those of the specified event.
  14972. *
  14973. * @param {(String|Symbol)} [event] The event name.
  14974. * @returns {EventEmitter} `this`.
  14975. * @public
  14976. */
  14977. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  14978. var evt;
  14979. if (event) {
  14980. evt = prefix ? prefix + event : event;
  14981. if (this._events[evt]) clearEvent(this, evt);
  14982. } else {
  14983. this._events = new Events();
  14984. this._eventsCount = 0;
  14985. }
  14986. return this;
  14987. };
  14988. //
  14989. // Alias methods names because people roll like that.
  14990. //
  14991. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  14992. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  14993. //
  14994. // Expose the prefix.
  14995. //
  14996. EventEmitter.prefixed = prefix;
  14997. //
  14998. // Allow `EventEmitter` to be imported as module namespace.
  14999. //
  15000. EventEmitter.EventEmitter = EventEmitter;
  15001. //
  15002. // Expose the module.
  15003. //
  15004. {
  15005. module.exports = EventEmitter;
  15006. }
  15007. } (eventemitter3));
  15008. var eventemitter3Exports = eventemitter3.exports;
  15009. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  15010. class TransmuxerInterface {
  15011. constructor(hls, id, onTransmuxComplete, onFlush) {
  15012. this.error = null;
  15013. this.hls = void 0;
  15014. this.id = void 0;
  15015. this.observer = void 0;
  15016. this.frag = null;
  15017. this.part = null;
  15018. this.useWorker = void 0;
  15019. this.workerContext = null;
  15020. this.onwmsg = void 0;
  15021. this.transmuxer = null;
  15022. this.onTransmuxComplete = void 0;
  15023. this.onFlush = void 0;
  15024. const config = hls.config;
  15025. this.hls = hls;
  15026. this.id = id;
  15027. this.useWorker = !!config.enableWorker;
  15028. this.onTransmuxComplete = onTransmuxComplete;
  15029. this.onFlush = onFlush;
  15030. const forwardMessage = (ev, data) => {
  15031. data = data || {};
  15032. data.frag = this.frag;
  15033. data.id = this.id;
  15034. if (ev === Events.ERROR) {
  15035. this.error = data.error;
  15036. }
  15037. this.hls.trigger(ev, data);
  15038. };
  15039. // forward events to main thread
  15040. this.observer = new EventEmitter();
  15041. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  15042. this.observer.on(Events.ERROR, forwardMessage);
  15043. const MediaSource = getMediaSource(config.preferManagedMediaSource) || {
  15044. isTypeSupported: () => false
  15045. };
  15046. const m2tsTypeSupported = {
  15047. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  15048. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  15049. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  15050. };
  15051. if (this.useWorker && typeof Worker !== 'undefined') {
  15052. const canCreateWorker = config.workerPath || hasUMDWorker();
  15053. if (canCreateWorker) {
  15054. try {
  15055. if (config.workerPath) {
  15056. logger.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  15057. this.workerContext = loadWorker(config.workerPath);
  15058. } else {
  15059. logger.log(`injecting Web Worker for "${id}"`);
  15060. this.workerContext = injectWorker();
  15061. }
  15062. this.onwmsg = event => this.onWorkerMessage(event);
  15063. const {
  15064. worker
  15065. } = this.workerContext;
  15066. worker.addEventListener('message', this.onwmsg);
  15067. worker.onerror = event => {
  15068. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  15069. config.enableWorker = false;
  15070. logger.warn(`Error in "${id}" Web Worker, fallback to inline`);
  15071. this.hls.trigger(Events.ERROR, {
  15072. type: ErrorTypes.OTHER_ERROR,
  15073. details: ErrorDetails.INTERNAL_EXCEPTION,
  15074. fatal: false,
  15075. event: 'demuxerWorker',
  15076. error
  15077. });
  15078. };
  15079. worker.postMessage({
  15080. cmd: 'init',
  15081. typeSupported: m2tsTypeSupported,
  15082. vendor: '',
  15083. id: id,
  15084. config: JSON.stringify(config)
  15085. });
  15086. } catch (err) {
  15087. logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  15088. this.resetWorker();
  15089. this.error = null;
  15090. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  15091. }
  15092. return;
  15093. }
  15094. }
  15095. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  15096. }
  15097. resetWorker() {
  15098. if (this.workerContext) {
  15099. const {
  15100. worker,
  15101. objectURL
  15102. } = this.workerContext;
  15103. if (objectURL) {
  15104. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  15105. self.URL.revokeObjectURL(objectURL);
  15106. }
  15107. worker.removeEventListener('message', this.onwmsg);
  15108. worker.onerror = null;
  15109. worker.terminate();
  15110. this.workerContext = null;
  15111. }
  15112. }
  15113. destroy() {
  15114. if (this.workerContext) {
  15115. this.resetWorker();
  15116. this.onwmsg = undefined;
  15117. } else {
  15118. const transmuxer = this.transmuxer;
  15119. if (transmuxer) {
  15120. transmuxer.destroy();
  15121. this.transmuxer = null;
  15122. }
  15123. }
  15124. const observer = this.observer;
  15125. if (observer) {
  15126. observer.removeAllListeners();
  15127. }
  15128. this.frag = null;
  15129. // @ts-ignore
  15130. this.observer = null;
  15131. // @ts-ignore
  15132. this.hls = null;
  15133. }
  15134. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  15135. var _frag$initSegment, _lastFrag$initSegment;
  15136. chunkMeta.transmuxing.start = self.performance.now();
  15137. const {
  15138. transmuxer
  15139. } = this;
  15140. const timeOffset = part ? part.start : frag.start;
  15141. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  15142. const decryptdata = frag.decryptdata;
  15143. const lastFrag = this.frag;
  15144. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  15145. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  15146. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  15147. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  15148. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  15149. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  15150. const now = self.performance.now();
  15151. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  15152. frag.stats.parsing.start = now;
  15153. }
  15154. if (part && (partDiff || !contiguous)) {
  15155. part.stats.parsing.start = now;
  15156. }
  15157. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  15158. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  15159. if (!contiguous || discontinuity || initSegmentChange) {
  15160. logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}
  15161. discontinuity: ${discontinuity}
  15162. trackSwitch: ${trackSwitch}
  15163. contiguous: ${contiguous}
  15164. accurateTimeOffset: ${accurateTimeOffset}
  15165. timeOffset: ${timeOffset}
  15166. initSegmentChange: ${initSegmentChange}`);
  15167. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  15168. this.configureTransmuxer(config);
  15169. }
  15170. this.frag = frag;
  15171. this.part = part;
  15172. // Frags with sn of 'initSegment' are not transmuxed
  15173. if (this.workerContext) {
  15174. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  15175. this.workerContext.worker.postMessage({
  15176. cmd: 'demux',
  15177. data,
  15178. decryptdata,
  15179. chunkMeta,
  15180. state
  15181. }, data instanceof ArrayBuffer ? [data] : []);
  15182. } else if (transmuxer) {
  15183. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  15184. if (isPromise(transmuxResult)) {
  15185. transmuxer.async = true;
  15186. transmuxResult.then(data => {
  15187. this.handleTransmuxComplete(data);
  15188. }).catch(error => {
  15189. this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  15190. });
  15191. } else {
  15192. transmuxer.async = false;
  15193. this.handleTransmuxComplete(transmuxResult);
  15194. }
  15195. }
  15196. }
  15197. flush(chunkMeta) {
  15198. chunkMeta.transmuxing.start = self.performance.now();
  15199. const {
  15200. transmuxer
  15201. } = this;
  15202. if (this.workerContext) {
  15203. this.workerContext.worker.postMessage({
  15204. cmd: 'flush',
  15205. chunkMeta
  15206. });
  15207. } else if (transmuxer) {
  15208. let transmuxResult = transmuxer.flush(chunkMeta);
  15209. const asyncFlush = isPromise(transmuxResult);
  15210. if (asyncFlush || transmuxer.async) {
  15211. if (!isPromise(transmuxResult)) {
  15212. transmuxResult = Promise.resolve(transmuxResult);
  15213. }
  15214. transmuxResult.then(data => {
  15215. this.handleFlushResult(data, chunkMeta);
  15216. }).catch(error => {
  15217. this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  15218. });
  15219. } else {
  15220. this.handleFlushResult(transmuxResult, chunkMeta);
  15221. }
  15222. }
  15223. }
  15224. transmuxerError(error, chunkMeta, reason) {
  15225. if (!this.hls) {
  15226. return;
  15227. }
  15228. this.error = error;
  15229. this.hls.trigger(Events.ERROR, {
  15230. type: ErrorTypes.MEDIA_ERROR,
  15231. details: ErrorDetails.FRAG_PARSING_ERROR,
  15232. chunkMeta,
  15233. frag: this.frag || undefined,
  15234. fatal: false,
  15235. error,
  15236. err: error,
  15237. reason
  15238. });
  15239. }
  15240. handleFlushResult(results, chunkMeta) {
  15241. results.forEach(result => {
  15242. this.handleTransmuxComplete(result);
  15243. });
  15244. this.onFlush(chunkMeta);
  15245. }
  15246. onWorkerMessage(event) {
  15247. const data = event.data;
  15248. if (!(data != null && data.event)) {
  15249. logger.warn(`worker message received with no ${data ? 'event name' : 'data'}`);
  15250. return;
  15251. }
  15252. const hls = this.hls;
  15253. if (!this.hls) {
  15254. return;
  15255. }
  15256. switch (data.event) {
  15257. case 'init':
  15258. {
  15259. var _this$workerContext;
  15260. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  15261. if (objectURL) {
  15262. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  15263. self.URL.revokeObjectURL(objectURL);
  15264. }
  15265. break;
  15266. }
  15267. case 'transmuxComplete':
  15268. {
  15269. this.handleTransmuxComplete(data.data);
  15270. break;
  15271. }
  15272. case 'flush':
  15273. {
  15274. this.onFlush(data.data);
  15275. break;
  15276. }
  15277. // pass logs from the worker thread to the main logger
  15278. case 'workerLog':
  15279. if (logger[data.data.logType]) {
  15280. logger[data.data.logType](data.data.message);
  15281. }
  15282. break;
  15283. default:
  15284. {
  15285. data.data = data.data || {};
  15286. data.data.frag = this.frag;
  15287. data.data.id = this.id;
  15288. hls.trigger(data.event, data.data);
  15289. break;
  15290. }
  15291. }
  15292. }
  15293. configureTransmuxer(config) {
  15294. const {
  15295. transmuxer
  15296. } = this;
  15297. if (this.workerContext) {
  15298. this.workerContext.worker.postMessage({
  15299. cmd: 'configure',
  15300. config
  15301. });
  15302. } else if (transmuxer) {
  15303. transmuxer.configure(config);
  15304. }
  15305. }
  15306. handleTransmuxComplete(result) {
  15307. result.chunkMeta.transmuxing.end = self.performance.now();
  15308. this.onTransmuxComplete(result);
  15309. }
  15310. }
  15311. function subtitleOptionsIdentical(trackList1, trackList2) {
  15312. if (trackList1.length !== trackList2.length) {
  15313. return false;
  15314. }
  15315. for (let i = 0; i < trackList1.length; i++) {
  15316. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  15317. return false;
  15318. }
  15319. }
  15320. return true;
  15321. }
  15322. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  15323. // Media options with the same rendition ID must be bit identical
  15324. const stableRenditionId = attrs1['STABLE-RENDITION-ID'];
  15325. if (stableRenditionId && !customAttributes) {
  15326. return stableRenditionId === attrs2['STABLE-RENDITION-ID'];
  15327. }
  15328. // When rendition ID is not present, compare attributes
  15329. return !(customAttributes || ['LANGUAGE', 'NAME', 'CHARACTERISTICS', 'AUTOSELECT', 'DEFAULT', 'FORCED', 'ASSOC-LANGUAGE']).some(subtitleAttribute => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  15330. }
  15331. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  15332. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || '').toLowerCase());
  15333. }
  15334. const TICK_INTERVAL$2 = 100; // how often to tick in ms
  15335. class AudioStreamController extends BaseStreamController {
  15336. constructor(hls, fragmentTracker, keyLoader) {
  15337. super(hls, fragmentTracker, keyLoader, '[audio-stream-controller]', PlaylistLevelType.AUDIO);
  15338. this.videoBuffer = null;
  15339. this.videoTrackCC = -1;
  15340. this.waitingVideoCC = -1;
  15341. this.bufferedTrack = null;
  15342. this.switchingTrack = null;
  15343. this.trackId = -1;
  15344. this.waitingData = null;
  15345. this.mainDetails = null;
  15346. this.flushing = false;
  15347. this.bufferFlushed = false;
  15348. this.cachedTrackLoadedData = null;
  15349. this._registerListeners();
  15350. }
  15351. onHandlerDestroying() {
  15352. this._unregisterListeners();
  15353. super.onHandlerDestroying();
  15354. this.mainDetails = null;
  15355. this.bufferedTrack = null;
  15356. this.switchingTrack = null;
  15357. }
  15358. _registerListeners() {
  15359. const {
  15360. hls
  15361. } = this;
  15362. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15363. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15364. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15365. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15366. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15367. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15368. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15369. hls.on(Events.ERROR, this.onError, this);
  15370. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  15371. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15372. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15373. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15374. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15375. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15376. }
  15377. _unregisterListeners() {
  15378. const {
  15379. hls
  15380. } = this;
  15381. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15382. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15383. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15384. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15385. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15386. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15387. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15388. hls.off(Events.ERROR, this.onError, this);
  15389. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  15390. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15391. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15392. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15393. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15394. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15395. }
  15396. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  15397. onInitPtsFound(event, {
  15398. frag,
  15399. id,
  15400. initPTS,
  15401. timescale
  15402. }) {
  15403. // Always update the new INIT PTS
  15404. // Can change due level switch
  15405. if (id === 'main') {
  15406. const cc = frag.cc;
  15407. this.initPTS[frag.cc] = {
  15408. baseTime: initPTS,
  15409. timescale
  15410. };
  15411. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`);
  15412. this.videoTrackCC = cc;
  15413. // If we are waiting, tick immediately to unblock audio fragment transmuxing
  15414. if (this.state === State.WAITING_INIT_PTS) {
  15415. this.tick();
  15416. }
  15417. }
  15418. }
  15419. startLoad(startPosition) {
  15420. if (!this.levels) {
  15421. this.startPosition = startPosition;
  15422. this.state = State.STOPPED;
  15423. return;
  15424. }
  15425. const lastCurrentTime = this.lastCurrentTime;
  15426. this.stopLoad();
  15427. this.setInterval(TICK_INTERVAL$2);
  15428. if (lastCurrentTime > 0 && startPosition === -1) {
  15429. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  15430. startPosition = lastCurrentTime;
  15431. this.state = State.IDLE;
  15432. } else {
  15433. this.loadedmetadata = false;
  15434. this.state = State.WAITING_TRACK;
  15435. }
  15436. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  15437. this.tick();
  15438. }
  15439. doTick() {
  15440. switch (this.state) {
  15441. case State.IDLE:
  15442. this.doTickIdle();
  15443. break;
  15444. case State.WAITING_TRACK:
  15445. {
  15446. var _levels$trackId;
  15447. const {
  15448. levels,
  15449. trackId
  15450. } = this;
  15451. const details = levels == null ? void 0 : (_levels$trackId = levels[trackId]) == null ? void 0 : _levels$trackId.details;
  15452. if (details) {
  15453. if (this.waitForCdnTuneIn(details)) {
  15454. break;
  15455. }
  15456. this.state = State.WAITING_INIT_PTS;
  15457. }
  15458. break;
  15459. }
  15460. case State.FRAG_LOADING_WAITING_RETRY:
  15461. {
  15462. var _this$media;
  15463. const now = performance.now();
  15464. const retryDate = this.retryDate;
  15465. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  15466. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  15467. const {
  15468. levels,
  15469. trackId
  15470. } = this;
  15471. this.log('RetryDate reached, switch back to IDLE state');
  15472. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  15473. this.state = State.IDLE;
  15474. }
  15475. break;
  15476. }
  15477. case State.WAITING_INIT_PTS:
  15478. {
  15479. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  15480. const waitingData = this.waitingData;
  15481. if (waitingData) {
  15482. const {
  15483. frag,
  15484. part,
  15485. cache,
  15486. complete
  15487. } = waitingData;
  15488. if (this.initPTS[frag.cc] !== undefined) {
  15489. this.waitingData = null;
  15490. this.waitingVideoCC = -1;
  15491. this.state = State.FRAG_LOADING;
  15492. const payload = cache.flush();
  15493. const data = {
  15494. frag,
  15495. part,
  15496. payload,
  15497. networkDetails: null
  15498. };
  15499. this._handleFragmentLoadProgress(data);
  15500. if (complete) {
  15501. super._handleFragmentLoadComplete(data);
  15502. }
  15503. } else if (this.videoTrackCC !== this.waitingVideoCC) {
  15504. // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
  15505. this.log(`Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`);
  15506. this.clearWaitingFragment();
  15507. } else {
  15508. // Drop waiting fragment if an earlier fragment is needed
  15509. const pos = this.getLoadPosition();
  15510. const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole);
  15511. const waitingFragmentAtPosition = fragmentWithinToleranceTest(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
  15512. if (waitingFragmentAtPosition < 0) {
  15513. this.log(`Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`);
  15514. this.clearWaitingFragment();
  15515. }
  15516. }
  15517. } else {
  15518. this.state = State.IDLE;
  15519. }
  15520. }
  15521. }
  15522. this.onTickEnd();
  15523. }
  15524. clearWaitingFragment() {
  15525. const waitingData = this.waitingData;
  15526. if (waitingData) {
  15527. this.fragmentTracker.removeFragment(waitingData.frag);
  15528. this.waitingData = null;
  15529. this.waitingVideoCC = -1;
  15530. this.state = State.IDLE;
  15531. }
  15532. }
  15533. resetLoadingState() {
  15534. this.clearWaitingFragment();
  15535. super.resetLoadingState();
  15536. }
  15537. onTickEnd() {
  15538. const {
  15539. media
  15540. } = this;
  15541. if (!(media != null && media.readyState)) {
  15542. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  15543. return;
  15544. }
  15545. this.lastCurrentTime = media.currentTime;
  15546. }
  15547. doTickIdle() {
  15548. const {
  15549. hls,
  15550. levels,
  15551. media,
  15552. trackId
  15553. } = this;
  15554. const config = hls.config;
  15555. // 1. if video not attached AND
  15556. // start fragment already requested OR start frag prefetch not enabled
  15557. // 2. if tracks or track not loaded and selected
  15558. // then exit loop
  15559. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  15560. if (!media && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  15561. return;
  15562. }
  15563. const levelInfo = levels[trackId];
  15564. const trackDetails = levelInfo.details;
  15565. if (!trackDetails || trackDetails.live && this.levelLastLoaded !== levelInfo || this.waitForCdnTuneIn(trackDetails)) {
  15566. this.state = State.WAITING_TRACK;
  15567. return;
  15568. }
  15569. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  15570. if (this.bufferFlushed && bufferable) {
  15571. this.bufferFlushed = false;
  15572. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  15573. }
  15574. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  15575. if (bufferInfo === null) {
  15576. return;
  15577. }
  15578. const {
  15579. bufferedTrack,
  15580. switchingTrack
  15581. } = this;
  15582. if (!switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  15583. hls.trigger(Events.BUFFER_EOS, {
  15584. type: 'audio'
  15585. });
  15586. this.state = State.ENDED;
  15587. return;
  15588. }
  15589. const mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, PlaylistLevelType.MAIN);
  15590. const bufferLen = bufferInfo.len;
  15591. const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len);
  15592. const fragments = trackDetails.fragments;
  15593. const start = fragments[0].start;
  15594. let targetBufferTime = this.flushing ? this.getLoadPosition() : bufferInfo.end;
  15595. if (switchingTrack && media) {
  15596. const pos = this.getLoadPosition();
  15597. // STABLE
  15598. if (bufferedTrack && !mediaAttributesIdentical(switchingTrack.attrs, bufferedTrack.attrs)) {
  15599. targetBufferTime = pos;
  15600. }
  15601. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  15602. if (trackDetails.PTSKnown && pos < start) {
  15603. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  15604. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15605. this.log('Alt audio track ahead of main track, seek to start of alt audio track');
  15606. media.currentTime = start + 0.05;
  15607. }
  15608. }
  15609. }
  15610. // if buffer length is less than maxBufLen, or near the end, find a fragment to load
  15611. if (bufferLen >= maxBufLen && !switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  15612. return;
  15613. }
  15614. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  15615. let atGap = false;
  15616. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  15617. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  15618. atGap = !!frag.gap;
  15619. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  15620. }
  15621. if (!frag) {
  15622. this.bufferFlushed = true;
  15623. return;
  15624. }
  15625. // Buffer audio up to one target duration ahead of main buffer
  15626. const atBufferSyncLimit = mainBufferInfo && frag.start > mainBufferInfo.end + trackDetails.targetduration;
  15627. if (atBufferSyncLimit ||
  15628. // Or wait for main buffer after buffing some audio
  15629. !(mainBufferInfo != null && mainBufferInfo.len) && bufferInfo.len) {
  15630. // Check fragment-tracker for main fragments since GAP segments do not show up in bufferInfo
  15631. const mainFrag = this.getAppendedFrag(frag.start, PlaylistLevelType.MAIN);
  15632. if (mainFrag === null) {
  15633. return;
  15634. }
  15635. // Bridge gaps in main buffer
  15636. atGap || (atGap = !!mainFrag.gap || !!atBufferSyncLimit && mainBufferInfo.len === 0);
  15637. if (atBufferSyncLimit && !atGap || atGap && bufferInfo.nextStart && bufferInfo.nextStart < mainFrag.end) {
  15638. return;
  15639. }
  15640. }
  15641. this.loadFragment(frag, levelInfo, targetBufferTime);
  15642. }
  15643. getMaxBufferLength(mainBufferLength) {
  15644. const maxConfigBuffer = super.getMaxBufferLength();
  15645. if (!mainBufferLength) {
  15646. return maxConfigBuffer;
  15647. }
  15648. return Math.min(Math.max(maxConfigBuffer, mainBufferLength), this.config.maxMaxBufferLength);
  15649. }
  15650. onMediaDetaching() {
  15651. this.videoBuffer = null;
  15652. this.bufferFlushed = this.flushing = false;
  15653. super.onMediaDetaching();
  15654. }
  15655. onAudioTracksUpdated(event, {
  15656. audioTracks
  15657. }) {
  15658. // Reset tranxmuxer is essential for large context switches (Content Steering)
  15659. this.resetTransmuxer();
  15660. this.levels = audioTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  15661. }
  15662. onAudioTrackSwitching(event, data) {
  15663. // if any URL found on new audio track, it is an alternate audio track
  15664. const altAudio = !!data.url;
  15665. this.trackId = data.id;
  15666. const {
  15667. fragCurrent
  15668. } = this;
  15669. if (fragCurrent) {
  15670. fragCurrent.abortRequests();
  15671. this.removeUnbufferedFrags(fragCurrent.start);
  15672. }
  15673. this.resetLoadingState();
  15674. // destroy useless transmuxer when switching audio to main
  15675. if (!altAudio) {
  15676. this.resetTransmuxer();
  15677. } else {
  15678. // switching to audio track, start timer if not already started
  15679. this.setInterval(TICK_INTERVAL$2);
  15680. }
  15681. // should we switch tracks ?
  15682. if (altAudio) {
  15683. this.switchingTrack = data;
  15684. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  15685. this.state = State.IDLE;
  15686. this.flushAudioIfNeeded(data);
  15687. } else {
  15688. this.switchingTrack = null;
  15689. this.bufferedTrack = data;
  15690. this.state = State.STOPPED;
  15691. }
  15692. this.tick();
  15693. }
  15694. onManifestLoading() {
  15695. this.fragmentTracker.removeAllFragments();
  15696. this.startPosition = this.lastCurrentTime = 0;
  15697. this.bufferFlushed = this.flushing = false;
  15698. this.levels = this.mainDetails = this.waitingData = this.bufferedTrack = this.cachedTrackLoadedData = this.switchingTrack = null;
  15699. this.startFragRequested = false;
  15700. this.trackId = this.videoTrackCC = this.waitingVideoCC = -1;
  15701. }
  15702. onLevelLoaded(event, data) {
  15703. this.mainDetails = data.details;
  15704. if (this.cachedTrackLoadedData !== null) {
  15705. this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData);
  15706. this.cachedTrackLoadedData = null;
  15707. }
  15708. }
  15709. onAudioTrackLoaded(event, data) {
  15710. var _track$details;
  15711. if (this.mainDetails == null) {
  15712. this.cachedTrackLoadedData = data;
  15713. return;
  15714. }
  15715. const {
  15716. levels
  15717. } = this;
  15718. const {
  15719. details: newDetails,
  15720. id: trackId
  15721. } = data;
  15722. if (!levels) {
  15723. this.warn(`Audio tracks were reset while loading level ${trackId}`);
  15724. return;
  15725. }
  15726. this.log(`Audio track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  15727. const track = levels[trackId];
  15728. let sliding = 0;
  15729. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  15730. this.checkLiveUpdate(newDetails);
  15731. const mainDetails = this.mainDetails;
  15732. if (newDetails.deltaUpdateFailed || !mainDetails) {
  15733. return;
  15734. }
  15735. if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  15736. // Make sure our audio rendition is aligned with the "main" rendition, using
  15737. // pdt as our reference times.
  15738. alignMediaPlaylistByPDT(newDetails, mainDetails);
  15739. sliding = newDetails.fragments[0].start;
  15740. } else {
  15741. var _this$levelLastLoaded;
  15742. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  15743. }
  15744. }
  15745. track.details = newDetails;
  15746. this.levelLastLoaded = track;
  15747. // compute start position if we are aligned with the main playlist
  15748. if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
  15749. this.setStartPosition(this.mainDetails || newDetails, sliding);
  15750. }
  15751. // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
  15752. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  15753. this.state = State.IDLE;
  15754. }
  15755. // trigger handler right now
  15756. this.tick();
  15757. }
  15758. _handleFragmentLoadProgress(data) {
  15759. var _frag$initSegment;
  15760. const {
  15761. frag,
  15762. part,
  15763. payload
  15764. } = data;
  15765. const {
  15766. config,
  15767. trackId,
  15768. levels
  15769. } = this;
  15770. if (!levels) {
  15771. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  15772. return;
  15773. }
  15774. const track = levels[trackId];
  15775. if (!track) {
  15776. this.warn('Audio track is undefined on fragment load progress');
  15777. return;
  15778. }
  15779. const details = track.details;
  15780. if (!details) {
  15781. this.warn('Audio track details undefined on fragment load progress');
  15782. this.removeUnbufferedFrags(frag.start);
  15783. return;
  15784. }
  15785. const audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
  15786. let transmuxer = this.transmuxer;
  15787. if (!transmuxer) {
  15788. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  15789. }
  15790. // Check if we have video initPTS
  15791. // If not we need to wait for it
  15792. const initPTS = this.initPTS[frag.cc];
  15793. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  15794. if (initPTS !== undefined) {
  15795. // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  15796. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  15797. const accurateTimeOffset = false; // details.PTSKnown || !details.live;
  15798. const partIndex = part ? part.index : -1;
  15799. const partial = partIndex !== -1;
  15800. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  15801. transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  15802. } else {
  15803. 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}`);
  15804. const {
  15805. cache
  15806. } = this.waitingData = this.waitingData || {
  15807. frag,
  15808. part,
  15809. cache: new ChunkCache(),
  15810. complete: false
  15811. };
  15812. cache.push(new Uint8Array(payload));
  15813. this.waitingVideoCC = this.videoTrackCC;
  15814. this.state = State.WAITING_INIT_PTS;
  15815. }
  15816. }
  15817. _handleFragmentLoadComplete(fragLoadedData) {
  15818. if (this.waitingData) {
  15819. this.waitingData.complete = true;
  15820. return;
  15821. }
  15822. super._handleFragmentLoadComplete(fragLoadedData);
  15823. }
  15824. onBufferReset( /* event: Events.BUFFER_RESET */
  15825. ) {
  15826. // reset reference to sourcebuffers
  15827. this.mediaBuffer = this.videoBuffer = null;
  15828. this.loadedmetadata = false;
  15829. }
  15830. onBufferCreated(event, data) {
  15831. const audioTrack = data.tracks.audio;
  15832. if (audioTrack) {
  15833. this.mediaBuffer = audioTrack.buffer || null;
  15834. }
  15835. if (data.tracks.video) {
  15836. this.videoBuffer = data.tracks.video.buffer || null;
  15837. }
  15838. }
  15839. onFragBuffered(event, data) {
  15840. const {
  15841. frag,
  15842. part
  15843. } = data;
  15844. if (frag.type !== PlaylistLevelType.AUDIO) {
  15845. if (!this.loadedmetadata && frag.type === PlaylistLevelType.MAIN) {
  15846. const bufferable = this.videoBuffer || this.media;
  15847. if (bufferable) {
  15848. const bufferedTimeRanges = BufferHelper.getBuffered(bufferable);
  15849. if (bufferedTimeRanges.length) {
  15850. this.loadedmetadata = true;
  15851. }
  15852. }
  15853. }
  15854. return;
  15855. }
  15856. if (this.fragContextChanged(frag)) {
  15857. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  15858. // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
  15859. 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'}`);
  15860. return;
  15861. }
  15862. if (frag.sn !== 'initSegment') {
  15863. this.fragPrevious = frag;
  15864. const track = this.switchingTrack;
  15865. if (track) {
  15866. this.bufferedTrack = track;
  15867. this.switchingTrack = null;
  15868. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  15869. }
  15870. }
  15871. this.fragBufferedComplete(frag, part);
  15872. }
  15873. onError(event, data) {
  15874. var _data$context;
  15875. if (data.fatal) {
  15876. this.state = State.ERROR;
  15877. return;
  15878. }
  15879. switch (data.details) {
  15880. case ErrorDetails.FRAG_GAP:
  15881. case ErrorDetails.FRAG_PARSING_ERROR:
  15882. case ErrorDetails.FRAG_DECRYPT_ERROR:
  15883. case ErrorDetails.FRAG_LOAD_ERROR:
  15884. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  15885. case ErrorDetails.KEY_LOAD_ERROR:
  15886. case ErrorDetails.KEY_LOAD_TIMEOUT:
  15887. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  15888. break;
  15889. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  15890. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  15891. case ErrorDetails.LEVEL_PARSING_ERROR:
  15892. // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE
  15893. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  15894. this.state = State.IDLE;
  15895. }
  15896. break;
  15897. case ErrorDetails.BUFFER_APPEND_ERROR:
  15898. case ErrorDetails.BUFFER_FULL_ERROR:
  15899. if (!data.parent || data.parent !== 'audio') {
  15900. return;
  15901. }
  15902. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  15903. this.resetLoadingState();
  15904. return;
  15905. }
  15906. if (this.reduceLengthAndFlushBuffer(data)) {
  15907. this.bufferedTrack = null;
  15908. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  15909. }
  15910. break;
  15911. case ErrorDetails.INTERNAL_EXCEPTION:
  15912. this.recoverWorkerError(data);
  15913. break;
  15914. }
  15915. }
  15916. onBufferFlushing(event, {
  15917. type
  15918. }) {
  15919. if (type !== ElementaryStreamTypes.VIDEO) {
  15920. this.flushing = true;
  15921. }
  15922. }
  15923. onBufferFlushed(event, {
  15924. type
  15925. }) {
  15926. if (type !== ElementaryStreamTypes.VIDEO) {
  15927. this.flushing = false;
  15928. this.bufferFlushed = true;
  15929. if (this.state === State.ENDED) {
  15930. this.state = State.IDLE;
  15931. }
  15932. const mediaBuffer = this.mediaBuffer || this.media;
  15933. if (mediaBuffer) {
  15934. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  15935. this.tick();
  15936. }
  15937. }
  15938. }
  15939. _handleTransmuxComplete(transmuxResult) {
  15940. var _id3$samples;
  15941. const id = 'audio';
  15942. const {
  15943. hls
  15944. } = this;
  15945. const {
  15946. remuxResult,
  15947. chunkMeta
  15948. } = transmuxResult;
  15949. const context = this.getCurrentContext(chunkMeta);
  15950. if (!context) {
  15951. this.resetWhenMissingContext(chunkMeta);
  15952. return;
  15953. }
  15954. const {
  15955. frag,
  15956. part,
  15957. level
  15958. } = context;
  15959. const {
  15960. details
  15961. } = level;
  15962. const {
  15963. audio,
  15964. text,
  15965. id3,
  15966. initSegment
  15967. } = remuxResult;
  15968. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  15969. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  15970. if (this.fragContextChanged(frag) || !details) {
  15971. this.fragmentTracker.removeFragment(frag);
  15972. return;
  15973. }
  15974. this.state = State.PARSING;
  15975. if (this.switchingTrack && audio) {
  15976. this.completeAudioSwitch(this.switchingTrack);
  15977. }
  15978. if (initSegment != null && initSegment.tracks) {
  15979. const mapFragment = frag.initSegment || frag;
  15980. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  15981. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  15982. frag: mapFragment,
  15983. id,
  15984. tracks: initSegment.tracks
  15985. });
  15986. // Only flush audio from old audio tracks when PTS is known on new audio track
  15987. }
  15988. if (audio) {
  15989. const {
  15990. startPTS,
  15991. endPTS,
  15992. startDTS,
  15993. endDTS
  15994. } = audio;
  15995. if (part) {
  15996. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  15997. startPTS,
  15998. endPTS,
  15999. startDTS,
  16000. endDTS
  16001. };
  16002. }
  16003. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  16004. this.bufferFragmentData(audio, frag, part, chunkMeta);
  16005. }
  16006. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  16007. const emittedID3 = _extends({
  16008. id,
  16009. frag,
  16010. details
  16011. }, id3);
  16012. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  16013. }
  16014. if (text) {
  16015. const emittedText = _extends({
  16016. id,
  16017. frag,
  16018. details
  16019. }, text);
  16020. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  16021. }
  16022. }
  16023. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  16024. if (this.state !== State.PARSING) {
  16025. return;
  16026. }
  16027. // delete any video track found on audio transmuxer
  16028. if (tracks.video) {
  16029. delete tracks.video;
  16030. }
  16031. // include levelCodec in audio and video tracks
  16032. const track = tracks.audio;
  16033. if (!track) {
  16034. return;
  16035. }
  16036. track.id = 'audio';
  16037. const variantAudioCodecs = currentLevel.audioCodec;
  16038. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  16039. // SourceBuffer will use track.levelCodec if defined
  16040. if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {
  16041. track.levelCodec = variantAudioCodecs;
  16042. }
  16043. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  16044. const initSegment = track.initSegment;
  16045. if (initSegment != null && initSegment.byteLength) {
  16046. const segment = {
  16047. type: 'audio',
  16048. frag,
  16049. part: null,
  16050. chunkMeta,
  16051. parent: frag.type,
  16052. data: initSegment
  16053. };
  16054. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  16055. }
  16056. // trigger handler right now
  16057. this.tickImmediate();
  16058. }
  16059. loadFragment(frag, track, targetBufferTime) {
  16060. // only load if fragment is not loaded or if in audio switch
  16061. const fragState = this.fragmentTracker.getState(frag);
  16062. this.fragCurrent = frag;
  16063. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  16064. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  16065. var _track$details2;
  16066. if (frag.sn === 'initSegment') {
  16067. this._loadInitSegment(frag, track);
  16068. } else if ((_track$details2 = track.details) != null && _track$details2.live && !this.initPTS[frag.cc]) {
  16069. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  16070. this.state = State.WAITING_INIT_PTS;
  16071. const mainDetails = this.mainDetails;
  16072. if (mainDetails && mainDetails.fragments[0].start !== track.details.fragments[0].start) {
  16073. alignMediaPlaylistByPDT(track.details, mainDetails);
  16074. }
  16075. } else {
  16076. this.startFragRequested = true;
  16077. super.loadFragment(frag, track, targetBufferTime);
  16078. }
  16079. } else {
  16080. this.clearTrackerIfNeeded(frag);
  16081. }
  16082. }
  16083. flushAudioIfNeeded(switchingTrack) {
  16084. const {
  16085. media,
  16086. bufferedTrack
  16087. } = this;
  16088. const bufferedAttributes = bufferedTrack == null ? void 0 : bufferedTrack.attrs;
  16089. const switchAttributes = switchingTrack.attrs;
  16090. if (media && bufferedAttributes && (bufferedAttributes.CHANNELS !== switchAttributes.CHANNELS || bufferedTrack.name !== switchingTrack.name || bufferedTrack.lang !== switchingTrack.lang)) {
  16091. this.log('Switching audio track : flushing all audio');
  16092. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  16093. this.bufferedTrack = null;
  16094. }
  16095. }
  16096. completeAudioSwitch(switchingTrack) {
  16097. const {
  16098. hls
  16099. } = this;
  16100. this.flushAudioIfNeeded(switchingTrack);
  16101. this.bufferedTrack = switchingTrack;
  16102. this.switchingTrack = null;
  16103. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  16104. }
  16105. }
  16106. class AudioTrackController extends BasePlaylistController {
  16107. constructor(hls) {
  16108. super(hls, '[audio-track-controller]');
  16109. this.tracks = [];
  16110. this.groupIds = null;
  16111. this.tracksInGroup = [];
  16112. this.trackId = -1;
  16113. this.currentTrack = null;
  16114. this.selectDefaultTrack = true;
  16115. this.registerListeners();
  16116. }
  16117. registerListeners() {
  16118. const {
  16119. hls
  16120. } = this;
  16121. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16122. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16123. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16124. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16125. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16126. hls.on(Events.ERROR, this.onError, this);
  16127. }
  16128. unregisterListeners() {
  16129. const {
  16130. hls
  16131. } = this;
  16132. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16133. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16134. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16135. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16136. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16137. hls.off(Events.ERROR, this.onError, this);
  16138. }
  16139. destroy() {
  16140. this.unregisterListeners();
  16141. this.tracks.length = 0;
  16142. this.tracksInGroup.length = 0;
  16143. this.currentTrack = null;
  16144. super.destroy();
  16145. }
  16146. onManifestLoading() {
  16147. this.tracks = [];
  16148. this.tracksInGroup = [];
  16149. this.groupIds = null;
  16150. this.currentTrack = null;
  16151. this.trackId = -1;
  16152. this.selectDefaultTrack = true;
  16153. }
  16154. onManifestParsed(event, data) {
  16155. this.tracks = data.audioTracks || [];
  16156. }
  16157. onAudioTrackLoaded(event, data) {
  16158. const {
  16159. id,
  16160. groupId,
  16161. details
  16162. } = data;
  16163. const trackInActiveGroup = this.tracksInGroup[id];
  16164. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16165. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16166. return;
  16167. }
  16168. const curDetails = trackInActiveGroup.details;
  16169. trackInActiveGroup.details = data.details;
  16170. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16171. if (id === this.trackId) {
  16172. this.playlistLoaded(id, data, curDetails);
  16173. }
  16174. }
  16175. onLevelLoading(event, data) {
  16176. this.switchLevel(data.level);
  16177. }
  16178. onLevelSwitching(event, data) {
  16179. this.switchLevel(data.level);
  16180. }
  16181. switchLevel(levelIndex) {
  16182. const levelInfo = this.hls.levels[levelIndex];
  16183. if (!levelInfo) {
  16184. return;
  16185. }
  16186. const audioGroups = levelInfo.audioGroups || null;
  16187. const currentGroups = this.groupIds;
  16188. let currentTrack = this.currentTrack;
  16189. 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)) {
  16190. this.groupIds = audioGroups;
  16191. this.trackId = -1;
  16192. this.currentTrack = null;
  16193. const audioTracks = this.tracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  16194. if (audioTracks.length) {
  16195. // Disable selectDefaultTrack if there are no default tracks
  16196. if (this.selectDefaultTrack && !audioTracks.some(track => track.default)) {
  16197. this.selectDefaultTrack = false;
  16198. }
  16199. // track.id should match hls.audioTracks index
  16200. audioTracks.forEach((track, i) => {
  16201. track.id = i;
  16202. });
  16203. } else if (!currentTrack && !this.tracksInGroup.length) {
  16204. // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks
  16205. return;
  16206. }
  16207. this.tracksInGroup = audioTracks;
  16208. // Find preferred track
  16209. const audioPreference = this.hls.config.audioPreference;
  16210. if (!currentTrack && audioPreference) {
  16211. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  16212. if (groupIndex > -1) {
  16213. currentTrack = audioTracks[groupIndex];
  16214. } else {
  16215. const allIndex = findMatchingOption(audioPreference, this.tracks);
  16216. currentTrack = this.tracks[allIndex];
  16217. }
  16218. }
  16219. // Select initial track
  16220. let trackId = this.findTrackId(currentTrack);
  16221. if (trackId === -1 && currentTrack) {
  16222. trackId = this.findTrackId(null);
  16223. }
  16224. // Dispatch events and load track if needed
  16225. const audioTracksUpdated = {
  16226. audioTracks
  16227. };
  16228. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(',')}`);
  16229. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  16230. const selectedTrackId = this.trackId;
  16231. if (trackId !== -1 && selectedTrackId === -1) {
  16232. this.setAudioTrack(trackId);
  16233. } else if (audioTracks.length && selectedTrackId === -1) {
  16234. var _this$groupIds;
  16235. 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}`);
  16236. this.warn(error.message);
  16237. this.hls.trigger(Events.ERROR, {
  16238. type: ErrorTypes.MEDIA_ERROR,
  16239. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  16240. fatal: true,
  16241. error
  16242. });
  16243. }
  16244. } else if (this.shouldReloadPlaylist(currentTrack)) {
  16245. // Retry playlist loading if no playlist is or has been loaded yet
  16246. this.setAudioTrack(this.trackId);
  16247. }
  16248. }
  16249. onError(event, data) {
  16250. if (data.fatal || !data.context) {
  16251. return;
  16252. }
  16253. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  16254. this.requestScheduled = -1;
  16255. this.checkRetry(data);
  16256. }
  16257. }
  16258. get allAudioTracks() {
  16259. return this.tracks;
  16260. }
  16261. get audioTracks() {
  16262. return this.tracksInGroup;
  16263. }
  16264. get audioTrack() {
  16265. return this.trackId;
  16266. }
  16267. set audioTrack(newId) {
  16268. // If audio track is selected from API then don't choose from the manifest default track
  16269. this.selectDefaultTrack = false;
  16270. this.setAudioTrack(newId);
  16271. }
  16272. setAudioOption(audioOption) {
  16273. const hls = this.hls;
  16274. hls.config.audioPreference = audioOption;
  16275. if (audioOption) {
  16276. const allAudioTracks = this.allAudioTracks;
  16277. this.selectDefaultTrack = false;
  16278. if (allAudioTracks.length) {
  16279. // First see if current option matches (no switch op)
  16280. const currentTrack = this.currentTrack;
  16281. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  16282. return currentTrack;
  16283. }
  16284. // Find option in available tracks (tracksInGroup)
  16285. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  16286. if (groupIndex > -1) {
  16287. const track = this.tracksInGroup[groupIndex];
  16288. this.setAudioTrack(groupIndex);
  16289. return track;
  16290. } else if (currentTrack) {
  16291. // Find option in nearest level audio group
  16292. let searchIndex = hls.loadLevel;
  16293. if (searchIndex === -1) {
  16294. searchIndex = hls.firstAutoLevel;
  16295. }
  16296. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  16297. if (switchIndex === -1) {
  16298. // could not find matching variant
  16299. return null;
  16300. }
  16301. // and switch level to acheive the audio group switch
  16302. hls.nextLoadLevel = switchIndex;
  16303. }
  16304. if (audioOption.channels || audioOption.audioCodec) {
  16305. // Could not find a match with codec / channels predicate
  16306. // Find a match without channels or codec
  16307. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  16308. if (withoutCodecAndChannelsMatch > -1) {
  16309. return allAudioTracks[withoutCodecAndChannelsMatch];
  16310. }
  16311. }
  16312. }
  16313. }
  16314. return null;
  16315. }
  16316. setAudioTrack(newId) {
  16317. const tracks = this.tracksInGroup;
  16318. // check if level idx is valid
  16319. if (newId < 0 || newId >= tracks.length) {
  16320. this.warn(`Invalid audio track id: ${newId}`);
  16321. return;
  16322. }
  16323. // stopping live reloading timer if any
  16324. this.clearTimer();
  16325. this.selectDefaultTrack = false;
  16326. const lastTrack = this.currentTrack;
  16327. const track = tracks[newId];
  16328. const trackLoaded = track.details && !track.details.live;
  16329. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  16330. return;
  16331. }
  16332. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  16333. this.trackId = newId;
  16334. this.currentTrack = track;
  16335. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  16336. // Do not reload track unless live
  16337. if (trackLoaded) {
  16338. return;
  16339. }
  16340. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  16341. this.loadPlaylist(hlsUrlParameters);
  16342. }
  16343. findTrackId(currentTrack) {
  16344. const audioTracks = this.tracksInGroup;
  16345. for (let i = 0; i < audioTracks.length; i++) {
  16346. const track = audioTracks[i];
  16347. if (this.selectDefaultTrack && !track.default) {
  16348. continue;
  16349. }
  16350. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  16351. return i;
  16352. }
  16353. }
  16354. if (currentTrack) {
  16355. const {
  16356. name,
  16357. lang,
  16358. assocLang,
  16359. characteristics,
  16360. audioCodec,
  16361. channels
  16362. } = currentTrack;
  16363. for (let i = 0; i < audioTracks.length; i++) {
  16364. const track = audioTracks[i];
  16365. if (matchesOption({
  16366. name,
  16367. lang,
  16368. assocLang,
  16369. characteristics,
  16370. audioCodec,
  16371. channels
  16372. }, track, audioMatchPredicate)) {
  16373. return i;
  16374. }
  16375. }
  16376. for (let i = 0; i < audioTracks.length; i++) {
  16377. const track = audioTracks[i];
  16378. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  16379. return i;
  16380. }
  16381. }
  16382. for (let i = 0; i < audioTracks.length; i++) {
  16383. const track = audioTracks[i];
  16384. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  16385. return i;
  16386. }
  16387. }
  16388. }
  16389. return -1;
  16390. }
  16391. loadPlaylist(hlsUrlParameters) {
  16392. const audioTrack = this.currentTrack;
  16393. if (this.shouldLoadPlaylist(audioTrack) && audioTrack) {
  16394. super.loadPlaylist();
  16395. const id = audioTrack.id;
  16396. const groupId = audioTrack.groupId;
  16397. let url = audioTrack.url;
  16398. if (hlsUrlParameters) {
  16399. try {
  16400. url = hlsUrlParameters.addDirectives(url);
  16401. } catch (error) {
  16402. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  16403. }
  16404. }
  16405. // track not retrieved yet, or live playlist we need to (re)load it
  16406. this.log(`loading audio-track playlist ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}`);
  16407. this.clearTimer();
  16408. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  16409. url,
  16410. id,
  16411. groupId,
  16412. deliveryDirectives: hlsUrlParameters || null
  16413. });
  16414. }
  16415. }
  16416. }
  16417. const TICK_INTERVAL$1 = 500; // how often to tick in ms
  16418. class SubtitleStreamController extends BaseStreamController {
  16419. constructor(hls, fragmentTracker, keyLoader) {
  16420. super(hls, fragmentTracker, keyLoader, '[subtitle-stream-controller]', PlaylistLevelType.SUBTITLE);
  16421. this.currentTrackId = -1;
  16422. this.tracksBuffered = [];
  16423. this.mainDetails = null;
  16424. this._registerListeners();
  16425. }
  16426. onHandlerDestroying() {
  16427. this._unregisterListeners();
  16428. super.onHandlerDestroying();
  16429. this.mainDetails = null;
  16430. }
  16431. _registerListeners() {
  16432. const {
  16433. hls
  16434. } = this;
  16435. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16436. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16437. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16438. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16439. hls.on(Events.ERROR, this.onError, this);
  16440. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  16441. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  16442. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16443. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  16444. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16445. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16446. }
  16447. _unregisterListeners() {
  16448. const {
  16449. hls
  16450. } = this;
  16451. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16452. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16453. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16454. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16455. hls.off(Events.ERROR, this.onError, this);
  16456. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  16457. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  16458. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16459. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  16460. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16461. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16462. }
  16463. startLoad(startPosition) {
  16464. this.stopLoad();
  16465. this.state = State.IDLE;
  16466. this.setInterval(TICK_INTERVAL$1);
  16467. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  16468. this.tick();
  16469. }
  16470. onManifestLoading() {
  16471. this.mainDetails = null;
  16472. this.fragmentTracker.removeAllFragments();
  16473. }
  16474. onMediaDetaching() {
  16475. this.tracksBuffered = [];
  16476. super.onMediaDetaching();
  16477. }
  16478. onLevelLoaded(event, data) {
  16479. this.mainDetails = data.details;
  16480. }
  16481. onSubtitleFragProcessed(event, data) {
  16482. const {
  16483. frag,
  16484. success
  16485. } = data;
  16486. this.fragPrevious = frag;
  16487. this.state = State.IDLE;
  16488. if (!success) {
  16489. return;
  16490. }
  16491. const buffered = this.tracksBuffered[this.currentTrackId];
  16492. if (!buffered) {
  16493. return;
  16494. }
  16495. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  16496. // so we can re-use the logic used to detect how much has been buffered
  16497. let timeRange;
  16498. const fragStart = frag.start;
  16499. for (let i = 0; i < buffered.length; i++) {
  16500. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  16501. timeRange = buffered[i];
  16502. break;
  16503. }
  16504. }
  16505. const fragEnd = frag.start + frag.duration;
  16506. if (timeRange) {
  16507. timeRange.end = fragEnd;
  16508. } else {
  16509. timeRange = {
  16510. start: fragStart,
  16511. end: fragEnd
  16512. };
  16513. buffered.push(timeRange);
  16514. }
  16515. this.fragmentTracker.fragBuffered(frag);
  16516. this.fragBufferedComplete(frag, null);
  16517. }
  16518. onBufferFlushing(event, data) {
  16519. const {
  16520. startOffset,
  16521. endOffset
  16522. } = data;
  16523. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  16524. const endOffsetSubtitles = endOffset - 1;
  16525. if (endOffsetSubtitles <= 0) {
  16526. return;
  16527. }
  16528. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  16529. this.tracksBuffered.forEach(buffered => {
  16530. for (let i = 0; i < buffered.length;) {
  16531. if (buffered[i].end <= endOffsetSubtitles) {
  16532. buffered.shift();
  16533. continue;
  16534. } else if (buffered[i].start < endOffsetSubtitles) {
  16535. buffered[i].start = endOffsetSubtitles;
  16536. } else {
  16537. break;
  16538. }
  16539. i++;
  16540. }
  16541. });
  16542. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  16543. }
  16544. }
  16545. onFragBuffered(event, data) {
  16546. if (!this.loadedmetadata && data.frag.type === PlaylistLevelType.MAIN) {
  16547. var _this$media;
  16548. if ((_this$media = this.media) != null && _this$media.buffered.length) {
  16549. this.loadedmetadata = true;
  16550. }
  16551. }
  16552. }
  16553. // If something goes wrong, proceed to next frag, if we were processing one.
  16554. onError(event, data) {
  16555. const frag = data.frag;
  16556. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  16557. if (data.details === ErrorDetails.FRAG_GAP) {
  16558. this.fragmentTracker.fragBuffered(frag, true);
  16559. }
  16560. if (this.fragCurrent) {
  16561. this.fragCurrent.abortRequests();
  16562. }
  16563. if (this.state !== State.STOPPED) {
  16564. this.state = State.IDLE;
  16565. }
  16566. }
  16567. }
  16568. // Got all new subtitle levels.
  16569. onSubtitleTracksUpdated(event, {
  16570. subtitleTracks
  16571. }) {
  16572. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  16573. this.levels = subtitleTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  16574. return;
  16575. }
  16576. this.tracksBuffered = [];
  16577. this.levels = subtitleTracks.map(mediaPlaylist => {
  16578. const level = new Level(mediaPlaylist);
  16579. this.tracksBuffered[level.id] = [];
  16580. return level;
  16581. });
  16582. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  16583. this.fragPrevious = null;
  16584. this.mediaBuffer = null;
  16585. }
  16586. onSubtitleTrackSwitch(event, data) {
  16587. var _this$levels;
  16588. this.currentTrackId = data.id;
  16589. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  16590. this.clearInterval();
  16591. return;
  16592. }
  16593. // Check if track has the necessary details to load fragments
  16594. const currentTrack = this.levels[this.currentTrackId];
  16595. if (currentTrack != null && currentTrack.details) {
  16596. this.mediaBuffer = this.mediaBufferTimeRanges;
  16597. } else {
  16598. this.mediaBuffer = null;
  16599. }
  16600. if (currentTrack) {
  16601. this.setInterval(TICK_INTERVAL$1);
  16602. }
  16603. }
  16604. // Got a new set of subtitle fragments.
  16605. onSubtitleTrackLoaded(event, data) {
  16606. var _track$details;
  16607. const {
  16608. currentTrackId,
  16609. levels
  16610. } = this;
  16611. const {
  16612. details: newDetails,
  16613. id: trackId
  16614. } = data;
  16615. if (!levels) {
  16616. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  16617. return;
  16618. }
  16619. const track = levels[trackId];
  16620. if (trackId >= levels.length || !track) {
  16621. return;
  16622. }
  16623. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  16624. this.mediaBuffer = this.mediaBufferTimeRanges;
  16625. let sliding = 0;
  16626. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  16627. const mainDetails = this.mainDetails;
  16628. if (newDetails.deltaUpdateFailed || !mainDetails) {
  16629. return;
  16630. }
  16631. const mainSlidingStartFragment = mainDetails.fragments[0];
  16632. if (!track.details) {
  16633. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  16634. alignMediaPlaylistByPDT(newDetails, mainDetails);
  16635. sliding = newDetails.fragments[0].start;
  16636. } else if (mainSlidingStartFragment) {
  16637. // line up live playlist with main so that fragments in range are loaded
  16638. sliding = mainSlidingStartFragment.start;
  16639. addSliding(newDetails, sliding);
  16640. }
  16641. } else {
  16642. var _this$levelLastLoaded;
  16643. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  16644. if (sliding === 0 && mainSlidingStartFragment) {
  16645. // realign with main when there is no overlap with last refresh
  16646. sliding = mainSlidingStartFragment.start;
  16647. addSliding(newDetails, sliding);
  16648. }
  16649. }
  16650. }
  16651. track.details = newDetails;
  16652. this.levelLastLoaded = track;
  16653. if (trackId !== currentTrackId) {
  16654. return;
  16655. }
  16656. if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
  16657. this.setStartPosition(this.mainDetails || newDetails, sliding);
  16658. }
  16659. // trigger handler right now
  16660. this.tick();
  16661. // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
  16662. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  16663. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  16664. if (!foundFrag) {
  16665. this.warn('Subtitle playlist not aligned with playback');
  16666. track.details = undefined;
  16667. }
  16668. }
  16669. }
  16670. _handleFragmentLoadComplete(fragLoadedData) {
  16671. const {
  16672. frag,
  16673. payload
  16674. } = fragLoadedData;
  16675. const decryptData = frag.decryptdata;
  16676. const hls = this.hls;
  16677. if (this.fragContextChanged(frag)) {
  16678. return;
  16679. }
  16680. // check to see if the payload needs to be decrypted
  16681. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  16682. const startTime = performance.now();
  16683. // decrypt the subtitles
  16684. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(err => {
  16685. hls.trigger(Events.ERROR, {
  16686. type: ErrorTypes.MEDIA_ERROR,
  16687. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  16688. fatal: false,
  16689. error: err,
  16690. reason: err.message,
  16691. frag
  16692. });
  16693. throw err;
  16694. }).then(decryptedData => {
  16695. const endTime = performance.now();
  16696. hls.trigger(Events.FRAG_DECRYPTED, {
  16697. frag,
  16698. payload: decryptedData,
  16699. stats: {
  16700. tstart: startTime,
  16701. tdecrypt: endTime
  16702. }
  16703. });
  16704. }).catch(err => {
  16705. this.warn(`${err.name}: ${err.message}`);
  16706. this.state = State.IDLE;
  16707. });
  16708. }
  16709. }
  16710. doTick() {
  16711. if (!this.media) {
  16712. this.state = State.IDLE;
  16713. return;
  16714. }
  16715. if (this.state === State.IDLE) {
  16716. const {
  16717. currentTrackId,
  16718. levels
  16719. } = this;
  16720. const track = levels == null ? void 0 : levels[currentTrackId];
  16721. if (!track || !levels.length || !track.details) {
  16722. return;
  16723. }
  16724. const {
  16725. config
  16726. } = this;
  16727. const currentTime = this.getLoadPosition();
  16728. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  16729. const {
  16730. end: targetBufferTime,
  16731. len: bufferLen
  16732. } = bufferedInfo;
  16733. const mainBufferInfo = this.getFwdBufferInfo(this.media, PlaylistLevelType.MAIN);
  16734. const trackDetails = track.details;
  16735. const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len) + trackDetails.levelTargetDuration;
  16736. if (bufferLen > maxBufLen) {
  16737. return;
  16738. }
  16739. const fragments = trackDetails.fragments;
  16740. const fragLen = fragments.length;
  16741. const end = trackDetails.edge;
  16742. let foundFrag = null;
  16743. const fragPrevious = this.fragPrevious;
  16744. if (targetBufferTime < end) {
  16745. const tolerance = config.maxFragLookUpTolerance;
  16746. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  16747. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  16748. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  16749. foundFrag = fragments[0];
  16750. }
  16751. } else {
  16752. foundFrag = fragments[fragLen - 1];
  16753. }
  16754. if (!foundFrag) {
  16755. return;
  16756. }
  16757. foundFrag = this.mapToInitFragWhenRequired(foundFrag);
  16758. if (foundFrag.sn !== 'initSegment') {
  16759. // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment
  16760. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  16761. const prevFrag = fragments[curSNIdx - 1];
  16762. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  16763. foundFrag = prevFrag;
  16764. }
  16765. }
  16766. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  16767. // only load if fragment is not loaded
  16768. this.loadFragment(foundFrag, track, targetBufferTime);
  16769. }
  16770. }
  16771. }
  16772. getMaxBufferLength(mainBufferLength) {
  16773. const maxConfigBuffer = super.getMaxBufferLength();
  16774. if (!mainBufferLength) {
  16775. return maxConfigBuffer;
  16776. }
  16777. return Math.max(maxConfigBuffer, mainBufferLength);
  16778. }
  16779. loadFragment(frag, level, targetBufferTime) {
  16780. this.fragCurrent = frag;
  16781. if (frag.sn === 'initSegment') {
  16782. this._loadInitSegment(frag, level);
  16783. } else {
  16784. this.startFragRequested = true;
  16785. super.loadFragment(frag, level, targetBufferTime);
  16786. }
  16787. }
  16788. get mediaBufferTimeRanges() {
  16789. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  16790. }
  16791. }
  16792. class BufferableInstance {
  16793. constructor(timeranges) {
  16794. this.buffered = void 0;
  16795. const getRange = (name, index, length) => {
  16796. index = index >>> 0;
  16797. if (index > length - 1) {
  16798. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  16799. }
  16800. return timeranges[index][name];
  16801. };
  16802. this.buffered = {
  16803. get length() {
  16804. return timeranges.length;
  16805. },
  16806. end(index) {
  16807. return getRange('end', index, timeranges.length);
  16808. },
  16809. start(index) {
  16810. return getRange('start', index, timeranges.length);
  16811. }
  16812. };
  16813. }
  16814. }
  16815. class SubtitleTrackController extends BasePlaylistController {
  16816. constructor(hls) {
  16817. super(hls, '[subtitle-track-controller]');
  16818. this.media = null;
  16819. this.tracks = [];
  16820. this.groupIds = null;
  16821. this.tracksInGroup = [];
  16822. this.trackId = -1;
  16823. this.currentTrack = null;
  16824. this.selectDefaultTrack = true;
  16825. this.queuedDefaultTrack = -1;
  16826. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  16827. this.useTextTrackPolling = false;
  16828. this.subtitlePollingInterval = -1;
  16829. this._subtitleDisplay = true;
  16830. this.onTextTracksChanged = () => {
  16831. if (!this.useTextTrackPolling) {
  16832. self.clearInterval(this.subtitlePollingInterval);
  16833. }
  16834. // Media is undefined when switching streams via loadSource()
  16835. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  16836. return;
  16837. }
  16838. let textTrack = null;
  16839. const tracks = filterSubtitleTracks(this.media.textTracks);
  16840. for (let i = 0; i < tracks.length; i++) {
  16841. if (tracks[i].mode === 'hidden') {
  16842. // Do not break in case there is a following track with showing.
  16843. textTrack = tracks[i];
  16844. } else if (tracks[i].mode === 'showing') {
  16845. textTrack = tracks[i];
  16846. break;
  16847. }
  16848. }
  16849. // Find internal track index for TextTrack
  16850. const trackId = this.findTrackForTextTrack(textTrack);
  16851. if (this.subtitleTrack !== trackId) {
  16852. this.setSubtitleTrack(trackId);
  16853. }
  16854. };
  16855. this.registerListeners();
  16856. }
  16857. destroy() {
  16858. this.unregisterListeners();
  16859. this.tracks.length = 0;
  16860. this.tracksInGroup.length = 0;
  16861. this.currentTrack = null;
  16862. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  16863. super.destroy();
  16864. }
  16865. get subtitleDisplay() {
  16866. return this._subtitleDisplay;
  16867. }
  16868. set subtitleDisplay(value) {
  16869. this._subtitleDisplay = value;
  16870. if (this.trackId > -1) {
  16871. this.toggleTrackModes();
  16872. }
  16873. }
  16874. registerListeners() {
  16875. const {
  16876. hls
  16877. } = this;
  16878. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16879. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16880. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16881. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16882. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16883. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16884. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16885. hls.on(Events.ERROR, this.onError, this);
  16886. }
  16887. unregisterListeners() {
  16888. const {
  16889. hls
  16890. } = this;
  16891. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16892. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16893. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16894. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16895. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16896. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16897. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16898. hls.off(Events.ERROR, this.onError, this);
  16899. }
  16900. // Listen for subtitle track change, then extract the current track ID.
  16901. onMediaAttached(event, data) {
  16902. this.media = data.media;
  16903. if (!this.media) {
  16904. return;
  16905. }
  16906. if (this.queuedDefaultTrack > -1) {
  16907. this.subtitleTrack = this.queuedDefaultTrack;
  16908. this.queuedDefaultTrack = -1;
  16909. }
  16910. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  16911. if (this.useTextTrackPolling) {
  16912. this.pollTrackChange(500);
  16913. } else {
  16914. this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
  16915. }
  16916. }
  16917. pollTrackChange(timeout) {
  16918. self.clearInterval(this.subtitlePollingInterval);
  16919. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  16920. }
  16921. onMediaDetaching() {
  16922. if (!this.media) {
  16923. return;
  16924. }
  16925. self.clearInterval(this.subtitlePollingInterval);
  16926. if (!this.useTextTrackPolling) {
  16927. this.media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
  16928. }
  16929. if (this.trackId > -1) {
  16930. this.queuedDefaultTrack = this.trackId;
  16931. }
  16932. const textTracks = filterSubtitleTracks(this.media.textTracks);
  16933. // Clear loaded cues on media detachment from tracks
  16934. textTracks.forEach(track => {
  16935. clearCurrentCues(track);
  16936. });
  16937. // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
  16938. this.subtitleTrack = -1;
  16939. this.media = null;
  16940. }
  16941. onManifestLoading() {
  16942. this.tracks = [];
  16943. this.groupIds = null;
  16944. this.tracksInGroup = [];
  16945. this.trackId = -1;
  16946. this.currentTrack = null;
  16947. this.selectDefaultTrack = true;
  16948. }
  16949. // Fired whenever a new manifest is loaded.
  16950. onManifestParsed(event, data) {
  16951. this.tracks = data.subtitleTracks;
  16952. }
  16953. onSubtitleTrackLoaded(event, data) {
  16954. const {
  16955. id,
  16956. groupId,
  16957. details
  16958. } = data;
  16959. const trackInActiveGroup = this.tracksInGroup[id];
  16960. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16961. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16962. return;
  16963. }
  16964. const curDetails = trackInActiveGroup.details;
  16965. trackInActiveGroup.details = data.details;
  16966. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16967. if (id === this.trackId) {
  16968. this.playlistLoaded(id, data, curDetails);
  16969. }
  16970. }
  16971. onLevelLoading(event, data) {
  16972. this.switchLevel(data.level);
  16973. }
  16974. onLevelSwitching(event, data) {
  16975. this.switchLevel(data.level);
  16976. }
  16977. switchLevel(levelIndex) {
  16978. const levelInfo = this.hls.levels[levelIndex];
  16979. if (!levelInfo) {
  16980. return;
  16981. }
  16982. const subtitleGroups = levelInfo.subtitleGroups || null;
  16983. const currentGroups = this.groupIds;
  16984. let currentTrack = this.currentTrack;
  16985. 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)) {
  16986. this.groupIds = subtitleGroups;
  16987. this.trackId = -1;
  16988. this.currentTrack = null;
  16989. const subtitleTracks = this.tracks.filter(track => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  16990. if (subtitleTracks.length) {
  16991. // Disable selectDefaultTrack if there are no default tracks
  16992. if (this.selectDefaultTrack && !subtitleTracks.some(track => track.default)) {
  16993. this.selectDefaultTrack = false;
  16994. }
  16995. // track.id should match hls.audioTracks index
  16996. subtitleTracks.forEach((track, i) => {
  16997. track.id = i;
  16998. });
  16999. } else if (!currentTrack && !this.tracksInGroup.length) {
  17000. // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks
  17001. return;
  17002. }
  17003. this.tracksInGroup = subtitleTracks;
  17004. // Find preferred track
  17005. const subtitlePreference = this.hls.config.subtitlePreference;
  17006. if (!currentTrack && subtitlePreference) {
  17007. this.selectDefaultTrack = false;
  17008. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  17009. if (groupIndex > -1) {
  17010. currentTrack = subtitleTracks[groupIndex];
  17011. } else {
  17012. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  17013. currentTrack = this.tracks[allIndex];
  17014. }
  17015. }
  17016. // Select initial track
  17017. let trackId = this.findTrackId(currentTrack);
  17018. if (trackId === -1 && currentTrack) {
  17019. trackId = this.findTrackId(null);
  17020. }
  17021. // Dispatch events and load track if needed
  17022. const subtitleTracksUpdated = {
  17023. subtitleTracks
  17024. };
  17025. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(',')}" group-id`);
  17026. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  17027. if (trackId !== -1 && this.trackId === -1) {
  17028. this.setSubtitleTrack(trackId);
  17029. }
  17030. } else if (this.shouldReloadPlaylist(currentTrack)) {
  17031. // Retry playlist loading if no playlist is or has been loaded yet
  17032. this.setSubtitleTrack(this.trackId);
  17033. }
  17034. }
  17035. findTrackId(currentTrack) {
  17036. const tracks = this.tracksInGroup;
  17037. const selectDefault = this.selectDefaultTrack;
  17038. for (let i = 0; i < tracks.length; i++) {
  17039. const track = tracks[i];
  17040. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  17041. continue;
  17042. }
  17043. if (!currentTrack || matchesOption(track, currentTrack)) {
  17044. return i;
  17045. }
  17046. }
  17047. if (currentTrack) {
  17048. for (let i = 0; i < tracks.length; i++) {
  17049. const track = tracks[i];
  17050. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  17051. return i;
  17052. }
  17053. }
  17054. for (let i = 0; i < tracks.length; i++) {
  17055. const track = tracks[i];
  17056. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  17057. return i;
  17058. }
  17059. }
  17060. }
  17061. return -1;
  17062. }
  17063. findTrackForTextTrack(textTrack) {
  17064. if (textTrack) {
  17065. const tracks = this.tracksInGroup;
  17066. for (let i = 0; i < tracks.length; i++) {
  17067. const track = tracks[i];
  17068. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  17069. return i;
  17070. }
  17071. }
  17072. }
  17073. return -1;
  17074. }
  17075. onError(event, data) {
  17076. if (data.fatal || !data.context) {
  17077. return;
  17078. }
  17079. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  17080. this.checkRetry(data);
  17081. }
  17082. }
  17083. get allSubtitleTracks() {
  17084. return this.tracks;
  17085. }
  17086. /** get alternate subtitle tracks list from playlist **/
  17087. get subtitleTracks() {
  17088. return this.tracksInGroup;
  17089. }
  17090. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  17091. get subtitleTrack() {
  17092. return this.trackId;
  17093. }
  17094. set subtitleTrack(newId) {
  17095. this.selectDefaultTrack = false;
  17096. this.setSubtitleTrack(newId);
  17097. }
  17098. setSubtitleOption(subtitleOption) {
  17099. this.hls.config.subtitlePreference = subtitleOption;
  17100. if (subtitleOption) {
  17101. const allSubtitleTracks = this.allSubtitleTracks;
  17102. this.selectDefaultTrack = false;
  17103. if (allSubtitleTracks.length) {
  17104. // First see if current option matches (no switch op)
  17105. const currentTrack = this.currentTrack;
  17106. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  17107. return currentTrack;
  17108. }
  17109. // Find option in current group
  17110. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  17111. if (groupIndex > -1) {
  17112. const track = this.tracksInGroup[groupIndex];
  17113. this.setSubtitleTrack(groupIndex);
  17114. return track;
  17115. } else if (currentTrack) {
  17116. // If this is not the initial selection return null
  17117. // option should have matched one in active group
  17118. return null;
  17119. } else {
  17120. // Find the option in all tracks for initial selection
  17121. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  17122. if (allIndex > -1) {
  17123. return allSubtitleTracks[allIndex];
  17124. }
  17125. }
  17126. }
  17127. }
  17128. return null;
  17129. }
  17130. loadPlaylist(hlsUrlParameters) {
  17131. super.loadPlaylist();
  17132. const currentTrack = this.currentTrack;
  17133. if (this.shouldLoadPlaylist(currentTrack) && currentTrack) {
  17134. const id = currentTrack.id;
  17135. const groupId = currentTrack.groupId;
  17136. let url = currentTrack.url;
  17137. if (hlsUrlParameters) {
  17138. try {
  17139. url = hlsUrlParameters.addDirectives(url);
  17140. } catch (error) {
  17141. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  17142. }
  17143. }
  17144. this.log(`Loading subtitle playlist for id ${id}`);
  17145. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  17146. url,
  17147. id,
  17148. groupId,
  17149. deliveryDirectives: hlsUrlParameters || null
  17150. });
  17151. }
  17152. }
  17153. /**
  17154. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  17155. * This operates on the DOM textTracks.
  17156. * A value of -1 will disable all subtitle tracks.
  17157. */
  17158. toggleTrackModes() {
  17159. const {
  17160. media
  17161. } = this;
  17162. if (!media) {
  17163. return;
  17164. }
  17165. const textTracks = filterSubtitleTracks(media.textTracks);
  17166. const currentTrack = this.currentTrack;
  17167. let nextTrack;
  17168. if (currentTrack) {
  17169. nextTrack = textTracks.filter(textTrack => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  17170. if (!nextTrack) {
  17171. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  17172. }
  17173. }
  17174. [].slice.call(textTracks).forEach(track => {
  17175. if (track.mode !== 'disabled' && track !== nextTrack) {
  17176. track.mode = 'disabled';
  17177. }
  17178. });
  17179. if (nextTrack) {
  17180. const mode = this.subtitleDisplay ? 'showing' : 'hidden';
  17181. if (nextTrack.mode !== mode) {
  17182. nextTrack.mode = mode;
  17183. }
  17184. }
  17185. }
  17186. /**
  17187. * This method is responsible for validating the subtitle index and periodically reloading if live.
  17188. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  17189. */
  17190. setSubtitleTrack(newId) {
  17191. const tracks = this.tracksInGroup;
  17192. // setting this.subtitleTrack will trigger internal logic
  17193. // if media has not been attached yet, it will fail
  17194. // we keep a reference to the default track id
  17195. // and we'll set subtitleTrack when onMediaAttached is triggered
  17196. if (!this.media) {
  17197. this.queuedDefaultTrack = newId;
  17198. return;
  17199. }
  17200. // exit if track id as already set or invalid
  17201. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  17202. this.warn(`Invalid subtitle track id: ${newId}`);
  17203. return;
  17204. }
  17205. // stopping live reloading timer if any
  17206. this.clearTimer();
  17207. this.selectDefaultTrack = false;
  17208. const lastTrack = this.currentTrack;
  17209. const track = tracks[newId] || null;
  17210. this.trackId = newId;
  17211. this.currentTrack = track;
  17212. this.toggleTrackModes();
  17213. if (!track) {
  17214. // switch to -1
  17215. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  17216. id: newId
  17217. });
  17218. return;
  17219. }
  17220. const trackLoaded = !!track.details && !track.details.live;
  17221. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  17222. return;
  17223. }
  17224. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ''));
  17225. const {
  17226. id,
  17227. groupId = '',
  17228. name,
  17229. type,
  17230. url
  17231. } = track;
  17232. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  17233. id,
  17234. groupId,
  17235. name,
  17236. type,
  17237. url
  17238. });
  17239. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  17240. this.loadPlaylist(hlsUrlParameters);
  17241. }
  17242. }
  17243. class BufferOperationQueue {
  17244. constructor(sourceBufferReference) {
  17245. this.buffers = void 0;
  17246. this.queues = {
  17247. video: [],
  17248. audio: [],
  17249. audiovideo: []
  17250. };
  17251. this.buffers = sourceBufferReference;
  17252. }
  17253. append(operation, type, pending) {
  17254. const queue = this.queues[type];
  17255. queue.push(operation);
  17256. if (queue.length === 1 && !pending) {
  17257. this.executeNext(type);
  17258. }
  17259. }
  17260. insertAbort(operation, type) {
  17261. const queue = this.queues[type];
  17262. queue.unshift(operation);
  17263. this.executeNext(type);
  17264. }
  17265. appendBlocker(type) {
  17266. let execute;
  17267. const promise = new Promise(resolve => {
  17268. execute = resolve;
  17269. });
  17270. const operation = {
  17271. execute,
  17272. onStart: () => {},
  17273. onComplete: () => {},
  17274. onError: () => {}
  17275. };
  17276. this.append(operation, type);
  17277. return promise;
  17278. }
  17279. executeNext(type) {
  17280. const queue = this.queues[type];
  17281. if (queue.length) {
  17282. const operation = queue[0];
  17283. try {
  17284. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  17285. // which do not end with this event must call _onSBUpdateEnd manually
  17286. operation.execute();
  17287. } catch (error) {
  17288. logger.warn(`[buffer-operation-queue]: Exception executing "${type}" SourceBuffer operation: ${error}`);
  17289. operation.onError(error);
  17290. // Only shift the current operation off, otherwise the updateend handler will do this for us
  17291. const sb = this.buffers[type];
  17292. if (!(sb != null && sb.updating)) {
  17293. this.shiftAndExecuteNext(type);
  17294. }
  17295. }
  17296. }
  17297. }
  17298. shiftAndExecuteNext(type) {
  17299. this.queues[type].shift();
  17300. this.executeNext(type);
  17301. }
  17302. current(type) {
  17303. return this.queues[type][0];
  17304. }
  17305. }
  17306. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  17307. class BufferController {
  17308. constructor(hls) {
  17309. // The level details used to determine duration, target-duration and live
  17310. this.details = null;
  17311. // cache the self generated object url to detect hijack of video tag
  17312. this._objectUrl = null;
  17313. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  17314. this.operationQueue = void 0;
  17315. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  17316. this.listeners = void 0;
  17317. this.hls = void 0;
  17318. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  17319. this.bufferCodecEventsExpected = 0;
  17320. // The total number of BUFFER_CODEC events received
  17321. this._bufferCodecEventsTotal = 0;
  17322. // A reference to the attached media element
  17323. this.media = null;
  17324. // A reference to the active media source
  17325. this.mediaSource = null;
  17326. // Last MP3 audio chunk appended
  17327. this.lastMpegAudioChunk = null;
  17328. this.appendSource = void 0;
  17329. // counters
  17330. this.appendErrors = {
  17331. audio: 0,
  17332. video: 0,
  17333. audiovideo: 0
  17334. };
  17335. this.tracks = {};
  17336. this.pendingTracks = {};
  17337. this.sourceBuffer = void 0;
  17338. this.log = void 0;
  17339. this.warn = void 0;
  17340. this.error = void 0;
  17341. this._onEndStreaming = event => {
  17342. if (!this.hls) {
  17343. return;
  17344. }
  17345. this.hls.pauseBuffering();
  17346. };
  17347. this._onStartStreaming = event => {
  17348. if (!this.hls) {
  17349. return;
  17350. }
  17351. this.hls.resumeBuffering();
  17352. };
  17353. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  17354. this._onMediaSourceOpen = () => {
  17355. const {
  17356. media,
  17357. mediaSource
  17358. } = this;
  17359. this.log('Media source opened');
  17360. if (media) {
  17361. media.removeEventListener('emptied', this._onMediaEmptied);
  17362. this.updateMediaElementDuration();
  17363. this.hls.trigger(Events.MEDIA_ATTACHED, {
  17364. media,
  17365. mediaSource: mediaSource
  17366. });
  17367. }
  17368. if (mediaSource) {
  17369. // once received, don't listen anymore to sourceopen event
  17370. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  17371. }
  17372. this.checkPendingTracks();
  17373. };
  17374. this._onMediaSourceClose = () => {
  17375. this.log('Media source closed');
  17376. };
  17377. this._onMediaSourceEnded = () => {
  17378. this.log('Media source ended');
  17379. };
  17380. this._onMediaEmptied = () => {
  17381. const {
  17382. mediaSrc,
  17383. _objectUrl
  17384. } = this;
  17385. if (mediaSrc !== _objectUrl) {
  17386. logger.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  17387. }
  17388. };
  17389. this.hls = hls;
  17390. const logPrefix = '[buffer-controller]';
  17391. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  17392. this.log = logger.log.bind(logger, logPrefix);
  17393. this.warn = logger.warn.bind(logger, logPrefix);
  17394. this.error = logger.error.bind(logger, logPrefix);
  17395. this._initSourceBuffer();
  17396. this.registerListeners();
  17397. }
  17398. hasSourceTypes() {
  17399. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  17400. }
  17401. destroy() {
  17402. this.unregisterListeners();
  17403. this.details = null;
  17404. this.lastMpegAudioChunk = null;
  17405. // @ts-ignore
  17406. this.hls = null;
  17407. }
  17408. registerListeners() {
  17409. const {
  17410. hls
  17411. } = this;
  17412. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17413. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17414. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17415. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17416. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  17417. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17418. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17419. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  17420. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17421. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17422. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  17423. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  17424. }
  17425. unregisterListeners() {
  17426. const {
  17427. hls
  17428. } = this;
  17429. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17430. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17431. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17432. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17433. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  17434. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17435. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17436. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  17437. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17438. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17439. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  17440. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  17441. }
  17442. _initSourceBuffer() {
  17443. this.sourceBuffer = {};
  17444. this.operationQueue = new BufferOperationQueue(this.sourceBuffer);
  17445. this.listeners = {
  17446. audio: [],
  17447. video: [],
  17448. audiovideo: []
  17449. };
  17450. this.appendErrors = {
  17451. audio: 0,
  17452. video: 0,
  17453. audiovideo: 0
  17454. };
  17455. this.lastMpegAudioChunk = null;
  17456. }
  17457. onManifestLoading() {
  17458. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;
  17459. this.details = null;
  17460. }
  17461. onManifestParsed(event, data) {
  17462. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  17463. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  17464. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  17465. // it will contain the expected nb of source buffers, no need to compute it
  17466. let codecEvents = 2;
  17467. if (data.audio && !data.video || !data.altAudio || !true) {
  17468. codecEvents = 1;
  17469. }
  17470. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  17471. this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);
  17472. }
  17473. onMediaAttaching(event, data) {
  17474. const media = this.media = data.media;
  17475. const MediaSource = getMediaSource(this.appendSource);
  17476. if (media && MediaSource) {
  17477. var _ms$constructor;
  17478. const ms = this.mediaSource = new MediaSource();
  17479. this.log(`created media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
  17480. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  17481. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  17482. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  17483. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  17484. if (this.appendSource) {
  17485. ms.addEventListener('startstreaming', this._onStartStreaming);
  17486. ms.addEventListener('endstreaming', this._onEndStreaming);
  17487. }
  17488. // cache the locally generated object url
  17489. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  17490. // link video and media Source
  17491. if (this.appendSource) {
  17492. try {
  17493. media.removeAttribute('src');
  17494. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  17495. const MMS = self.ManagedMediaSource;
  17496. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  17497. removeSourceChildren(media);
  17498. addSource(media, objectUrl);
  17499. media.load();
  17500. } catch (error) {
  17501. media.src = objectUrl;
  17502. }
  17503. } else {
  17504. media.src = objectUrl;
  17505. }
  17506. media.addEventListener('emptied', this._onMediaEmptied);
  17507. }
  17508. }
  17509. onMediaDetaching() {
  17510. const {
  17511. media,
  17512. mediaSource,
  17513. _objectUrl
  17514. } = this;
  17515. if (mediaSource) {
  17516. this.log('media source detaching');
  17517. if (mediaSource.readyState === 'open') {
  17518. try {
  17519. // endOfStream could trigger exception if any sourcebuffer is in updating state
  17520. // we don't really care about checking sourcebuffer state here,
  17521. // as we are anyway detaching the MediaSource
  17522. // let's just avoid this exception to propagate
  17523. mediaSource.endOfStream();
  17524. } catch (err) {
  17525. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  17526. }
  17527. }
  17528. // Clean up the SourceBuffers by invoking onBufferReset
  17529. this.onBufferReset();
  17530. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  17531. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  17532. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  17533. if (this.appendSource) {
  17534. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  17535. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  17536. }
  17537. // Detach properly the MediaSource from the HTMLMediaElement as
  17538. // suggested in https://github.com/w3c/media-source/issues/53.
  17539. if (media) {
  17540. media.removeEventListener('emptied', this._onMediaEmptied);
  17541. if (_objectUrl) {
  17542. self.URL.revokeObjectURL(_objectUrl);
  17543. }
  17544. // clean up video tag src only if it's our own url. some external libraries might
  17545. // hijack the video tag and change its 'src' without destroying the Hls instance first
  17546. if (this.mediaSrc === _objectUrl) {
  17547. media.removeAttribute('src');
  17548. if (this.appendSource) {
  17549. removeSourceChildren(media);
  17550. }
  17551. media.load();
  17552. } else {
  17553. this.warn('media|source.src was changed by a third party - skip cleanup');
  17554. }
  17555. }
  17556. this.mediaSource = null;
  17557. this.media = null;
  17558. this._objectUrl = null;
  17559. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  17560. this.pendingTracks = {};
  17561. this.tracks = {};
  17562. }
  17563. this.hls.trigger(Events.MEDIA_DETACHED, undefined);
  17564. }
  17565. onBufferReset() {
  17566. this.getSourceBufferTypes().forEach(type => {
  17567. this.resetBuffer(type);
  17568. });
  17569. this._initSourceBuffer();
  17570. }
  17571. resetBuffer(type) {
  17572. const sb = this.sourceBuffer[type];
  17573. try {
  17574. if (sb) {
  17575. var _this$mediaSource;
  17576. this.removeBufferListeners(type);
  17577. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  17578. // accessing it
  17579. this.sourceBuffer[type] = undefined;
  17580. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  17581. this.mediaSource.removeSourceBuffer(sb);
  17582. }
  17583. }
  17584. } catch (err) {
  17585. this.warn(`onBufferReset ${type}`, err);
  17586. }
  17587. }
  17588. onBufferCodecs(event, data) {
  17589. const sourceBufferCount = this.getSourceBufferTypes().length;
  17590. const trackNames = Object.keys(data);
  17591. trackNames.forEach(trackName => {
  17592. if (sourceBufferCount) {
  17593. // check if SourceBuffer codec needs to change
  17594. const track = this.tracks[trackName];
  17595. if (track && typeof track.buffer.changeType === 'function') {
  17596. var _trackCodec;
  17597. const {
  17598. id,
  17599. codec,
  17600. levelCodec,
  17601. container,
  17602. metadata
  17603. } = data[trackName];
  17604. const currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec);
  17605. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  17606. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  17607. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  17608. if (trackCodec && currentCodec !== nextCodec) {
  17609. if (trackName.slice(0, 5) === 'audio') {
  17610. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  17611. }
  17612. const mimeType = `${container};codecs=${trackCodec}`;
  17613. this.appendChangeType(trackName, mimeType);
  17614. this.log(`switching codec ${currentCodecFull} to ${trackCodec}`);
  17615. this.tracks[trackName] = {
  17616. buffer: track.buffer,
  17617. codec,
  17618. container,
  17619. levelCodec,
  17620. metadata,
  17621. id
  17622. };
  17623. }
  17624. }
  17625. } else {
  17626. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  17627. this.pendingTracks[trackName] = data[trackName];
  17628. }
  17629. });
  17630. // if sourcebuffers already created, do nothing ...
  17631. if (sourceBufferCount) {
  17632. return;
  17633. }
  17634. const bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  17635. if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {
  17636. this.log(`${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(',')}`);
  17637. this.bufferCodecEventsExpected = bufferCodecEventsExpected;
  17638. }
  17639. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  17640. this.checkPendingTracks();
  17641. }
  17642. }
  17643. appendChangeType(type, mimeType) {
  17644. const {
  17645. operationQueue
  17646. } = this;
  17647. const operation = {
  17648. execute: () => {
  17649. const sb = this.sourceBuffer[type];
  17650. if (sb) {
  17651. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  17652. sb.changeType(mimeType);
  17653. }
  17654. operationQueue.shiftAndExecuteNext(type);
  17655. },
  17656. onStart: () => {},
  17657. onComplete: () => {},
  17658. onError: error => {
  17659. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  17660. }
  17661. };
  17662. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  17663. }
  17664. onBufferAppending(event, eventData) {
  17665. const {
  17666. hls,
  17667. operationQueue,
  17668. tracks
  17669. } = this;
  17670. const {
  17671. data,
  17672. type,
  17673. frag,
  17674. part,
  17675. chunkMeta
  17676. } = eventData;
  17677. const chunkStats = chunkMeta.buffering[type];
  17678. const bufferAppendingStart = self.performance.now();
  17679. chunkStats.start = bufferAppendingStart;
  17680. const fragBuffering = frag.stats.buffering;
  17681. const partBuffering = part ? part.stats.buffering : null;
  17682. if (fragBuffering.start === 0) {
  17683. fragBuffering.start = bufferAppendingStart;
  17684. }
  17685. if (partBuffering && partBuffering.start === 0) {
  17686. partBuffering.start = bufferAppendingStart;
  17687. }
  17688. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  17689. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  17690. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  17691. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  17692. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  17693. const audioTrack = tracks.audio;
  17694. let checkTimestampOffset = false;
  17695. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  17696. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  17697. this.lastMpegAudioChunk = chunkMeta;
  17698. }
  17699. const fragStart = frag.start;
  17700. const operation = {
  17701. execute: () => {
  17702. chunkStats.executeStart = self.performance.now();
  17703. if (checkTimestampOffset) {
  17704. const sb = this.sourceBuffer[type];
  17705. if (sb) {
  17706. const delta = fragStart - sb.timestampOffset;
  17707. if (Math.abs(delta) >= 0.1) {
  17708. this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`);
  17709. sb.timestampOffset = fragStart;
  17710. }
  17711. }
  17712. }
  17713. this.appendExecutor(data, type);
  17714. },
  17715. onStart: () => {
  17716. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  17717. },
  17718. onComplete: () => {
  17719. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  17720. const end = self.performance.now();
  17721. chunkStats.executeEnd = chunkStats.end = end;
  17722. if (fragBuffering.first === 0) {
  17723. fragBuffering.first = end;
  17724. }
  17725. if (partBuffering && partBuffering.first === 0) {
  17726. partBuffering.first = end;
  17727. }
  17728. const {
  17729. sourceBuffer
  17730. } = this;
  17731. const timeRanges = {};
  17732. for (const type in sourceBuffer) {
  17733. timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);
  17734. }
  17735. this.appendErrors[type] = 0;
  17736. if (type === 'audio' || type === 'video') {
  17737. this.appendErrors.audiovideo = 0;
  17738. } else {
  17739. this.appendErrors.audio = 0;
  17740. this.appendErrors.video = 0;
  17741. }
  17742. this.hls.trigger(Events.BUFFER_APPENDED, {
  17743. type,
  17744. frag,
  17745. part,
  17746. chunkMeta,
  17747. parent: frag.type,
  17748. timeRanges
  17749. });
  17750. },
  17751. onError: error => {
  17752. // in case any error occured while appending, put back segment in segments table
  17753. const event = {
  17754. type: ErrorTypes.MEDIA_ERROR,
  17755. parent: frag.type,
  17756. details: ErrorDetails.BUFFER_APPEND_ERROR,
  17757. sourceBufferName: type,
  17758. frag,
  17759. part,
  17760. chunkMeta,
  17761. error,
  17762. err: error,
  17763. fatal: false
  17764. };
  17765. if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
  17766. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  17767. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  17768. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  17769. } else {
  17770. const appendErrorCount = ++this.appendErrors[type];
  17771. event.details = ErrorDetails.BUFFER_APPEND_ERROR;
  17772. /* with UHD content, we could get loop of quota exceeded error until
  17773. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  17774. */
  17775. this.warn(`Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer`);
  17776. if (appendErrorCount >= hls.config.appendErrorMaxRetry) {
  17777. event.fatal = true;
  17778. }
  17779. }
  17780. hls.trigger(Events.ERROR, event);
  17781. }
  17782. };
  17783. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  17784. }
  17785. onBufferFlushing(event, data) {
  17786. const {
  17787. operationQueue
  17788. } = this;
  17789. const flushOperation = type => ({
  17790. execute: this.removeExecutor.bind(this, type, data.startOffset, data.endOffset),
  17791. onStart: () => {
  17792. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  17793. },
  17794. onComplete: () => {
  17795. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  17796. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17797. type
  17798. });
  17799. },
  17800. onError: error => {
  17801. this.warn(`Failed to remove from ${type} SourceBuffer`, error);
  17802. }
  17803. });
  17804. if (data.type) {
  17805. operationQueue.append(flushOperation(data.type), data.type);
  17806. } else {
  17807. this.getSourceBufferTypes().forEach(type => {
  17808. operationQueue.append(flushOperation(type), type);
  17809. });
  17810. }
  17811. }
  17812. onFragParsed(event, data) {
  17813. const {
  17814. frag,
  17815. part
  17816. } = data;
  17817. const buffersAppendedTo = [];
  17818. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  17819. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  17820. buffersAppendedTo.push('audiovideo');
  17821. } else {
  17822. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  17823. buffersAppendedTo.push('audio');
  17824. }
  17825. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  17826. buffersAppendedTo.push('video');
  17827. }
  17828. }
  17829. const onUnblocked = () => {
  17830. const now = self.performance.now();
  17831. frag.stats.buffering.end = now;
  17832. if (part) {
  17833. part.stats.buffering.end = now;
  17834. }
  17835. const stats = part ? part.stats : frag.stats;
  17836. this.hls.trigger(Events.FRAG_BUFFERED, {
  17837. frag,
  17838. part,
  17839. stats,
  17840. id: frag.type
  17841. });
  17842. };
  17843. if (buffersAppendedTo.length === 0) {
  17844. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  17845. }
  17846. this.blockBuffers(onUnblocked, buffersAppendedTo);
  17847. }
  17848. onFragChanged(event, data) {
  17849. this.trimBuffers();
  17850. }
  17851. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  17852. // an undefined data.type will mark all buffers as EOS.
  17853. onBufferEos(event, data) {
  17854. const ended = this.getSourceBufferTypes().reduce((acc, type) => {
  17855. const sb = this.sourceBuffer[type];
  17856. if (sb && (!data.type || data.type === type)) {
  17857. sb.ending = true;
  17858. if (!sb.ended) {
  17859. sb.ended = true;
  17860. this.log(`${type} sourceBuffer now EOS`);
  17861. }
  17862. }
  17863. return acc && !!(!sb || sb.ended);
  17864. }, true);
  17865. if (ended) {
  17866. this.log(`Queueing mediaSource.endOfStream()`);
  17867. this.blockBuffers(() => {
  17868. this.getSourceBufferTypes().forEach(type => {
  17869. const sb = this.sourceBuffer[type];
  17870. if (sb) {
  17871. sb.ending = false;
  17872. }
  17873. });
  17874. const {
  17875. mediaSource
  17876. } = this;
  17877. if (!mediaSource || mediaSource.readyState !== 'open') {
  17878. if (mediaSource) {
  17879. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  17880. }
  17881. return;
  17882. }
  17883. this.log(`Calling mediaSource.endOfStream()`);
  17884. // Allow this to throw and be caught by the enqueueing function
  17885. mediaSource.endOfStream();
  17886. });
  17887. }
  17888. }
  17889. onLevelUpdated(event, {
  17890. details
  17891. }) {
  17892. if (!details.fragments.length) {
  17893. return;
  17894. }
  17895. this.details = details;
  17896. if (this.getSourceBufferTypes().length) {
  17897. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  17898. } else {
  17899. this.updateMediaElementDuration();
  17900. }
  17901. }
  17902. trimBuffers() {
  17903. const {
  17904. hls,
  17905. details,
  17906. media
  17907. } = this;
  17908. if (!media || details === null) {
  17909. return;
  17910. }
  17911. const sourceBufferTypes = this.getSourceBufferTypes();
  17912. if (!sourceBufferTypes.length) {
  17913. return;
  17914. }
  17915. const config = hls.config;
  17916. const currentTime = media.currentTime;
  17917. const targetDuration = details.levelTargetDuration;
  17918. // Support for deprecated liveBackBufferLength
  17919. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  17920. if (isFiniteNumber(backBufferLength) && backBufferLength > 0) {
  17921. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  17922. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  17923. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  17924. }
  17925. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  17926. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  17927. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  17928. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  17929. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  17930. }
  17931. }
  17932. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  17933. const {
  17934. details,
  17935. sourceBuffer
  17936. } = this;
  17937. const sourceBufferTypes = this.getSourceBufferTypes();
  17938. sourceBufferTypes.forEach(type => {
  17939. const sb = sourceBuffer[type];
  17940. if (sb) {
  17941. const buffered = BufferHelper.getBuffered(sb);
  17942. // when target buffer start exceeds actual buffer start
  17943. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  17944. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  17945. bufferEnd: targetBackBufferPosition
  17946. });
  17947. // Support for deprecated event:
  17948. if (details != null && details.live) {
  17949. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  17950. bufferEnd: targetBackBufferPosition
  17951. });
  17952. } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) {
  17953. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  17954. return;
  17955. }
  17956. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17957. startOffset: 0,
  17958. endOffset: targetBackBufferPosition,
  17959. type
  17960. });
  17961. }
  17962. }
  17963. });
  17964. }
  17965. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  17966. const {
  17967. sourceBuffer
  17968. } = this;
  17969. const sourceBufferTypes = this.getSourceBufferTypes();
  17970. sourceBufferTypes.forEach(type => {
  17971. const sb = sourceBuffer[type];
  17972. if (sb) {
  17973. const buffered = BufferHelper.getBuffered(sb);
  17974. const numBufferedRanges = buffered.length;
  17975. // The buffer is either empty or contiguous
  17976. if (numBufferedRanges < 2) {
  17977. return;
  17978. }
  17979. const bufferStart = buffered.start(numBufferedRanges - 1);
  17980. const bufferEnd = buffered.end(numBufferedRanges - 1);
  17981. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  17982. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  17983. return;
  17984. } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {
  17985. this.log(`Cannot flush ${type} front buffer while SourceBuffer is in ended state`);
  17986. return;
  17987. }
  17988. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17989. startOffset: bufferStart,
  17990. endOffset: Infinity,
  17991. type
  17992. });
  17993. }
  17994. });
  17995. }
  17996. /**
  17997. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  17998. * 'liveDurationInfinity` is set to `true`
  17999. * More details: https://github.com/video-dev/hls.js/issues/355
  18000. */
  18001. updateMediaElementDuration() {
  18002. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  18003. return;
  18004. }
  18005. const {
  18006. details,
  18007. hls,
  18008. media,
  18009. mediaSource
  18010. } = this;
  18011. const levelDuration = details.fragments[0].start + details.totalduration;
  18012. const mediaDuration = media.duration;
  18013. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  18014. if (details.live && hls.config.liveDurationInfinity) {
  18015. // Override duration to Infinity
  18016. mediaSource.duration = Infinity;
  18017. this.updateSeekableRange(details);
  18018. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) {
  18019. // levelDuration was the last value we set.
  18020. // not using mediaSource.duration as the browser may tweak this value
  18021. // only update Media Source duration if its value increase, this is to avoid
  18022. // flushing already buffered portion when switching between quality level
  18023. this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`);
  18024. mediaSource.duration = levelDuration;
  18025. }
  18026. }
  18027. updateSeekableRange(levelDetails) {
  18028. const mediaSource = this.mediaSource;
  18029. const fragments = levelDetails.fragments;
  18030. const len = fragments.length;
  18031. if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) {
  18032. const start = Math.max(0, fragments[0].start);
  18033. const end = Math.max(start, start + levelDetails.totalduration);
  18034. this.log(`Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  18035. mediaSource.setLiveSeekableRange(start, end);
  18036. }
  18037. }
  18038. checkPendingTracks() {
  18039. const {
  18040. bufferCodecEventsExpected,
  18041. operationQueue,
  18042. pendingTracks
  18043. } = this;
  18044. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  18045. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  18046. // data has been appended to existing ones.
  18047. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  18048. const pendingTracksCount = Object.keys(pendingTracks).length;
  18049. if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || 'audiovideo' in pendingTracks)) {
  18050. // ok, let's create them now !
  18051. this.createSourceBuffers(pendingTracks);
  18052. this.pendingTracks = {};
  18053. // append any pending segments now !
  18054. const buffers = this.getSourceBufferTypes();
  18055. if (buffers.length) {
  18056. this.hls.trigger(Events.BUFFER_CREATED, {
  18057. tracks: this.tracks
  18058. });
  18059. buffers.forEach(type => {
  18060. operationQueue.executeNext(type);
  18061. });
  18062. } else {
  18063. const error = new Error('could not create source buffer for media codec(s)');
  18064. this.hls.trigger(Events.ERROR, {
  18065. type: ErrorTypes.MEDIA_ERROR,
  18066. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  18067. fatal: true,
  18068. error,
  18069. reason: error.message
  18070. });
  18071. }
  18072. }
  18073. }
  18074. createSourceBuffers(tracks) {
  18075. const {
  18076. sourceBuffer,
  18077. mediaSource
  18078. } = this;
  18079. if (!mediaSource) {
  18080. throw Error('createSourceBuffers called when mediaSource was null');
  18081. }
  18082. for (const trackName in tracks) {
  18083. if (!sourceBuffer[trackName]) {
  18084. var _track$levelCodec;
  18085. const track = tracks[trackName];
  18086. if (!track) {
  18087. throw Error(`source buffer exists for track ${trackName}, however track does not`);
  18088. }
  18089. // use levelCodec as first priority unless it contains multiple comma-separated codec values
  18090. let codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(',')) === -1 ? track.levelCodec : track.codec;
  18091. if (codec) {
  18092. if (trackName.slice(0, 5) === 'audio') {
  18093. codec = getCodecCompatibleName(codec, this.appendSource);
  18094. }
  18095. }
  18096. const mimeType = `${track.container};codecs=${codec}`;
  18097. this.log(`creating sourceBuffer(${mimeType})`);
  18098. try {
  18099. const sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  18100. const sbName = trackName;
  18101. this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
  18102. this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
  18103. this.addBufferListener(sbName, 'error', this._onSBUpdateError);
  18104. // ManagedSourceBuffer bufferedchange event
  18105. if (this.appendSource) {
  18106. this.addBufferListener(sbName, 'bufferedchange', (type, event) => {
  18107. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  18108. const removedRanges = event.removedRanges;
  18109. if (removedRanges != null && removedRanges.length) {
  18110. this.hls.trigger(Events.BUFFER_FLUSHED, {
  18111. type: trackName
  18112. });
  18113. }
  18114. });
  18115. }
  18116. this.tracks[trackName] = {
  18117. buffer: sb,
  18118. codec: codec,
  18119. container: track.container,
  18120. levelCodec: track.levelCodec,
  18121. metadata: track.metadata,
  18122. id: track.id
  18123. };
  18124. } catch (err) {
  18125. this.error(`error while trying to add sourceBuffer: ${err.message}`);
  18126. this.hls.trigger(Events.ERROR, {
  18127. type: ErrorTypes.MEDIA_ERROR,
  18128. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  18129. fatal: false,
  18130. error: err,
  18131. sourceBufferName: trackName,
  18132. mimeType: mimeType
  18133. });
  18134. }
  18135. }
  18136. }
  18137. }
  18138. get mediaSrc() {
  18139. var _this$media, _this$media$querySele;
  18140. const media = ((_this$media = this.media) == null ? void 0 : (_this$media$querySele = _this$media.querySelector) == null ? void 0 : _this$media$querySele.call(_this$media, 'source')) || this.media;
  18141. return media == null ? void 0 : media.src;
  18142. }
  18143. _onSBUpdateStart(type) {
  18144. const {
  18145. operationQueue
  18146. } = this;
  18147. const operation = operationQueue.current(type);
  18148. operation.onStart();
  18149. }
  18150. _onSBUpdateEnd(type) {
  18151. var _this$mediaSource2;
  18152. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  18153. this.resetBuffer(type);
  18154. return;
  18155. }
  18156. const {
  18157. operationQueue
  18158. } = this;
  18159. const operation = operationQueue.current(type);
  18160. operation.onComplete();
  18161. operationQueue.shiftAndExecuteNext(type);
  18162. }
  18163. _onSBUpdateError(type, event) {
  18164. var _this$mediaSource3;
  18165. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState}`);
  18166. this.error(`${error}`, event);
  18167. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  18168. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  18169. this.hls.trigger(Events.ERROR, {
  18170. type: ErrorTypes.MEDIA_ERROR,
  18171. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  18172. sourceBufferName: type,
  18173. error,
  18174. fatal: false
  18175. });
  18176. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  18177. const operation = this.operationQueue.current(type);
  18178. if (operation) {
  18179. operation.onError(error);
  18180. }
  18181. }
  18182. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  18183. removeExecutor(type, startOffset, endOffset) {
  18184. const {
  18185. media,
  18186. mediaSource,
  18187. operationQueue,
  18188. sourceBuffer
  18189. } = this;
  18190. const sb = sourceBuffer[type];
  18191. if (!media || !mediaSource || !sb) {
  18192. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  18193. operationQueue.shiftAndExecuteNext(type);
  18194. return;
  18195. }
  18196. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  18197. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  18198. const removeStart = Math.max(0, startOffset);
  18199. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  18200. if (removeEnd > removeStart && (!sb.ending || sb.ended)) {
  18201. sb.ended = false;
  18202. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  18203. sb.remove(removeStart, removeEnd);
  18204. } else {
  18205. // Cycle the queue
  18206. operationQueue.shiftAndExecuteNext(type);
  18207. }
  18208. }
  18209. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  18210. appendExecutor(data, type) {
  18211. const sb = this.sourceBuffer[type];
  18212. if (!sb) {
  18213. if (!this.pendingTracks[type]) {
  18214. throw new Error(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  18215. }
  18216. return;
  18217. }
  18218. sb.ended = false;
  18219. sb.appendBuffer(data);
  18220. }
  18221. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  18222. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  18223. // upon completion, since we already do it here
  18224. blockBuffers(onUnblocked, buffers = this.getSourceBufferTypes()) {
  18225. if (!buffers.length) {
  18226. this.log('Blocking operation requested, but no SourceBuffers exist');
  18227. Promise.resolve().then(onUnblocked);
  18228. return;
  18229. }
  18230. const {
  18231. operationQueue
  18232. } = this;
  18233. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  18234. const blockingOperations = buffers.map(type => operationQueue.appendBlocker(type));
  18235. Promise.all(blockingOperations).then(() => {
  18236. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  18237. onUnblocked();
  18238. buffers.forEach(type => {
  18239. const sb = this.sourceBuffer[type];
  18240. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  18241. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  18242. // While this is a workaround, it's probably useful to have around
  18243. if (!(sb != null && sb.updating)) {
  18244. operationQueue.shiftAndExecuteNext(type);
  18245. }
  18246. });
  18247. });
  18248. }
  18249. getSourceBufferTypes() {
  18250. return Object.keys(this.sourceBuffer);
  18251. }
  18252. addBufferListener(type, event, fn) {
  18253. const buffer = this.sourceBuffer[type];
  18254. if (!buffer) {
  18255. return;
  18256. }
  18257. const listener = fn.bind(this, type);
  18258. this.listeners[type].push({
  18259. event,
  18260. listener
  18261. });
  18262. buffer.addEventListener(event, listener);
  18263. }
  18264. removeBufferListeners(type) {
  18265. const buffer = this.sourceBuffer[type];
  18266. if (!buffer) {
  18267. return;
  18268. }
  18269. this.listeners[type].forEach(l => {
  18270. buffer.removeEventListener(l.event, l.listener);
  18271. });
  18272. }
  18273. }
  18274. function removeSourceChildren(node) {
  18275. const sourceChildren = node.querySelectorAll('source');
  18276. [].slice.call(sourceChildren).forEach(source => {
  18277. node.removeChild(source);
  18278. });
  18279. }
  18280. function addSource(media, url) {
  18281. const source = self.document.createElement('source');
  18282. source.type = 'video/mp4';
  18283. source.src = url;
  18284. media.appendChild(source);
  18285. }
  18286. /**
  18287. *
  18288. * This code was ported from the dash.js project at:
  18289. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  18290. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  18291. *
  18292. * The original copyright appears below:
  18293. *
  18294. * The copyright in this software is being made available under the BSD License,
  18295. * included below. This software may be subject to other third party and contributor
  18296. * rights, including patent rights, and no such rights are granted under this license.
  18297. *
  18298. * Copyright (c) 2015-2016, DASH Industry Forum.
  18299. * All rights reserved.
  18300. *
  18301. * Redistribution and use in source and binary forms, with or without modification,
  18302. * are permitted provided that the following conditions are met:
  18303. * 1. Redistributions of source code must retain the above copyright notice, this
  18304. * list of conditions and the following disclaimer.
  18305. * * Redistributions in binary form must reproduce the above copyright notice,
  18306. * this list of conditions and the following disclaimer in the documentation and/or
  18307. * other materials provided with the distribution.
  18308. * 2. Neither the name of Dash Industry Forum nor the names of its
  18309. * contributors may be used to endorse or promote products derived from this software
  18310. * without specific prior written permission.
  18311. *
  18312. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  18313. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18314. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18315. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  18316. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  18317. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18318. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  18319. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  18320. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  18321. * POSSIBILITY OF SUCH DAMAGE.
  18322. */
  18323. /**
  18324. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  18325. */
  18326. const specialCea608CharsCodes = {
  18327. 0x2a: 0xe1,
  18328. // lowercase a, acute accent
  18329. 0x5c: 0xe9,
  18330. // lowercase e, acute accent
  18331. 0x5e: 0xed,
  18332. // lowercase i, acute accent
  18333. 0x5f: 0xf3,
  18334. // lowercase o, acute accent
  18335. 0x60: 0xfa,
  18336. // lowercase u, acute accent
  18337. 0x7b: 0xe7,
  18338. // lowercase c with cedilla
  18339. 0x7c: 0xf7,
  18340. // division symbol
  18341. 0x7d: 0xd1,
  18342. // uppercase N tilde
  18343. 0x7e: 0xf1,
  18344. // lowercase n tilde
  18345. 0x7f: 0x2588,
  18346. // Full block
  18347. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18348. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  18349. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  18350. 0x80: 0xae,
  18351. // Registered symbol (R)
  18352. 0x81: 0xb0,
  18353. // degree sign
  18354. 0x82: 0xbd,
  18355. // 1/2 symbol
  18356. 0x83: 0xbf,
  18357. // Inverted (open) question mark
  18358. 0x84: 0x2122,
  18359. // Trademark symbol (TM)
  18360. 0x85: 0xa2,
  18361. // Cents symbol
  18362. 0x86: 0xa3,
  18363. // Pounds sterling
  18364. 0x87: 0x266a,
  18365. // Music 8'th note
  18366. 0x88: 0xe0,
  18367. // lowercase a, grave accent
  18368. 0x89: 0x20,
  18369. // transparent space (regular)
  18370. 0x8a: 0xe8,
  18371. // lowercase e, grave accent
  18372. 0x8b: 0xe2,
  18373. // lowercase a, circumflex accent
  18374. 0x8c: 0xea,
  18375. // lowercase e, circumflex accent
  18376. 0x8d: 0xee,
  18377. // lowercase i, circumflex accent
  18378. 0x8e: 0xf4,
  18379. // lowercase o, circumflex accent
  18380. 0x8f: 0xfb,
  18381. // lowercase u, circumflex accent
  18382. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18383. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  18384. 0x90: 0xc1,
  18385. // capital letter A with acute
  18386. 0x91: 0xc9,
  18387. // capital letter E with acute
  18388. 0x92: 0xd3,
  18389. // capital letter O with acute
  18390. 0x93: 0xda,
  18391. // capital letter U with acute
  18392. 0x94: 0xdc,
  18393. // capital letter U with diaresis
  18394. 0x95: 0xfc,
  18395. // lowercase letter U with diaeresis
  18396. 0x96: 0x2018,
  18397. // opening single quote
  18398. 0x97: 0xa1,
  18399. // inverted exclamation mark
  18400. 0x98: 0x2a,
  18401. // asterisk
  18402. 0x99: 0x2019,
  18403. // closing single quote
  18404. 0x9a: 0x2501,
  18405. // box drawings heavy horizontal
  18406. 0x9b: 0xa9,
  18407. // copyright sign
  18408. 0x9c: 0x2120,
  18409. // Service mark
  18410. 0x9d: 0x2022,
  18411. // (round) bullet
  18412. 0x9e: 0x201c,
  18413. // Left double quotation mark
  18414. 0x9f: 0x201d,
  18415. // Right double quotation mark
  18416. 0xa0: 0xc0,
  18417. // uppercase A, grave accent
  18418. 0xa1: 0xc2,
  18419. // uppercase A, circumflex
  18420. 0xa2: 0xc7,
  18421. // uppercase C with cedilla
  18422. 0xa3: 0xc8,
  18423. // uppercase E, grave accent
  18424. 0xa4: 0xca,
  18425. // uppercase E, circumflex
  18426. 0xa5: 0xcb,
  18427. // capital letter E with diaresis
  18428. 0xa6: 0xeb,
  18429. // lowercase letter e with diaresis
  18430. 0xa7: 0xce,
  18431. // uppercase I, circumflex
  18432. 0xa8: 0xcf,
  18433. // uppercase I, with diaresis
  18434. 0xa9: 0xef,
  18435. // lowercase i, with diaresis
  18436. 0xaa: 0xd4,
  18437. // uppercase O, circumflex
  18438. 0xab: 0xd9,
  18439. // uppercase U, grave accent
  18440. 0xac: 0xf9,
  18441. // lowercase u, grave accent
  18442. 0xad: 0xdb,
  18443. // uppercase U, circumflex
  18444. 0xae: 0xab,
  18445. // left-pointing double angle quotation mark
  18446. 0xaf: 0xbb,
  18447. // right-pointing double angle quotation mark
  18448. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18449. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  18450. 0xb0: 0xc3,
  18451. // Uppercase A, tilde
  18452. 0xb1: 0xe3,
  18453. // Lowercase a, tilde
  18454. 0xb2: 0xcd,
  18455. // Uppercase I, acute accent
  18456. 0xb3: 0xcc,
  18457. // Uppercase I, grave accent
  18458. 0xb4: 0xec,
  18459. // Lowercase i, grave accent
  18460. 0xb5: 0xd2,
  18461. // Uppercase O, grave accent
  18462. 0xb6: 0xf2,
  18463. // Lowercase o, grave accent
  18464. 0xb7: 0xd5,
  18465. // Uppercase O, tilde
  18466. 0xb8: 0xf5,
  18467. // Lowercase o, tilde
  18468. 0xb9: 0x7b,
  18469. // Open curly brace
  18470. 0xba: 0x7d,
  18471. // Closing curly brace
  18472. 0xbb: 0x5c,
  18473. // Backslash
  18474. 0xbc: 0x5e,
  18475. // Caret
  18476. 0xbd: 0x5f,
  18477. // Underscore
  18478. 0xbe: 0x7c,
  18479. // Pipe (vertical line)
  18480. 0xbf: 0x223c,
  18481. // Tilde operator
  18482. 0xc0: 0xc4,
  18483. // Uppercase A, umlaut
  18484. 0xc1: 0xe4,
  18485. // Lowercase A, umlaut
  18486. 0xc2: 0xd6,
  18487. // Uppercase O, umlaut
  18488. 0xc3: 0xf6,
  18489. // Lowercase o, umlaut
  18490. 0xc4: 0xdf,
  18491. // Esszett (sharp S)
  18492. 0xc5: 0xa5,
  18493. // Yen symbol
  18494. 0xc6: 0xa4,
  18495. // Generic currency sign
  18496. 0xc7: 0x2503,
  18497. // Box drawings heavy vertical
  18498. 0xc8: 0xc5,
  18499. // Uppercase A, ring
  18500. 0xc9: 0xe5,
  18501. // Lowercase A, ring
  18502. 0xca: 0xd8,
  18503. // Uppercase O, stroke
  18504. 0xcb: 0xf8,
  18505. // Lowercase o, strok
  18506. 0xcc: 0x250f,
  18507. // Box drawings heavy down and right
  18508. 0xcd: 0x2513,
  18509. // Box drawings heavy down and left
  18510. 0xce: 0x2517,
  18511. // Box drawings heavy up and right
  18512. 0xcf: 0x251b // Box drawings heavy up and left
  18513. };
  18514. /**
  18515. * Utils
  18516. */
  18517. const getCharForByte = byte => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  18518. const NR_ROWS = 15;
  18519. const NR_COLS = 100;
  18520. // Tables to look up row from PAC data
  18521. const rowsLowCh1 = {
  18522. 0x11: 1,
  18523. 0x12: 3,
  18524. 0x15: 5,
  18525. 0x16: 7,
  18526. 0x17: 9,
  18527. 0x10: 11,
  18528. 0x13: 12,
  18529. 0x14: 14
  18530. };
  18531. const rowsHighCh1 = {
  18532. 0x11: 2,
  18533. 0x12: 4,
  18534. 0x15: 6,
  18535. 0x16: 8,
  18536. 0x17: 10,
  18537. 0x13: 13,
  18538. 0x14: 15
  18539. };
  18540. const rowsLowCh2 = {
  18541. 0x19: 1,
  18542. 0x1a: 3,
  18543. 0x1d: 5,
  18544. 0x1e: 7,
  18545. 0x1f: 9,
  18546. 0x18: 11,
  18547. 0x1b: 12,
  18548. 0x1c: 14
  18549. };
  18550. const rowsHighCh2 = {
  18551. 0x19: 2,
  18552. 0x1a: 4,
  18553. 0x1d: 6,
  18554. 0x1e: 8,
  18555. 0x1f: 10,
  18556. 0x1b: 13,
  18557. 0x1c: 15
  18558. };
  18559. const backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  18560. class CaptionsLogger {
  18561. constructor() {
  18562. this.time = null;
  18563. this.verboseLevel = 0;
  18564. }
  18565. log(severity, msg) {
  18566. if (this.verboseLevel >= severity) {
  18567. const m = typeof msg === 'function' ? msg() : msg;
  18568. logger.log(`${this.time} [${severity}] ${m}`);
  18569. }
  18570. }
  18571. }
  18572. const numArrayToHexArray = function numArrayToHexArray(numArray) {
  18573. const hexArray = [];
  18574. for (let j = 0; j < numArray.length; j++) {
  18575. hexArray.push(numArray[j].toString(16));
  18576. }
  18577. return hexArray;
  18578. };
  18579. class PenState {
  18580. constructor() {
  18581. this.foreground = 'white';
  18582. this.underline = false;
  18583. this.italics = false;
  18584. this.background = 'black';
  18585. this.flash = false;
  18586. }
  18587. reset() {
  18588. this.foreground = 'white';
  18589. this.underline = false;
  18590. this.italics = false;
  18591. this.background = 'black';
  18592. this.flash = false;
  18593. }
  18594. setStyles(styles) {
  18595. const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  18596. for (let i = 0; i < attribs.length; i++) {
  18597. const style = attribs[i];
  18598. if (styles.hasOwnProperty(style)) {
  18599. this[style] = styles[style];
  18600. }
  18601. }
  18602. }
  18603. isDefault() {
  18604. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  18605. }
  18606. equals(other) {
  18607. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  18608. }
  18609. copy(newPenState) {
  18610. this.foreground = newPenState.foreground;
  18611. this.underline = newPenState.underline;
  18612. this.italics = newPenState.italics;
  18613. this.background = newPenState.background;
  18614. this.flash = newPenState.flash;
  18615. }
  18616. toString() {
  18617. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  18618. }
  18619. }
  18620. /**
  18621. * Unicode character with styling and background.
  18622. * @constructor
  18623. */
  18624. class StyledUnicodeChar {
  18625. constructor() {
  18626. this.uchar = ' ';
  18627. this.penState = new PenState();
  18628. }
  18629. reset() {
  18630. this.uchar = ' ';
  18631. this.penState.reset();
  18632. }
  18633. setChar(uchar, newPenState) {
  18634. this.uchar = uchar;
  18635. this.penState.copy(newPenState);
  18636. }
  18637. setPenState(newPenState) {
  18638. this.penState.copy(newPenState);
  18639. }
  18640. equals(other) {
  18641. return this.uchar === other.uchar && this.penState.equals(other.penState);
  18642. }
  18643. copy(newChar) {
  18644. this.uchar = newChar.uchar;
  18645. this.penState.copy(newChar.penState);
  18646. }
  18647. isEmpty() {
  18648. return this.uchar === ' ' && this.penState.isDefault();
  18649. }
  18650. }
  18651. /**
  18652. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  18653. * @constructor
  18654. */
  18655. class Row {
  18656. constructor(logger) {
  18657. this.chars = [];
  18658. this.pos = 0;
  18659. this.currPenState = new PenState();
  18660. this.cueStartTime = null;
  18661. this.logger = void 0;
  18662. for (let i = 0; i < NR_COLS; i++) {
  18663. this.chars.push(new StyledUnicodeChar());
  18664. }
  18665. this.logger = logger;
  18666. }
  18667. equals(other) {
  18668. for (let i = 0; i < NR_COLS; i++) {
  18669. if (!this.chars[i].equals(other.chars[i])) {
  18670. return false;
  18671. }
  18672. }
  18673. return true;
  18674. }
  18675. copy(other) {
  18676. for (let i = 0; i < NR_COLS; i++) {
  18677. this.chars[i].copy(other.chars[i]);
  18678. }
  18679. }
  18680. isEmpty() {
  18681. let empty = true;
  18682. for (let i = 0; i < NR_COLS; i++) {
  18683. if (!this.chars[i].isEmpty()) {
  18684. empty = false;
  18685. break;
  18686. }
  18687. }
  18688. return empty;
  18689. }
  18690. /**
  18691. * Set the cursor to a valid column.
  18692. */
  18693. setCursor(absPos) {
  18694. if (this.pos !== absPos) {
  18695. this.pos = absPos;
  18696. }
  18697. if (this.pos < 0) {
  18698. this.logger.log(3, 'Negative cursor position ' + this.pos);
  18699. this.pos = 0;
  18700. } else if (this.pos > NR_COLS) {
  18701. this.logger.log(3, 'Too large cursor position ' + this.pos);
  18702. this.pos = NR_COLS;
  18703. }
  18704. }
  18705. /**
  18706. * Move the cursor relative to current position.
  18707. */
  18708. moveCursor(relPos) {
  18709. const newPos = this.pos + relPos;
  18710. if (relPos > 1) {
  18711. for (let i = this.pos + 1; i < newPos + 1; i++) {
  18712. this.chars[i].setPenState(this.currPenState);
  18713. }
  18714. }
  18715. this.setCursor(newPos);
  18716. }
  18717. /**
  18718. * Backspace, move one step back and clear character.
  18719. */
  18720. backSpace() {
  18721. this.moveCursor(-1);
  18722. this.chars[this.pos].setChar(' ', this.currPenState);
  18723. }
  18724. insertChar(byte) {
  18725. if (byte >= 0x90) {
  18726. // Extended char
  18727. this.backSpace();
  18728. }
  18729. const char = getCharForByte(byte);
  18730. if (this.pos >= NR_COLS) {
  18731. this.logger.log(0, () => 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  18732. return;
  18733. }
  18734. this.chars[this.pos].setChar(char, this.currPenState);
  18735. this.moveCursor(1);
  18736. }
  18737. clearFromPos(startPos) {
  18738. let i;
  18739. for (i = startPos; i < NR_COLS; i++) {
  18740. this.chars[i].reset();
  18741. }
  18742. }
  18743. clear() {
  18744. this.clearFromPos(0);
  18745. this.pos = 0;
  18746. this.currPenState.reset();
  18747. }
  18748. clearToEndOfRow() {
  18749. this.clearFromPos(this.pos);
  18750. }
  18751. getTextString() {
  18752. const chars = [];
  18753. let empty = true;
  18754. for (let i = 0; i < NR_COLS; i++) {
  18755. const char = this.chars[i].uchar;
  18756. if (char !== ' ') {
  18757. empty = false;
  18758. }
  18759. chars.push(char);
  18760. }
  18761. if (empty) {
  18762. return '';
  18763. } else {
  18764. return chars.join('');
  18765. }
  18766. }
  18767. setPenStyles(styles) {
  18768. this.currPenState.setStyles(styles);
  18769. const currChar = this.chars[this.pos];
  18770. currChar.setPenState(this.currPenState);
  18771. }
  18772. }
  18773. /**
  18774. * Keep a CEA-608 screen of 32x15 styled characters
  18775. * @constructor
  18776. */
  18777. class CaptionScreen {
  18778. constructor(logger) {
  18779. this.rows = [];
  18780. this.currRow = NR_ROWS - 1;
  18781. this.nrRollUpRows = null;
  18782. this.lastOutputScreen = null;
  18783. this.logger = void 0;
  18784. for (let i = 0; i < NR_ROWS; i++) {
  18785. this.rows.push(new Row(logger));
  18786. }
  18787. this.logger = logger;
  18788. }
  18789. reset() {
  18790. for (let i = 0; i < NR_ROWS; i++) {
  18791. this.rows[i].clear();
  18792. }
  18793. this.currRow = NR_ROWS - 1;
  18794. }
  18795. equals(other) {
  18796. let equal = true;
  18797. for (let i = 0; i < NR_ROWS; i++) {
  18798. if (!this.rows[i].equals(other.rows[i])) {
  18799. equal = false;
  18800. break;
  18801. }
  18802. }
  18803. return equal;
  18804. }
  18805. copy(other) {
  18806. for (let i = 0; i < NR_ROWS; i++) {
  18807. this.rows[i].copy(other.rows[i]);
  18808. }
  18809. }
  18810. isEmpty() {
  18811. let empty = true;
  18812. for (let i = 0; i < NR_ROWS; i++) {
  18813. if (!this.rows[i].isEmpty()) {
  18814. empty = false;
  18815. break;
  18816. }
  18817. }
  18818. return empty;
  18819. }
  18820. backSpace() {
  18821. const row = this.rows[this.currRow];
  18822. row.backSpace();
  18823. }
  18824. clearToEndOfRow() {
  18825. const row = this.rows[this.currRow];
  18826. row.clearToEndOfRow();
  18827. }
  18828. /**
  18829. * Insert a character (without styling) in the current row.
  18830. */
  18831. insertChar(char) {
  18832. const row = this.rows[this.currRow];
  18833. row.insertChar(char);
  18834. }
  18835. setPen(styles) {
  18836. const row = this.rows[this.currRow];
  18837. row.setPenStyles(styles);
  18838. }
  18839. moveCursor(relPos) {
  18840. const row = this.rows[this.currRow];
  18841. row.moveCursor(relPos);
  18842. }
  18843. setCursor(absPos) {
  18844. this.logger.log(2, 'setCursor: ' + absPos);
  18845. const row = this.rows[this.currRow];
  18846. row.setCursor(absPos);
  18847. }
  18848. setPAC(pacData) {
  18849. this.logger.log(2, () => 'pacData = ' + JSON.stringify(pacData));
  18850. let newRow = pacData.row - 1;
  18851. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  18852. newRow = this.nrRollUpRows - 1;
  18853. }
  18854. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  18855. if (this.nrRollUpRows && this.currRow !== newRow) {
  18856. // clear all rows first
  18857. for (let i = 0; i < NR_ROWS; i++) {
  18858. this.rows[i].clear();
  18859. }
  18860. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  18861. // topRowIndex - the start of rows to copy (inclusive index)
  18862. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  18863. // We only copy if the last position was already shown.
  18864. // We use the cueStartTime value to check this.
  18865. const lastOutputScreen = this.lastOutputScreen;
  18866. if (lastOutputScreen) {
  18867. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  18868. const time = this.logger.time;
  18869. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  18870. for (let i = 0; i < this.nrRollUpRows; i++) {
  18871. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  18872. }
  18873. }
  18874. }
  18875. }
  18876. this.currRow = newRow;
  18877. const row = this.rows[this.currRow];
  18878. if (pacData.indent !== null) {
  18879. const indent = pacData.indent;
  18880. const prevPos = Math.max(indent - 1, 0);
  18881. row.setCursor(pacData.indent);
  18882. pacData.color = row.chars[prevPos].penState.foreground;
  18883. }
  18884. const styles = {
  18885. foreground: pacData.color,
  18886. underline: pacData.underline,
  18887. italics: pacData.italics,
  18888. background: 'black',
  18889. flash: false
  18890. };
  18891. this.setPen(styles);
  18892. }
  18893. /**
  18894. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  18895. */
  18896. setBkgData(bkgData) {
  18897. this.logger.log(2, () => 'bkgData = ' + JSON.stringify(bkgData));
  18898. this.backSpace();
  18899. this.setPen(bkgData);
  18900. this.insertChar(0x20); // Space
  18901. }
  18902. setRollUpRows(nrRows) {
  18903. this.nrRollUpRows = nrRows;
  18904. }
  18905. rollUp() {
  18906. if (this.nrRollUpRows === null) {
  18907. this.logger.log(3, 'roll_up but nrRollUpRows not set yet');
  18908. return; // Not properly setup
  18909. }
  18910. this.logger.log(1, () => this.getDisplayText());
  18911. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  18912. const topRow = this.rows.splice(topRowIndex, 1)[0];
  18913. topRow.clear();
  18914. this.rows.splice(this.currRow, 0, topRow);
  18915. this.logger.log(2, 'Rolling up');
  18916. // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
  18917. }
  18918. /**
  18919. * Get all non-empty rows with as unicode text.
  18920. */
  18921. getDisplayText(asOneRow) {
  18922. asOneRow = asOneRow || false;
  18923. const displayText = [];
  18924. let text = '';
  18925. let rowNr = -1;
  18926. for (let i = 0; i < NR_ROWS; i++) {
  18927. const rowText = this.rows[i].getTextString();
  18928. if (rowText) {
  18929. rowNr = i + 1;
  18930. if (asOneRow) {
  18931. displayText.push('Row ' + rowNr + ": '" + rowText + "'");
  18932. } else {
  18933. displayText.push(rowText.trim());
  18934. }
  18935. }
  18936. }
  18937. if (displayText.length > 0) {
  18938. if (asOneRow) {
  18939. text = '[' + displayText.join(' | ') + ']';
  18940. } else {
  18941. text = displayText.join('\n');
  18942. }
  18943. }
  18944. return text;
  18945. }
  18946. getTextAndFormat() {
  18947. return this.rows;
  18948. }
  18949. }
  18950. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  18951. class Cea608Channel {
  18952. constructor(channelNumber, outputFilter, logger) {
  18953. this.chNr = void 0;
  18954. this.outputFilter = void 0;
  18955. this.mode = void 0;
  18956. this.verbose = void 0;
  18957. this.displayedMemory = void 0;
  18958. this.nonDisplayedMemory = void 0;
  18959. this.lastOutputScreen = void 0;
  18960. this.currRollUpRow = void 0;
  18961. this.writeScreen = void 0;
  18962. this.cueStartTime = void 0;
  18963. this.logger = void 0;
  18964. this.chNr = channelNumber;
  18965. this.outputFilter = outputFilter;
  18966. this.mode = null;
  18967. this.verbose = 0;
  18968. this.displayedMemory = new CaptionScreen(logger);
  18969. this.nonDisplayedMemory = new CaptionScreen(logger);
  18970. this.lastOutputScreen = new CaptionScreen(logger);
  18971. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  18972. this.writeScreen = this.displayedMemory;
  18973. this.mode = null;
  18974. this.cueStartTime = null; // Keeps track of where a cue started.
  18975. this.logger = logger;
  18976. }
  18977. reset() {
  18978. this.mode = null;
  18979. this.displayedMemory.reset();
  18980. this.nonDisplayedMemory.reset();
  18981. this.lastOutputScreen.reset();
  18982. this.outputFilter.reset();
  18983. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  18984. this.writeScreen = this.displayedMemory;
  18985. this.mode = null;
  18986. this.cueStartTime = null;
  18987. }
  18988. getHandler() {
  18989. return this.outputFilter;
  18990. }
  18991. setHandler(newHandler) {
  18992. this.outputFilter = newHandler;
  18993. }
  18994. setPAC(pacData) {
  18995. this.writeScreen.setPAC(pacData);
  18996. }
  18997. setBkgData(bkgData) {
  18998. this.writeScreen.setBkgData(bkgData);
  18999. }
  19000. setMode(newMode) {
  19001. if (newMode === this.mode) {
  19002. return;
  19003. }
  19004. this.mode = newMode;
  19005. this.logger.log(2, () => 'MODE=' + newMode);
  19006. if (this.mode === 'MODE_POP-ON') {
  19007. this.writeScreen = this.nonDisplayedMemory;
  19008. } else {
  19009. this.writeScreen = this.displayedMemory;
  19010. this.writeScreen.reset();
  19011. }
  19012. if (this.mode !== 'MODE_ROLL-UP') {
  19013. this.displayedMemory.nrRollUpRows = null;
  19014. this.nonDisplayedMemory.nrRollUpRows = null;
  19015. }
  19016. this.mode = newMode;
  19017. }
  19018. insertChars(chars) {
  19019. for (let i = 0; i < chars.length; i++) {
  19020. this.writeScreen.insertChar(chars[i]);
  19021. }
  19022. const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  19023. this.logger.log(2, () => screen + ': ' + this.writeScreen.getDisplayText(true));
  19024. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  19025. this.logger.log(1, () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  19026. this.outputDataUpdate();
  19027. }
  19028. }
  19029. ccRCL() {
  19030. // Resume Caption Loading (switch mode to Pop On)
  19031. this.logger.log(2, 'RCL - Resume Caption Loading');
  19032. this.setMode('MODE_POP-ON');
  19033. }
  19034. ccBS() {
  19035. // BackSpace
  19036. this.logger.log(2, 'BS - BackSpace');
  19037. if (this.mode === 'MODE_TEXT') {
  19038. return;
  19039. }
  19040. this.writeScreen.backSpace();
  19041. if (this.writeScreen === this.displayedMemory) {
  19042. this.outputDataUpdate();
  19043. }
  19044. }
  19045. ccAOF() {
  19046. // Reserved (formerly Alarm Off)
  19047. }
  19048. ccAON() {
  19049. // Reserved (formerly Alarm On)
  19050. }
  19051. ccDER() {
  19052. // Delete to End of Row
  19053. this.logger.log(2, 'DER- Delete to End of Row');
  19054. this.writeScreen.clearToEndOfRow();
  19055. this.outputDataUpdate();
  19056. }
  19057. ccRU(nrRows) {
  19058. // Roll-Up Captions-2,3,or 4 Rows
  19059. this.logger.log(2, 'RU(' + nrRows + ') - Roll Up');
  19060. this.writeScreen = this.displayedMemory;
  19061. this.setMode('MODE_ROLL-UP');
  19062. this.writeScreen.setRollUpRows(nrRows);
  19063. }
  19064. ccFON() {
  19065. // Flash On
  19066. this.logger.log(2, 'FON - Flash On');
  19067. this.writeScreen.setPen({
  19068. flash: true
  19069. });
  19070. }
  19071. ccRDC() {
  19072. // Resume Direct Captioning (switch mode to PaintOn)
  19073. this.logger.log(2, 'RDC - Resume Direct Captioning');
  19074. this.setMode('MODE_PAINT-ON');
  19075. }
  19076. ccTR() {
  19077. // Text Restart in text mode (not supported, however)
  19078. this.logger.log(2, 'TR');
  19079. this.setMode('MODE_TEXT');
  19080. }
  19081. ccRTD() {
  19082. // Resume Text Display in Text mode (not supported, however)
  19083. this.logger.log(2, 'RTD');
  19084. this.setMode('MODE_TEXT');
  19085. }
  19086. ccEDM() {
  19087. // Erase Displayed Memory
  19088. this.logger.log(2, 'EDM - Erase Displayed Memory');
  19089. this.displayedMemory.reset();
  19090. this.outputDataUpdate(true);
  19091. }
  19092. ccCR() {
  19093. // Carriage Return
  19094. this.logger.log(2, 'CR - Carriage Return');
  19095. this.writeScreen.rollUp();
  19096. this.outputDataUpdate(true);
  19097. }
  19098. ccENM() {
  19099. // Erase Non-Displayed Memory
  19100. this.logger.log(2, 'ENM - Erase Non-displayed Memory');
  19101. this.nonDisplayedMemory.reset();
  19102. }
  19103. ccEOC() {
  19104. // End of Caption (Flip Memories)
  19105. this.logger.log(2, 'EOC - End Of Caption');
  19106. if (this.mode === 'MODE_POP-ON') {
  19107. const tmp = this.displayedMemory;
  19108. this.displayedMemory = this.nonDisplayedMemory;
  19109. this.nonDisplayedMemory = tmp;
  19110. this.writeScreen = this.nonDisplayedMemory;
  19111. this.logger.log(1, () => 'DISP: ' + this.displayedMemory.getDisplayText());
  19112. }
  19113. this.outputDataUpdate(true);
  19114. }
  19115. ccTO(nrCols) {
  19116. // Tab Offset 1,2, or 3 columns
  19117. this.logger.log(2, 'TO(' + nrCols + ') - Tab Offset');
  19118. this.writeScreen.moveCursor(nrCols);
  19119. }
  19120. ccMIDROW(secondByte) {
  19121. // Parse MIDROW command
  19122. const styles = {
  19123. flash: false
  19124. };
  19125. styles.underline = secondByte % 2 === 1;
  19126. styles.italics = secondByte >= 0x2e;
  19127. if (!styles.italics) {
  19128. const colorIndex = Math.floor(secondByte / 2) - 0x10;
  19129. const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  19130. styles.foreground = colors[colorIndex];
  19131. } else {
  19132. styles.foreground = 'white';
  19133. }
  19134. this.logger.log(2, 'MIDROW: ' + JSON.stringify(styles));
  19135. this.writeScreen.setPen(styles);
  19136. }
  19137. outputDataUpdate(dispatch = false) {
  19138. const time = this.logger.time;
  19139. if (time === null) {
  19140. return;
  19141. }
  19142. if (this.outputFilter) {
  19143. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  19144. // Start of a new cue
  19145. this.cueStartTime = time;
  19146. } else {
  19147. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  19148. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  19149. if (dispatch && this.outputFilter.dispatchCue) {
  19150. this.outputFilter.dispatchCue();
  19151. }
  19152. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  19153. }
  19154. }
  19155. this.lastOutputScreen.copy(this.displayedMemory);
  19156. }
  19157. }
  19158. cueSplitAtTime(t) {
  19159. if (this.outputFilter) {
  19160. if (!this.displayedMemory.isEmpty()) {
  19161. if (this.outputFilter.newCue) {
  19162. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  19163. }
  19164. this.cueStartTime = t;
  19165. }
  19166. }
  19167. }
  19168. }
  19169. // Will be 1 or 2 when parsing captions
  19170. class Cea608Parser {
  19171. constructor(field, out1, out2) {
  19172. this.channels = void 0;
  19173. this.currentChannel = 0;
  19174. this.cmdHistory = createCmdHistory();
  19175. this.logger = void 0;
  19176. const logger = this.logger = new CaptionsLogger();
  19177. this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
  19178. }
  19179. getHandler(channel) {
  19180. return this.channels[channel].getHandler();
  19181. }
  19182. setHandler(channel, newHandler) {
  19183. this.channels[channel].setHandler(newHandler);
  19184. }
  19185. /**
  19186. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  19187. */
  19188. addData(time, byteList) {
  19189. this.logger.time = time;
  19190. for (let i = 0; i < byteList.length; i += 2) {
  19191. const a = byteList[i] & 0x7f;
  19192. const b = byteList[i + 1] & 0x7f;
  19193. let cmdFound = false;
  19194. let charsFound = null;
  19195. if (a === 0 && b === 0) {
  19196. continue;
  19197. } else {
  19198. this.logger.log(3, () => '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  19199. }
  19200. const cmdHistory = this.cmdHistory;
  19201. const isControlCode = a >= 0x10 && a <= 0x1f;
  19202. if (isControlCode) {
  19203. // Skip redundant control codes
  19204. if (hasCmdRepeated(a, b, cmdHistory)) {
  19205. setLastCmd(null, null, cmdHistory);
  19206. this.logger.log(3, () => 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  19207. continue;
  19208. }
  19209. setLastCmd(a, b, this.cmdHistory);
  19210. cmdFound = this.parseCmd(a, b);
  19211. if (!cmdFound) {
  19212. cmdFound = this.parseMidrow(a, b);
  19213. }
  19214. if (!cmdFound) {
  19215. cmdFound = this.parsePAC(a, b);
  19216. }
  19217. if (!cmdFound) {
  19218. cmdFound = this.parseBackgroundAttributes(a, b);
  19219. }
  19220. } else {
  19221. setLastCmd(null, null, cmdHistory);
  19222. }
  19223. if (!cmdFound) {
  19224. charsFound = this.parseChars(a, b);
  19225. if (charsFound) {
  19226. const currChNr = this.currentChannel;
  19227. if (currChNr && currChNr > 0) {
  19228. const channel = this.channels[currChNr];
  19229. channel.insertChars(charsFound);
  19230. } else {
  19231. this.logger.log(2, 'No channel found yet. TEXT-MODE?');
  19232. }
  19233. }
  19234. }
  19235. if (!cmdFound && !charsFound) {
  19236. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  19237. }
  19238. }
  19239. }
  19240. /**
  19241. * Parse Command.
  19242. * @returns True if a command was found
  19243. */
  19244. parseCmd(a, b) {
  19245. const cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
  19246. const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
  19247. if (!(cond1 || cond2)) {
  19248. return false;
  19249. }
  19250. const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
  19251. const channel = this.channels[chNr];
  19252. if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
  19253. if (b === 0x20) {
  19254. channel.ccRCL();
  19255. } else if (b === 0x21) {
  19256. channel.ccBS();
  19257. } else if (b === 0x22) {
  19258. channel.ccAOF();
  19259. } else if (b === 0x23) {
  19260. channel.ccAON();
  19261. } else if (b === 0x24) {
  19262. channel.ccDER();
  19263. } else if (b === 0x25) {
  19264. channel.ccRU(2);
  19265. } else if (b === 0x26) {
  19266. channel.ccRU(3);
  19267. } else if (b === 0x27) {
  19268. channel.ccRU(4);
  19269. } else if (b === 0x28) {
  19270. channel.ccFON();
  19271. } else if (b === 0x29) {
  19272. channel.ccRDC();
  19273. } else if (b === 0x2a) {
  19274. channel.ccTR();
  19275. } else if (b === 0x2b) {
  19276. channel.ccRTD();
  19277. } else if (b === 0x2c) {
  19278. channel.ccEDM();
  19279. } else if (b === 0x2d) {
  19280. channel.ccCR();
  19281. } else if (b === 0x2e) {
  19282. channel.ccENM();
  19283. } else if (b === 0x2f) {
  19284. channel.ccEOC();
  19285. }
  19286. } else {
  19287. // a == 0x17 || a == 0x1F
  19288. channel.ccTO(b - 0x20);
  19289. }
  19290. this.currentChannel = chNr;
  19291. return true;
  19292. }
  19293. /**
  19294. * Parse midrow styling command
  19295. */
  19296. parseMidrow(a, b) {
  19297. let chNr = 0;
  19298. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  19299. if (a === 0x11) {
  19300. chNr = 1;
  19301. } else {
  19302. chNr = 2;
  19303. }
  19304. if (chNr !== this.currentChannel) {
  19305. this.logger.log(0, 'Mismatch channel in midrow parsing');
  19306. return false;
  19307. }
  19308. const channel = this.channels[chNr];
  19309. if (!channel) {
  19310. return false;
  19311. }
  19312. channel.ccMIDROW(b);
  19313. this.logger.log(3, () => 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  19314. return true;
  19315. }
  19316. return false;
  19317. }
  19318. /**
  19319. * Parse Preable Access Codes (Table 53).
  19320. * @returns {Boolean} Tells if PAC found
  19321. */
  19322. parsePAC(a, b) {
  19323. let row;
  19324. const case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
  19325. const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
  19326. if (!(case1 || case2)) {
  19327. return false;
  19328. }
  19329. const chNr = a <= 0x17 ? 1 : 2;
  19330. if (b >= 0x40 && b <= 0x5f) {
  19331. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  19332. } else {
  19333. // 0x60 <= b <= 0x7F
  19334. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  19335. }
  19336. const channel = this.channels[chNr];
  19337. if (!channel) {
  19338. return false;
  19339. }
  19340. channel.setPAC(this.interpretPAC(row, b));
  19341. this.currentChannel = chNr;
  19342. return true;
  19343. }
  19344. /**
  19345. * Interpret the second byte of the pac, and return the information.
  19346. * @returns pacData with style parameters
  19347. */
  19348. interpretPAC(row, byte) {
  19349. let pacIndex;
  19350. const pacData = {
  19351. color: null,
  19352. italics: false,
  19353. indent: null,
  19354. underline: false,
  19355. row: row
  19356. };
  19357. if (byte > 0x5f) {
  19358. pacIndex = byte - 0x60;
  19359. } else {
  19360. pacIndex = byte - 0x40;
  19361. }
  19362. pacData.underline = (pacIndex & 1) === 1;
  19363. if (pacIndex <= 0xd) {
  19364. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  19365. } else if (pacIndex <= 0xf) {
  19366. pacData.italics = true;
  19367. pacData.color = 'white';
  19368. } else {
  19369. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  19370. }
  19371. return pacData; // Note that row has zero offset. The spec uses 1.
  19372. }
  19373. /**
  19374. * Parse characters.
  19375. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  19376. */
  19377. parseChars(a, b) {
  19378. let channelNr;
  19379. let charCodes = null;
  19380. let charCode1 = null;
  19381. if (a >= 0x19) {
  19382. channelNr = 2;
  19383. charCode1 = a - 8;
  19384. } else {
  19385. channelNr = 1;
  19386. charCode1 = a;
  19387. }
  19388. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  19389. // Special character
  19390. let oneCode;
  19391. if (charCode1 === 0x11) {
  19392. oneCode = b + 0x50;
  19393. } else if (charCode1 === 0x12) {
  19394. oneCode = b + 0x70;
  19395. } else {
  19396. oneCode = b + 0x90;
  19397. }
  19398. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  19399. charCodes = [oneCode];
  19400. } else if (a >= 0x20 && a <= 0x7f) {
  19401. charCodes = b === 0 ? [a] : [a, b];
  19402. }
  19403. if (charCodes) {
  19404. this.logger.log(3, () => 'Char codes = ' + numArrayToHexArray(charCodes).join(','));
  19405. }
  19406. return charCodes;
  19407. }
  19408. /**
  19409. * Parse extended background attributes as well as new foreground color black.
  19410. * @returns True if background attributes are found
  19411. */
  19412. parseBackgroundAttributes(a, b) {
  19413. const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  19414. const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  19415. if (!(case1 || case2)) {
  19416. return false;
  19417. }
  19418. let index;
  19419. const bkgData = {};
  19420. if (a === 0x10 || a === 0x18) {
  19421. index = Math.floor((b - 0x20) / 2);
  19422. bkgData.background = backgroundColors[index];
  19423. if (b % 2 === 1) {
  19424. bkgData.background = bkgData.background + '_semi';
  19425. }
  19426. } else if (b === 0x2d) {
  19427. bkgData.background = 'transparent';
  19428. } else {
  19429. bkgData.foreground = 'black';
  19430. if (b === 0x2f) {
  19431. bkgData.underline = true;
  19432. }
  19433. }
  19434. const chNr = a <= 0x17 ? 1 : 2;
  19435. const channel = this.channels[chNr];
  19436. channel.setBkgData(bkgData);
  19437. return true;
  19438. }
  19439. /**
  19440. * Reset state of parser and its channels.
  19441. */
  19442. reset() {
  19443. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  19444. const channel = this.channels[i];
  19445. if (channel) {
  19446. channel.reset();
  19447. }
  19448. }
  19449. setLastCmd(null, null, this.cmdHistory);
  19450. }
  19451. /**
  19452. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  19453. */
  19454. cueSplitAtTime(t) {
  19455. for (let i = 0; i < this.channels.length; i++) {
  19456. const channel = this.channels[i];
  19457. if (channel) {
  19458. channel.cueSplitAtTime(t);
  19459. }
  19460. }
  19461. }
  19462. }
  19463. function setLastCmd(a, b, cmdHistory) {
  19464. cmdHistory.a = a;
  19465. cmdHistory.b = b;
  19466. }
  19467. function hasCmdRepeated(a, b, cmdHistory) {
  19468. return cmdHistory.a === a && cmdHistory.b === b;
  19469. }
  19470. function createCmdHistory() {
  19471. return {
  19472. a: null,
  19473. b: null
  19474. };
  19475. }
  19476. class OutputFilter {
  19477. constructor(timelineController, trackName) {
  19478. this.timelineController = void 0;
  19479. this.cueRanges = [];
  19480. this.trackName = void 0;
  19481. this.startTime = null;
  19482. this.endTime = null;
  19483. this.screen = null;
  19484. this.timelineController = timelineController;
  19485. this.trackName = trackName;
  19486. }
  19487. dispatchCue() {
  19488. if (this.startTime === null) {
  19489. return;
  19490. }
  19491. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  19492. this.startTime = null;
  19493. }
  19494. newCue(startTime, endTime, screen) {
  19495. if (this.startTime === null || this.startTime > startTime) {
  19496. this.startTime = startTime;
  19497. }
  19498. this.endTime = endTime;
  19499. this.screen = screen;
  19500. this.timelineController.createCaptionsTrack(this.trackName);
  19501. }
  19502. reset() {
  19503. this.cueRanges = [];
  19504. this.startTime = null;
  19505. }
  19506. }
  19507. /**
  19508. * Copyright 2013 vtt.js Contributors
  19509. *
  19510. * Licensed under the Apache License, Version 2.0 (the 'License');
  19511. * you may not use this file except in compliance with the License.
  19512. * You may obtain a copy of the License at
  19513. *
  19514. * http://www.apache.org/licenses/LICENSE-2.0
  19515. *
  19516. * Unless required by applicable law or agreed to in writing, software
  19517. * distributed under the License is distributed on an 'AS IS' BASIS,
  19518. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19519. * See the License for the specific language governing permissions and
  19520. * limitations under the License.
  19521. */
  19522. var VTTCue = (function () {
  19523. if (optionalSelf != null && optionalSelf.VTTCue) {
  19524. return self.VTTCue;
  19525. }
  19526. const AllowedDirections = ['', 'lr', 'rl'];
  19527. const AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
  19528. function isAllowedValue(allowed, value) {
  19529. if (typeof value !== 'string') {
  19530. return false;
  19531. }
  19532. // necessary for assuring the generic conforms to the Array interface
  19533. if (!Array.isArray(allowed)) {
  19534. return false;
  19535. }
  19536. // reset the type so that the next narrowing works well
  19537. const lcValue = value.toLowerCase();
  19538. // use the allow list to narrow the type to a specific subset of strings
  19539. if (~allowed.indexOf(lcValue)) {
  19540. return lcValue;
  19541. }
  19542. return false;
  19543. }
  19544. function findDirectionSetting(value) {
  19545. return isAllowedValue(AllowedDirections, value);
  19546. }
  19547. function findAlignSetting(value) {
  19548. return isAllowedValue(AllowedAlignments, value);
  19549. }
  19550. function extend(obj, ...rest) {
  19551. let i = 1;
  19552. for (; i < arguments.length; i++) {
  19553. const cobj = arguments[i];
  19554. for (const p in cobj) {
  19555. obj[p] = cobj[p];
  19556. }
  19557. }
  19558. return obj;
  19559. }
  19560. function VTTCue(startTime, endTime, text) {
  19561. const cue = this;
  19562. const baseObj = {
  19563. enumerable: true
  19564. };
  19565. /**
  19566. * Shim implementation specific properties. These properties are not in
  19567. * the spec.
  19568. */
  19569. // Lets us know when the VTTCue's data has changed in such a way that we need
  19570. // to recompute its display state. This lets us compute its display state
  19571. // lazily.
  19572. cue.hasBeenReset = false;
  19573. /**
  19574. * VTTCue and TextTrackCue properties
  19575. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  19576. */
  19577. let _id = '';
  19578. let _pauseOnExit = false;
  19579. let _startTime = startTime;
  19580. let _endTime = endTime;
  19581. let _text = text;
  19582. let _region = null;
  19583. let _vertical = '';
  19584. let _snapToLines = true;
  19585. let _line = 'auto';
  19586. let _lineAlign = 'start';
  19587. let _position = 50;
  19588. let _positionAlign = 'middle';
  19589. let _size = 50;
  19590. let _align = 'middle';
  19591. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  19592. get: function () {
  19593. return _id;
  19594. },
  19595. set: function (value) {
  19596. _id = '' + value;
  19597. }
  19598. }));
  19599. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  19600. get: function () {
  19601. return _pauseOnExit;
  19602. },
  19603. set: function (value) {
  19604. _pauseOnExit = !!value;
  19605. }
  19606. }));
  19607. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  19608. get: function () {
  19609. return _startTime;
  19610. },
  19611. set: function (value) {
  19612. if (typeof value !== 'number') {
  19613. throw new TypeError('Start time must be set to a number.');
  19614. }
  19615. _startTime = value;
  19616. this.hasBeenReset = true;
  19617. }
  19618. }));
  19619. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  19620. get: function () {
  19621. return _endTime;
  19622. },
  19623. set: function (value) {
  19624. if (typeof value !== 'number') {
  19625. throw new TypeError('End time must be set to a number.');
  19626. }
  19627. _endTime = value;
  19628. this.hasBeenReset = true;
  19629. }
  19630. }));
  19631. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  19632. get: function () {
  19633. return _text;
  19634. },
  19635. set: function (value) {
  19636. _text = '' + value;
  19637. this.hasBeenReset = true;
  19638. }
  19639. }));
  19640. // todo: implement VTTRegion polyfill?
  19641. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  19642. get: function () {
  19643. return _region;
  19644. },
  19645. set: function (value) {
  19646. _region = value;
  19647. this.hasBeenReset = true;
  19648. }
  19649. }));
  19650. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  19651. get: function () {
  19652. return _vertical;
  19653. },
  19654. set: function (value) {
  19655. const setting = findDirectionSetting(value);
  19656. // Have to check for false because the setting an be an empty string.
  19657. if (setting === false) {
  19658. throw new SyntaxError('An invalid or illegal string was specified.');
  19659. }
  19660. _vertical = setting;
  19661. this.hasBeenReset = true;
  19662. }
  19663. }));
  19664. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  19665. get: function () {
  19666. return _snapToLines;
  19667. },
  19668. set: function (value) {
  19669. _snapToLines = !!value;
  19670. this.hasBeenReset = true;
  19671. }
  19672. }));
  19673. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  19674. get: function () {
  19675. return _line;
  19676. },
  19677. set: function (value) {
  19678. if (typeof value !== 'number' && value !== 'auto') {
  19679. throw new SyntaxError('An invalid number or illegal string was specified.');
  19680. }
  19681. _line = value;
  19682. this.hasBeenReset = true;
  19683. }
  19684. }));
  19685. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  19686. get: function () {
  19687. return _lineAlign;
  19688. },
  19689. set: function (value) {
  19690. const setting = findAlignSetting(value);
  19691. if (!setting) {
  19692. throw new SyntaxError('An invalid or illegal string was specified.');
  19693. }
  19694. _lineAlign = setting;
  19695. this.hasBeenReset = true;
  19696. }
  19697. }));
  19698. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  19699. get: function () {
  19700. return _position;
  19701. },
  19702. set: function (value) {
  19703. if (value < 0 || value > 100) {
  19704. throw new Error('Position must be between 0 and 100.');
  19705. }
  19706. _position = value;
  19707. this.hasBeenReset = true;
  19708. }
  19709. }));
  19710. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  19711. get: function () {
  19712. return _positionAlign;
  19713. },
  19714. set: function (value) {
  19715. const setting = findAlignSetting(value);
  19716. if (!setting) {
  19717. throw new SyntaxError('An invalid or illegal string was specified.');
  19718. }
  19719. _positionAlign = setting;
  19720. this.hasBeenReset = true;
  19721. }
  19722. }));
  19723. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  19724. get: function () {
  19725. return _size;
  19726. },
  19727. set: function (value) {
  19728. if (value < 0 || value > 100) {
  19729. throw new Error('Size must be between 0 and 100.');
  19730. }
  19731. _size = value;
  19732. this.hasBeenReset = true;
  19733. }
  19734. }));
  19735. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  19736. get: function () {
  19737. return _align;
  19738. },
  19739. set: function (value) {
  19740. const setting = findAlignSetting(value);
  19741. if (!setting) {
  19742. throw new SyntaxError('An invalid or illegal string was specified.');
  19743. }
  19744. _align = setting;
  19745. this.hasBeenReset = true;
  19746. }
  19747. }));
  19748. /**
  19749. * Other <track> spec defined properties
  19750. */
  19751. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  19752. cue.displayState = undefined;
  19753. }
  19754. /**
  19755. * VTTCue methods
  19756. */
  19757. VTTCue.prototype.getCueAsHTML = function () {
  19758. // Assume WebVTT.convertCueToDOMTree is on the global.
  19759. const WebVTT = self.WebVTT;
  19760. return WebVTT.convertCueToDOMTree(self, this.text);
  19761. };
  19762. // this is a polyfill hack
  19763. return VTTCue;
  19764. })();
  19765. /*
  19766. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
  19767. */
  19768. class StringDecoder {
  19769. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  19770. decode(data, options) {
  19771. if (!data) {
  19772. return '';
  19773. }
  19774. if (typeof data !== 'string') {
  19775. throw new Error('Error - expected string data.');
  19776. }
  19777. return decodeURIComponent(encodeURIComponent(data));
  19778. }
  19779. }
  19780. // Try to parse input as a time stamp.
  19781. function parseTimeStamp(input) {
  19782. function computeSeconds(h, m, s, f) {
  19783. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
  19784. }
  19785. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  19786. if (!m) {
  19787. return null;
  19788. }
  19789. if (parseFloat(m[2]) > 59) {
  19790. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  19791. // First position is hours as it's over 59.
  19792. return computeSeconds(m[2], m[3], 0, m[4]);
  19793. }
  19794. // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
  19795. return computeSeconds(m[1], m[2], m[3], m[4]);
  19796. }
  19797. // A settings object holds key/value pairs and will ignore anything but the first
  19798. // assignment to a specific key.
  19799. class Settings {
  19800. constructor() {
  19801. this.values = Object.create(null);
  19802. }
  19803. // Only accept the first assignment to any key.
  19804. set(k, v) {
  19805. if (!this.get(k) && v !== '') {
  19806. this.values[k] = v;
  19807. }
  19808. }
  19809. // Return the value for a key, or a default value.
  19810. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  19811. // a number of possible default values as properties where 'defaultKey' is
  19812. // the key of the property that will be chosen; otherwise it's assumed to be
  19813. // a single value.
  19814. get(k, dflt, defaultKey) {
  19815. if (defaultKey) {
  19816. return this.has(k) ? this.values[k] : dflt[defaultKey];
  19817. }
  19818. return this.has(k) ? this.values[k] : dflt;
  19819. }
  19820. // Check whether we have a value for a key.
  19821. has(k) {
  19822. return k in this.values;
  19823. }
  19824. // Accept a setting if its one of the given alternatives.
  19825. alt(k, v, a) {
  19826. for (let n = 0; n < a.length; ++n) {
  19827. if (v === a[n]) {
  19828. this.set(k, v);
  19829. break;
  19830. }
  19831. }
  19832. }
  19833. // Accept a setting if its a valid (signed) integer.
  19834. integer(k, v) {
  19835. if (/^-?\d+$/.test(v)) {
  19836. // integer
  19837. this.set(k, parseInt(v, 10));
  19838. }
  19839. }
  19840. // Accept a setting if its a valid percentage.
  19841. percent(k, v) {
  19842. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  19843. const percent = parseFloat(v);
  19844. if (percent >= 0 && percent <= 100) {
  19845. this.set(k, percent);
  19846. return true;
  19847. }
  19848. }
  19849. return false;
  19850. }
  19851. }
  19852. // Helper function to parse input into groups separated by 'groupDelim', and
  19853. // interpret each group as a key/value pair separated by 'keyValueDelim'.
  19854. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  19855. const groups = groupDelim ? input.split(groupDelim) : [input];
  19856. for (const i in groups) {
  19857. if (typeof groups[i] !== 'string') {
  19858. continue;
  19859. }
  19860. const kv = groups[i].split(keyValueDelim);
  19861. if (kv.length !== 2) {
  19862. continue;
  19863. }
  19864. const k = kv[0];
  19865. const v = kv[1];
  19866. callback(k, v);
  19867. }
  19868. }
  19869. const defaults = new VTTCue(0, 0, '');
  19870. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  19871. // Safari doesn't yet support this change, but FF and Chrome do.
  19872. const center = defaults.align === 'middle' ? 'middle' : 'center';
  19873. function parseCue(input, cue, regionList) {
  19874. // Remember the original input if we need to throw an error.
  19875. const oInput = input;
  19876. // 4.1 WebVTT timestamp
  19877. function consumeTimeStamp() {
  19878. const ts = parseTimeStamp(input);
  19879. if (ts === null) {
  19880. throw new Error('Malformed timestamp: ' + oInput);
  19881. }
  19882. // Remove time stamp from input.
  19883. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  19884. return ts;
  19885. }
  19886. // 4.4.2 WebVTT cue settings
  19887. function consumeCueSettings(input, cue) {
  19888. const settings = new Settings();
  19889. parseOptions(input, function (k, v) {
  19890. let vals;
  19891. switch (k) {
  19892. case 'region':
  19893. // Find the last region we parsed with the same region id.
  19894. for (let i = regionList.length - 1; i >= 0; i--) {
  19895. if (regionList[i].id === v) {
  19896. settings.set(k, regionList[i].region);
  19897. break;
  19898. }
  19899. }
  19900. break;
  19901. case 'vertical':
  19902. settings.alt(k, v, ['rl', 'lr']);
  19903. break;
  19904. case 'line':
  19905. vals = v.split(',');
  19906. settings.integer(k, vals[0]);
  19907. if (settings.percent(k, vals[0])) {
  19908. settings.set('snapToLines', false);
  19909. }
  19910. settings.alt(k, vals[0], ['auto']);
  19911. if (vals.length === 2) {
  19912. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  19913. }
  19914. break;
  19915. case 'position':
  19916. vals = v.split(',');
  19917. settings.percent(k, vals[0]);
  19918. if (vals.length === 2) {
  19919. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  19920. }
  19921. break;
  19922. case 'size':
  19923. settings.percent(k, v);
  19924. break;
  19925. case 'align':
  19926. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  19927. break;
  19928. }
  19929. }, /:/, /\s/);
  19930. // Apply default values for any missing fields.
  19931. cue.region = settings.get('region', null);
  19932. cue.vertical = settings.get('vertical', '');
  19933. let line = settings.get('line', 'auto');
  19934. if (line === 'auto' && defaults.line === -1) {
  19935. // set numeric line number for Safari
  19936. line = -1;
  19937. }
  19938. cue.line = line;
  19939. cue.lineAlign = settings.get('lineAlign', 'start');
  19940. cue.snapToLines = settings.get('snapToLines', true);
  19941. cue.size = settings.get('size', 100);
  19942. cue.align = settings.get('align', center);
  19943. let position = settings.get('position', 'auto');
  19944. if (position === 'auto' && defaults.position === 50) {
  19945. // set numeric position for Safari
  19946. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  19947. }
  19948. cue.position = position;
  19949. }
  19950. function skipWhitespace() {
  19951. input = input.replace(/^\s+/, '');
  19952. }
  19953. // 4.1 WebVTT cue timings.
  19954. skipWhitespace();
  19955. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  19956. skipWhitespace();
  19957. if (input.slice(0, 3) !== '-->') {
  19958. // (3) next characters must match '-->'
  19959. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  19960. }
  19961. input = input.slice(3);
  19962. skipWhitespace();
  19963. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  19964. // 4.1 WebVTT cue settings list.
  19965. skipWhitespace();
  19966. consumeCueSettings(input, cue);
  19967. }
  19968. function fixLineBreaks(input) {
  19969. return input.replace(/<br(?: \/)?>/gi, '\n');
  19970. }
  19971. class VTTParser {
  19972. constructor() {
  19973. this.state = 'INITIAL';
  19974. this.buffer = '';
  19975. this.decoder = new StringDecoder();
  19976. this.regionList = [];
  19977. this.cue = null;
  19978. this.oncue = void 0;
  19979. this.onparsingerror = void 0;
  19980. this.onflush = void 0;
  19981. }
  19982. parse(data) {
  19983. const _this = this;
  19984. // If there is no data then we won't decode it, but will just try to parse
  19985. // whatever is in buffer already. This may occur in circumstances, for
  19986. // example when flush() is called.
  19987. if (data) {
  19988. // Try to decode the data that we received.
  19989. _this.buffer += _this.decoder.decode(data, {
  19990. stream: true
  19991. });
  19992. }
  19993. function collectNextLine() {
  19994. let buffer = _this.buffer;
  19995. let pos = 0;
  19996. buffer = fixLineBreaks(buffer);
  19997. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  19998. ++pos;
  19999. }
  20000. const line = buffer.slice(0, pos);
  20001. // Advance the buffer early in case we fail below.
  20002. if (buffer[pos] === '\r') {
  20003. ++pos;
  20004. }
  20005. if (buffer[pos] === '\n') {
  20006. ++pos;
  20007. }
  20008. _this.buffer = buffer.slice(pos);
  20009. return line;
  20010. }
  20011. // 3.2 WebVTT metadata header syntax
  20012. function parseHeader(input) {
  20013. parseOptions(input, function (k, v) {
  20014. // switch (k) {
  20015. // case 'region':
  20016. // 3.3 WebVTT region metadata header syntax
  20017. // console.log('parse region', v);
  20018. // parseRegion(v);
  20019. // break;
  20020. // }
  20021. }, /:/);
  20022. }
  20023. // 5.1 WebVTT file parsing.
  20024. try {
  20025. let line = '';
  20026. if (_this.state === 'INITIAL') {
  20027. // We can't start parsing until we have the first line.
  20028. if (!/\r\n|\n/.test(_this.buffer)) {
  20029. return this;
  20030. }
  20031. line = collectNextLine();
  20032. // strip of UTF-8 BOM if any
  20033. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  20034. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  20035. if (!(m != null && m[0])) {
  20036. throw new Error('Malformed WebVTT signature.');
  20037. }
  20038. _this.state = 'HEADER';
  20039. }
  20040. let alreadyCollectedLine = false;
  20041. while (_this.buffer) {
  20042. // We can't parse a line until we have the full line.
  20043. if (!/\r\n|\n/.test(_this.buffer)) {
  20044. return this;
  20045. }
  20046. if (!alreadyCollectedLine) {
  20047. line = collectNextLine();
  20048. } else {
  20049. alreadyCollectedLine = false;
  20050. }
  20051. switch (_this.state) {
  20052. case 'HEADER':
  20053. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  20054. if (/:/.test(line)) {
  20055. parseHeader(line);
  20056. } else if (!line) {
  20057. // An empty line terminates the header and starts the body (cues).
  20058. _this.state = 'ID';
  20059. }
  20060. continue;
  20061. case 'NOTE':
  20062. // Ignore NOTE blocks.
  20063. if (!line) {
  20064. _this.state = 'ID';
  20065. }
  20066. continue;
  20067. case 'ID':
  20068. // Check for the start of NOTE blocks.
  20069. if (/^NOTE($|[ \t])/.test(line)) {
  20070. _this.state = 'NOTE';
  20071. break;
  20072. }
  20073. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  20074. if (!line) {
  20075. continue;
  20076. }
  20077. _this.cue = new VTTCue(0, 0, '');
  20078. _this.state = 'CUE';
  20079. // 30-39 - Check if self line contains an optional identifier or timing data.
  20080. if (line.indexOf('-->') === -1) {
  20081. _this.cue.id = line;
  20082. continue;
  20083. }
  20084. // Process line as start of a cue.
  20085. /* falls through */
  20086. case 'CUE':
  20087. // 40 - Collect cue timings and settings.
  20088. if (!_this.cue) {
  20089. _this.state = 'BADCUE';
  20090. continue;
  20091. }
  20092. try {
  20093. parseCue(line, _this.cue, _this.regionList);
  20094. } catch (e) {
  20095. // In case of an error ignore rest of the cue.
  20096. _this.cue = null;
  20097. _this.state = 'BADCUE';
  20098. continue;
  20099. }
  20100. _this.state = 'CUETEXT';
  20101. continue;
  20102. case 'CUETEXT':
  20103. {
  20104. const hasSubstring = line.indexOf('-->') !== -1;
  20105. // 34 - If we have an empty line then report the cue.
  20106. // 35 - If we have the special substring '-->' then report the cue,
  20107. // but do not collect the line as we need to process the current
  20108. // one as a new cue.
  20109. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  20110. // We are done parsing self cue.
  20111. if (_this.oncue && _this.cue) {
  20112. _this.oncue(_this.cue);
  20113. }
  20114. _this.cue = null;
  20115. _this.state = 'ID';
  20116. continue;
  20117. }
  20118. if (_this.cue === null) {
  20119. continue;
  20120. }
  20121. if (_this.cue.text) {
  20122. _this.cue.text += '\n';
  20123. }
  20124. _this.cue.text += line;
  20125. }
  20126. continue;
  20127. case 'BADCUE':
  20128. // 54-62 - Collect and discard the remaining cue.
  20129. if (!line) {
  20130. _this.state = 'ID';
  20131. }
  20132. }
  20133. }
  20134. } catch (e) {
  20135. // If we are currently parsing a cue, report what we have.
  20136. if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
  20137. _this.oncue(_this.cue);
  20138. }
  20139. _this.cue = null;
  20140. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  20141. // another exception occurred so enter BADCUE state.
  20142. _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  20143. }
  20144. return this;
  20145. }
  20146. flush() {
  20147. const _this = this;
  20148. try {
  20149. // Finish decoding the stream.
  20150. // _this.buffer += _this.decoder.decode();
  20151. // Synthesize the end of the current cue or region.
  20152. if (_this.cue || _this.state === 'HEADER') {
  20153. _this.buffer += '\n\n';
  20154. _this.parse();
  20155. }
  20156. // If we've flushed, parsed, and we're still on the INITIAL state then
  20157. // that means we don't have enough of the stream to parse the first
  20158. // line.
  20159. if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
  20160. throw new Error('Malformed WebVTT signature.');
  20161. }
  20162. } catch (e) {
  20163. if (_this.onparsingerror) {
  20164. _this.onparsingerror(e);
  20165. }
  20166. }
  20167. if (_this.onflush) {
  20168. _this.onflush();
  20169. }
  20170. return this;
  20171. }
  20172. }
  20173. const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  20174. // String.prototype.startsWith is not supported in IE11
  20175. const startsWith = function startsWith(inputString, searchString, position = 0) {
  20176. return inputString.slice(position, position + searchString.length) === searchString;
  20177. };
  20178. const cueString2millis = function cueString2millis(timeString) {
  20179. let ts = parseInt(timeString.slice(-3));
  20180. const secs = parseInt(timeString.slice(-6, -4));
  20181. const mins = parseInt(timeString.slice(-9, -7));
  20182. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(':'))) : 0;
  20183. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  20184. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  20185. }
  20186. ts += 1000 * secs;
  20187. ts += 60 * 1000 * mins;
  20188. ts += 60 * 60 * 1000 * hours;
  20189. return ts;
  20190. };
  20191. // From https://github.com/darkskyapp/string-hash
  20192. const hash = function hash(text) {
  20193. let _hash = 5381;
  20194. let i = text.length;
  20195. while (i) {
  20196. _hash = _hash * 33 ^ text.charCodeAt(--i);
  20197. }
  20198. return (_hash >>> 0).toString();
  20199. };
  20200. // Create a unique hash id for a cue based on start/end times and text.
  20201. // This helps timeline-controller to avoid showing repeated captions.
  20202. function generateCueId(startTime, endTime, text) {
  20203. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  20204. }
  20205. const calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  20206. let currCC = vttCCs[cc];
  20207. let prevCC = vttCCs[currCC.prevCC];
  20208. // This is the first discontinuity or cues have been processed since the last discontinuity
  20209. // Offset = current discontinuity time
  20210. if (!prevCC || !prevCC.new && currCC.new) {
  20211. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  20212. currCC.new = false;
  20213. return;
  20214. }
  20215. // There have been discontinuities since cues were last parsed.
  20216. // Offset = time elapsed
  20217. while ((_prevCC = prevCC) != null && _prevCC.new) {
  20218. var _prevCC;
  20219. vttCCs.ccOffset += currCC.start - prevCC.start;
  20220. currCC.new = false;
  20221. currCC = prevCC;
  20222. prevCC = vttCCs[currCC.prevCC];
  20223. }
  20224. vttCCs.presentationOffset = presentationTime;
  20225. };
  20226. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  20227. const parser = new VTTParser();
  20228. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  20229. // Uint8Array.prototype.reduce is not implemented in IE11
  20230. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
  20231. const cues = [];
  20232. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  20233. let cueTime = '00:00.000';
  20234. let timestampMapMPEGTS = 0;
  20235. let timestampMapLOCAL = 0;
  20236. let parsingError;
  20237. let inHeader = true;
  20238. parser.oncue = function (cue) {
  20239. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  20240. const currCC = vttCCs[cc];
  20241. let cueOffset = vttCCs.ccOffset;
  20242. // Calculate subtitle PTS offset
  20243. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;
  20244. // Update offsets for new discontinuities
  20245. if (currCC != null && currCC.new) {
  20246. if (timestampMapLOCAL !== undefined) {
  20247. // When local time is provided, offset = discontinuity start time - local time
  20248. cueOffset = vttCCs.ccOffset = currCC.start;
  20249. } else {
  20250. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  20251. }
  20252. }
  20253. if (webVttMpegTsMapOffset) {
  20254. if (!initPTS) {
  20255. parsingError = new Error('Missing initPTS for VTT MPEGTS');
  20256. return;
  20257. }
  20258. // If we have MPEGTS, offset = presentation time + discontinuity offset
  20259. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  20260. }
  20261. const duration = cue.endTime - cue.startTime;
  20262. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
  20263. cue.startTime = Math.max(startTime, 0);
  20264. cue.endTime = Math.max(startTime + duration, 0);
  20265. //trim trailing webvtt block whitespaces
  20266. const text = cue.text.trim();
  20267. // Fix encoding of special characters
  20268. cue.text = decodeURIComponent(encodeURIComponent(text));
  20269. // If the cue was not assigned an id from the VTT file (line above the content), create one.
  20270. if (!cue.id) {
  20271. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  20272. }
  20273. if (cue.endTime > 0) {
  20274. cues.push(cue);
  20275. }
  20276. };
  20277. parser.onparsingerror = function (error) {
  20278. parsingError = error;
  20279. };
  20280. parser.onflush = function () {
  20281. if (parsingError) {
  20282. errorCallBack(parsingError);
  20283. return;
  20284. }
  20285. callBack(cues);
  20286. };
  20287. // Go through contents line by line.
  20288. vttLines.forEach(line => {
  20289. if (inHeader) {
  20290. // Look for X-TIMESTAMP-MAP in header.
  20291. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  20292. // Once found, no more are allowed anyway, so stop searching.
  20293. inHeader = false;
  20294. // Extract LOCAL and MPEGTS.
  20295. line.slice(16).split(',').forEach(timestamp => {
  20296. if (startsWith(timestamp, 'LOCAL:')) {
  20297. cueTime = timestamp.slice(6);
  20298. } else if (startsWith(timestamp, 'MPEGTS:')) {
  20299. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  20300. }
  20301. });
  20302. try {
  20303. // Convert cue time to seconds
  20304. timestampMapLOCAL = cueString2millis(cueTime) / 1000;
  20305. } catch (error) {
  20306. parsingError = error;
  20307. }
  20308. // Return without parsing X-TIMESTAMP-MAP line.
  20309. return;
  20310. } else if (line === '') {
  20311. inHeader = false;
  20312. }
  20313. }
  20314. // Parse line by default.
  20315. parser.parse(line + '\n');
  20316. });
  20317. parser.flush();
  20318. }
  20319. const IMSC1_CODEC = 'stpp.ttml.im1t';
  20320. // Time format: h:m:s:frames(.subframes)
  20321. const HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  20322. // Time format: hours, minutes, seconds, milliseconds, frames, ticks
  20323. const TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  20324. const textAlignToLineAlign = {
  20325. left: 'start',
  20326. center: 'center',
  20327. right: 'end',
  20328. start: 'start',
  20329. end: 'end'
  20330. };
  20331. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  20332. const results = findBox(new Uint8Array(payload), ['mdat']);
  20333. if (results.length === 0) {
  20334. errorCallBack(new Error('Could not parse IMSC1 mdat'));
  20335. return;
  20336. }
  20337. const ttmlList = results.map(mdat => utf8ArrayToStr(mdat));
  20338. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  20339. try {
  20340. ttmlList.forEach(ttml => callBack(parseTTML(ttml, syncTime)));
  20341. } catch (error) {
  20342. errorCallBack(error);
  20343. }
  20344. }
  20345. function parseTTML(ttml, syncTime) {
  20346. const parser = new DOMParser();
  20347. const xmlDoc = parser.parseFromString(ttml, 'text/xml');
  20348. const tt = xmlDoc.getElementsByTagName('tt')[0];
  20349. if (!tt) {
  20350. throw new Error('Invalid ttml');
  20351. }
  20352. const defaultRateInfo = {
  20353. frameRate: 30,
  20354. subFrameRate: 1,
  20355. frameRateMultiplier: 0,
  20356. tickRate: 0
  20357. };
  20358. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  20359. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  20360. return result;
  20361. }, {});
  20362. const trim = tt.getAttribute('xml:space') !== 'preserve';
  20363. const styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
  20364. const regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
  20365. const cueElements = getElementCollection(tt, 'body', '[begin]');
  20366. return [].map.call(cueElements, cueElement => {
  20367. const cueText = getTextContent(cueElement, trim);
  20368. if (!cueText || !cueElement.hasAttribute('begin')) {
  20369. return null;
  20370. }
  20371. const startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
  20372. const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
  20373. let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
  20374. if (startTime === null) {
  20375. throw timestampParsingError(cueElement);
  20376. }
  20377. if (endTime === null) {
  20378. if (duration === null) {
  20379. throw timestampParsingError(cueElement);
  20380. }
  20381. endTime = startTime + duration;
  20382. }
  20383. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  20384. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  20385. const region = regionElements[cueElement.getAttribute('region')];
  20386. const style = styleElements[cueElement.getAttribute('style')];
  20387. // Apply styles to cue
  20388. const styles = getTtmlStyles(region, style, styleElements);
  20389. const {
  20390. textAlign
  20391. } = styles;
  20392. if (textAlign) {
  20393. // cue.positionAlign not settable in FF~2016
  20394. const lineAlign = textAlignToLineAlign[textAlign];
  20395. if (lineAlign) {
  20396. cue.lineAlign = lineAlign;
  20397. }
  20398. cue.align = textAlign;
  20399. }
  20400. _extends(cue, styles);
  20401. return cue;
  20402. }).filter(cue => cue !== null);
  20403. }
  20404. function getElementCollection(fromElement, parentName, childName) {
  20405. const parent = fromElement.getElementsByTagName(parentName)[0];
  20406. if (parent) {
  20407. return [].slice.call(parent.querySelectorAll(childName));
  20408. }
  20409. return [];
  20410. }
  20411. function collectionToDictionary(elementsWithId) {
  20412. return elementsWithId.reduce((dict, element) => {
  20413. const id = element.getAttribute('xml:id');
  20414. if (id) {
  20415. dict[id] = element;
  20416. }
  20417. return dict;
  20418. }, {});
  20419. }
  20420. function getTextContent(element, trim) {
  20421. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  20422. var _node$childNodes;
  20423. if (node.nodeName === 'br' && i) {
  20424. return str + '\n';
  20425. }
  20426. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  20427. return getTextContent(node, trim);
  20428. } else if (trim) {
  20429. return str + node.textContent.trim().replace(/\s+/g, ' ');
  20430. }
  20431. return str + node.textContent;
  20432. }, '');
  20433. }
  20434. function getTtmlStyles(region, style, styleElements) {
  20435. const ttsNs = 'http://www.w3.org/ns/ttml#styling';
  20436. let regionStyle = null;
  20437. const styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily'
  20438. // 'fontWeight',
  20439. // 'lineHeight',
  20440. // 'wrapOption',
  20441. // 'fontStyle',
  20442. // 'direction',
  20443. // 'writingMode'
  20444. ];
  20445. const regionStyleName = region != null && region.hasAttribute('style') ? region.getAttribute('style') : null;
  20446. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  20447. regionStyle = styleElements[regionStyleName];
  20448. }
  20449. return styleAttributes.reduce((styles, name) => {
  20450. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  20451. if (value) {
  20452. styles[name] = value;
  20453. }
  20454. return styles;
  20455. }, {});
  20456. }
  20457. function getAttributeNS(element, ns, name) {
  20458. if (!element) {
  20459. return null;
  20460. }
  20461. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  20462. }
  20463. function timestampParsingError(node) {
  20464. return new Error(`Could not parse ttml timestamp ${node}`);
  20465. }
  20466. function parseTtmlTime(timeAttributeValue, rateInfo) {
  20467. if (!timeAttributeValue) {
  20468. return null;
  20469. }
  20470. let seconds = parseTimeStamp(timeAttributeValue);
  20471. if (seconds === null) {
  20472. if (HMSF_REGEX.test(timeAttributeValue)) {
  20473. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  20474. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  20475. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  20476. }
  20477. }
  20478. return seconds;
  20479. }
  20480. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  20481. const m = HMSF_REGEX.exec(timeAttributeValue);
  20482. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  20483. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  20484. }
  20485. function parseTimeUnits(timeAttributeValue, rateInfo) {
  20486. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  20487. const value = Number(m[1]);
  20488. const unit = m[2];
  20489. switch (unit) {
  20490. case 'h':
  20491. return value * 3600;
  20492. case 'm':
  20493. return value * 60;
  20494. case 'ms':
  20495. return value * 1000;
  20496. case 'f':
  20497. return value / rateInfo.frameRate;
  20498. case 't':
  20499. return value / rateInfo.tickRate;
  20500. }
  20501. return value;
  20502. }
  20503. class TimelineController {
  20504. constructor(hls) {
  20505. this.hls = void 0;
  20506. this.media = null;
  20507. this.config = void 0;
  20508. this.enabled = true;
  20509. this.Cues = void 0;
  20510. this.textTracks = [];
  20511. this.tracks = [];
  20512. this.initPTS = [];
  20513. this.unparsedVttFrags = [];
  20514. this.captionsTracks = {};
  20515. this.nonNativeCaptionsTracks = {};
  20516. this.cea608Parser1 = void 0;
  20517. this.cea608Parser2 = void 0;
  20518. this.lastCc = -1;
  20519. // Last video (CEA-608) fragment CC
  20520. this.lastSn = -1;
  20521. // Last video (CEA-608) fragment MSN
  20522. this.lastPartIndex = -1;
  20523. // Last video (CEA-608) fragment Part Index
  20524. this.prevCC = -1;
  20525. // Last subtitle fragment CC
  20526. this.vttCCs = newVTTCCs();
  20527. this.captionsProperties = void 0;
  20528. this.hls = hls;
  20529. this.config = hls.config;
  20530. this.Cues = hls.config.cueHandler;
  20531. this.captionsProperties = {
  20532. textTrack1: {
  20533. label: this.config.captionsTextTrack1Label,
  20534. languageCode: this.config.captionsTextTrack1LanguageCode
  20535. },
  20536. textTrack2: {
  20537. label: this.config.captionsTextTrack2Label,
  20538. languageCode: this.config.captionsTextTrack2LanguageCode
  20539. },
  20540. textTrack3: {
  20541. label: this.config.captionsTextTrack3Label,
  20542. languageCode: this.config.captionsTextTrack3LanguageCode
  20543. },
  20544. textTrack4: {
  20545. label: this.config.captionsTextTrack4Label,
  20546. languageCode: this.config.captionsTextTrack4LanguageCode
  20547. }
  20548. };
  20549. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20550. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20551. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20552. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20553. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  20554. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  20555. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  20556. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  20557. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  20558. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  20559. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  20560. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  20561. }
  20562. destroy() {
  20563. const {
  20564. hls
  20565. } = this;
  20566. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20567. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20568. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20569. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20570. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  20571. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  20572. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  20573. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  20574. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  20575. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  20576. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  20577. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  20578. // @ts-ignore
  20579. this.hls = this.config = null;
  20580. this.cea608Parser1 = this.cea608Parser2 = undefined;
  20581. }
  20582. initCea608Parsers() {
  20583. if (this.config.enableCEA708Captions && (!this.cea608Parser1 || !this.cea608Parser2)) {
  20584. const channel1 = new OutputFilter(this, 'textTrack1');
  20585. const channel2 = new OutputFilter(this, 'textTrack2');
  20586. const channel3 = new OutputFilter(this, 'textTrack3');
  20587. const channel4 = new OutputFilter(this, 'textTrack4');
  20588. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  20589. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  20590. }
  20591. }
  20592. addCues(trackName, startTime, endTime, screen, cueRanges) {
  20593. // skip cues which overlap more than 50% with previously parsed time ranges
  20594. let merged = false;
  20595. for (let i = cueRanges.length; i--;) {
  20596. const cueRange = cueRanges[i];
  20597. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  20598. if (overlap >= 0) {
  20599. cueRange[0] = Math.min(cueRange[0], startTime);
  20600. cueRange[1] = Math.max(cueRange[1], endTime);
  20601. merged = true;
  20602. if (overlap / (endTime - startTime) > 0.5) {
  20603. return;
  20604. }
  20605. }
  20606. }
  20607. if (!merged) {
  20608. cueRanges.push([startTime, endTime]);
  20609. }
  20610. if (this.config.renderTextTracksNatively) {
  20611. const track = this.captionsTracks[trackName];
  20612. this.Cues.newCue(track, startTime, endTime, screen);
  20613. } else {
  20614. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  20615. this.hls.trigger(Events.CUES_PARSED, {
  20616. type: 'captions',
  20617. cues,
  20618. track: trackName
  20619. });
  20620. }
  20621. }
  20622. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  20623. onInitPtsFound(event, {
  20624. frag,
  20625. id,
  20626. initPTS,
  20627. timescale
  20628. }) {
  20629. const {
  20630. unparsedVttFrags
  20631. } = this;
  20632. if (id === 'main') {
  20633. this.initPTS[frag.cc] = {
  20634. baseTime: initPTS,
  20635. timescale
  20636. };
  20637. }
  20638. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  20639. // Parse any unparsed fragments upon receiving the initial PTS.
  20640. if (unparsedVttFrags.length) {
  20641. this.unparsedVttFrags = [];
  20642. unparsedVttFrags.forEach(frag => {
  20643. this.onFragLoaded(Events.FRAG_LOADED, frag);
  20644. });
  20645. }
  20646. }
  20647. getExistingTrack(label, language) {
  20648. const {
  20649. media
  20650. } = this;
  20651. if (media) {
  20652. for (let i = 0; i < media.textTracks.length; i++) {
  20653. const textTrack = media.textTracks[i];
  20654. if (canReuseVttTextTrack(textTrack, {
  20655. name: label,
  20656. lang: language,
  20657. attrs: {}
  20658. })) {
  20659. return textTrack;
  20660. }
  20661. }
  20662. }
  20663. return null;
  20664. }
  20665. createCaptionsTrack(trackName) {
  20666. if (this.config.renderTextTracksNatively) {
  20667. this.createNativeTrack(trackName);
  20668. } else {
  20669. this.createNonNativeTrack(trackName);
  20670. }
  20671. }
  20672. createNativeTrack(trackName) {
  20673. if (this.captionsTracks[trackName]) {
  20674. return;
  20675. }
  20676. const {
  20677. captionsProperties,
  20678. captionsTracks,
  20679. media
  20680. } = this;
  20681. const {
  20682. label,
  20683. languageCode
  20684. } = captionsProperties[trackName];
  20685. // Enable reuse of existing text track.
  20686. const existingTrack = this.getExistingTrack(label, languageCode);
  20687. if (!existingTrack) {
  20688. const textTrack = this.createTextTrack('captions', label, languageCode);
  20689. if (textTrack) {
  20690. // Set a special property on the track so we know it's managed by Hls.js
  20691. textTrack[trackName] = true;
  20692. captionsTracks[trackName] = textTrack;
  20693. }
  20694. } else {
  20695. captionsTracks[trackName] = existingTrack;
  20696. clearCurrentCues(captionsTracks[trackName]);
  20697. sendAddTrackEvent(captionsTracks[trackName], media);
  20698. }
  20699. }
  20700. createNonNativeTrack(trackName) {
  20701. if (this.nonNativeCaptionsTracks[trackName]) {
  20702. return;
  20703. }
  20704. // Create a list of a single track for the provider to consume
  20705. const trackProperties = this.captionsProperties[trackName];
  20706. if (!trackProperties) {
  20707. return;
  20708. }
  20709. const label = trackProperties.label;
  20710. const track = {
  20711. _id: trackName,
  20712. label,
  20713. kind: 'captions',
  20714. default: trackProperties.media ? !!trackProperties.media.default : false,
  20715. closedCaptions: trackProperties.media
  20716. };
  20717. this.nonNativeCaptionsTracks[trackName] = track;
  20718. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  20719. tracks: [track]
  20720. });
  20721. }
  20722. createTextTrack(kind, label, lang) {
  20723. const media = this.media;
  20724. if (!media) {
  20725. return;
  20726. }
  20727. return media.addTextTrack(kind, label, lang);
  20728. }
  20729. onMediaAttaching(event, data) {
  20730. this.media = data.media;
  20731. this._cleanTracks();
  20732. }
  20733. onMediaDetaching() {
  20734. const {
  20735. captionsTracks
  20736. } = this;
  20737. Object.keys(captionsTracks).forEach(trackName => {
  20738. clearCurrentCues(captionsTracks[trackName]);
  20739. delete captionsTracks[trackName];
  20740. });
  20741. this.nonNativeCaptionsTracks = {};
  20742. }
  20743. onManifestLoading() {
  20744. // Detect discontinuity in video fragment (CEA-608) parsing
  20745. this.lastCc = -1;
  20746. this.lastSn = -1;
  20747. this.lastPartIndex = -1;
  20748. // Detect discontinuity in subtitle manifests
  20749. this.prevCC = -1;
  20750. this.vttCCs = newVTTCCs();
  20751. // Reset tracks
  20752. this._cleanTracks();
  20753. this.tracks = [];
  20754. this.captionsTracks = {};
  20755. this.nonNativeCaptionsTracks = {};
  20756. this.textTracks = [];
  20757. this.unparsedVttFrags = [];
  20758. this.initPTS = [];
  20759. if (this.cea608Parser1 && this.cea608Parser2) {
  20760. this.cea608Parser1.reset();
  20761. this.cea608Parser2.reset();
  20762. }
  20763. }
  20764. _cleanTracks() {
  20765. // clear outdated subtitles
  20766. const {
  20767. media
  20768. } = this;
  20769. if (!media) {
  20770. return;
  20771. }
  20772. const textTracks = media.textTracks;
  20773. if (textTracks) {
  20774. for (let i = 0; i < textTracks.length; i++) {
  20775. clearCurrentCues(textTracks[i]);
  20776. }
  20777. }
  20778. }
  20779. onSubtitleTracksUpdated(event, data) {
  20780. const tracks = data.subtitleTracks || [];
  20781. const hasIMSC1 = tracks.some(track => track.textCodec === IMSC1_CODEC);
  20782. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  20783. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  20784. if (listIsIdentical) {
  20785. this.tracks = tracks;
  20786. return;
  20787. }
  20788. this.textTracks = [];
  20789. this.tracks = tracks;
  20790. if (this.config.renderTextTracksNatively) {
  20791. const media = this.media;
  20792. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  20793. this.tracks.forEach((track, index) => {
  20794. // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks
  20795. let textTrack;
  20796. if (inUseTracks) {
  20797. let inUseTrack = null;
  20798. for (let i = 0; i < inUseTracks.length; i++) {
  20799. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  20800. inUseTrack = inUseTracks[i];
  20801. inUseTracks[i] = null;
  20802. break;
  20803. }
  20804. }
  20805. if (inUseTrack) {
  20806. textTrack = inUseTrack;
  20807. }
  20808. }
  20809. if (textTrack) {
  20810. clearCurrentCues(textTrack);
  20811. } else {
  20812. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  20813. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  20814. if (textTrack) {
  20815. textTrack.mode = 'disabled';
  20816. }
  20817. }
  20818. if (textTrack) {
  20819. this.textTracks.push(textTrack);
  20820. }
  20821. });
  20822. // Warn when video element has captions or subtitle TextTracks carried over from another source
  20823. if (inUseTracks != null && inUseTracks.length) {
  20824. const unusedTextTracks = inUseTracks.filter(t => t !== null).map(t => t.label);
  20825. if (unusedTextTracks.length) {
  20826. logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(', ')}. Replace media element for each source to clear TextTracks and captions menu.`);
  20827. }
  20828. }
  20829. } else if (this.tracks.length) {
  20830. // Create a list of tracks for the provider to consume
  20831. const tracksList = this.tracks.map(track => {
  20832. return {
  20833. label: track.name,
  20834. kind: track.type.toLowerCase(),
  20835. default: track.default,
  20836. subtitleTrack: track
  20837. };
  20838. });
  20839. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  20840. tracks: tracksList
  20841. });
  20842. }
  20843. }
  20844. }
  20845. onManifestLoaded(event, data) {
  20846. if (this.config.enableCEA708Captions && data.captions) {
  20847. data.captions.forEach(captionsTrack => {
  20848. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  20849. if (!instreamIdMatch) {
  20850. return;
  20851. }
  20852. const trackName = `textTrack${instreamIdMatch[1]}`;
  20853. const trackProperties = this.captionsProperties[trackName];
  20854. if (!trackProperties) {
  20855. return;
  20856. }
  20857. trackProperties.label = captionsTrack.name;
  20858. if (captionsTrack.lang) {
  20859. // optional attribute
  20860. trackProperties.languageCode = captionsTrack.lang;
  20861. }
  20862. trackProperties.media = captionsTrack;
  20863. });
  20864. }
  20865. }
  20866. closedCaptionsForLevel(frag) {
  20867. const level = this.hls.levels[frag.level];
  20868. return level == null ? void 0 : level.attrs['CLOSED-CAPTIONS'];
  20869. }
  20870. onFragLoading(event, data) {
  20871. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  20872. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  20873. var _data$part$index, _data$part;
  20874. const {
  20875. cea608Parser1,
  20876. cea608Parser2,
  20877. lastSn
  20878. } = this;
  20879. const {
  20880. cc,
  20881. sn
  20882. } = data.frag;
  20883. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  20884. if (cea608Parser1 && cea608Parser2) {
  20885. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  20886. cea608Parser1.reset();
  20887. cea608Parser2.reset();
  20888. }
  20889. }
  20890. this.lastCc = cc;
  20891. this.lastSn = sn;
  20892. this.lastPartIndex = partIndex;
  20893. }
  20894. }
  20895. onFragLoaded(event, data) {
  20896. const {
  20897. frag,
  20898. payload
  20899. } = data;
  20900. if (frag.type === PlaylistLevelType.SUBTITLE) {
  20901. // If fragment is subtitle type, parse as WebVTT.
  20902. if (payload.byteLength) {
  20903. const decryptData = frag.decryptdata;
  20904. // fragment after decryption has a stats object
  20905. const decrypted = ('stats' in data);
  20906. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  20907. if (decryptData == null || !decryptData.encrypted || decrypted) {
  20908. const trackPlaylistMedia = this.tracks[frag.level];
  20909. const vttCCs = this.vttCCs;
  20910. if (!vttCCs[frag.cc]) {
  20911. vttCCs[frag.cc] = {
  20912. start: frag.start,
  20913. prevCC: this.prevCC,
  20914. new: true
  20915. };
  20916. this.prevCC = frag.cc;
  20917. }
  20918. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  20919. this._parseIMSC1(frag, payload);
  20920. } else {
  20921. this._parseVTTs(data);
  20922. }
  20923. }
  20924. } else {
  20925. // In case there is no payload, finish unsuccessfully.
  20926. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20927. success: false,
  20928. frag,
  20929. error: new Error('Empty subtitle payload')
  20930. });
  20931. }
  20932. }
  20933. }
  20934. _parseIMSC1(frag, payload) {
  20935. const hls = this.hls;
  20936. parseIMSC1(payload, this.initPTS[frag.cc], cues => {
  20937. this._appendCues(cues, frag.level);
  20938. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20939. success: true,
  20940. frag: frag
  20941. });
  20942. }, error => {
  20943. logger.log(`Failed to parse IMSC1: ${error}`);
  20944. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20945. success: false,
  20946. frag: frag,
  20947. error
  20948. });
  20949. });
  20950. }
  20951. _parseVTTs(data) {
  20952. var _frag$initSegment;
  20953. const {
  20954. frag,
  20955. payload
  20956. } = data;
  20957. // We need an initial synchronisation PTS. Store fragments as long as none has arrived
  20958. const {
  20959. initPTS,
  20960. unparsedVttFrags
  20961. } = this;
  20962. const maxAvCC = initPTS.length - 1;
  20963. if (!initPTS[frag.cc] && maxAvCC === -1) {
  20964. unparsedVttFrags.push(data);
  20965. return;
  20966. }
  20967. const hls = this.hls;
  20968. // Parse the WebVTT file contents.
  20969. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)) : payload;
  20970. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, cues => {
  20971. this._appendCues(cues, frag.level);
  20972. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20973. success: true,
  20974. frag: frag
  20975. });
  20976. }, error => {
  20977. const missingInitPTS = error.message === 'Missing initPTS for VTT MPEGTS';
  20978. if (missingInitPTS) {
  20979. unparsedVttFrags.push(data);
  20980. } else {
  20981. this._fallbackToIMSC1(frag, payload);
  20982. }
  20983. // Something went wrong while parsing. Trigger event with success false.
  20984. logger.log(`Failed to parse VTT cue: ${error}`);
  20985. if (missingInitPTS && maxAvCC > frag.cc) {
  20986. return;
  20987. }
  20988. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20989. success: false,
  20990. frag: frag,
  20991. error
  20992. });
  20993. });
  20994. }
  20995. _fallbackToIMSC1(frag, payload) {
  20996. // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
  20997. const trackPlaylistMedia = this.tracks[frag.level];
  20998. if (!trackPlaylistMedia.textCodec) {
  20999. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  21000. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  21001. this._parseIMSC1(frag, payload);
  21002. }, () => {
  21003. trackPlaylistMedia.textCodec = 'wvtt';
  21004. });
  21005. }
  21006. }
  21007. _appendCues(cues, fragLevel) {
  21008. const hls = this.hls;
  21009. if (this.config.renderTextTracksNatively) {
  21010. const textTrack = this.textTracks[fragLevel];
  21011. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  21012. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  21013. // and trying to access getCueById method of cues will throw an exception
  21014. // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
  21015. if (!textTrack || textTrack.mode === 'disabled') {
  21016. return;
  21017. }
  21018. cues.forEach(cue => addCueToTrack(textTrack, cue));
  21019. } else {
  21020. const currentTrack = this.tracks[fragLevel];
  21021. if (!currentTrack) {
  21022. return;
  21023. }
  21024. const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
  21025. hls.trigger(Events.CUES_PARSED, {
  21026. type: 'subtitles',
  21027. cues,
  21028. track
  21029. });
  21030. }
  21031. }
  21032. onFragDecrypted(event, data) {
  21033. const {
  21034. frag
  21035. } = data;
  21036. if (frag.type === PlaylistLevelType.SUBTITLE) {
  21037. this.onFragLoaded(Events.FRAG_LOADED, data);
  21038. }
  21039. }
  21040. onSubtitleTracksCleared() {
  21041. this.tracks = [];
  21042. this.captionsTracks = {};
  21043. }
  21044. onFragParsingUserdata(event, data) {
  21045. this.initCea608Parsers();
  21046. const {
  21047. cea608Parser1,
  21048. cea608Parser2
  21049. } = this;
  21050. if (!this.enabled || !cea608Parser1 || !cea608Parser2) {
  21051. return;
  21052. }
  21053. const {
  21054. frag,
  21055. samples
  21056. } = data;
  21057. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === 'NONE') {
  21058. return;
  21059. }
  21060. // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  21061. // It will create the proper timestamps based on the PTS value
  21062. for (let i = 0; i < samples.length; i++) {
  21063. const ccBytes = samples[i].bytes;
  21064. if (ccBytes) {
  21065. const ccdatas = this.extractCea608Data(ccBytes);
  21066. cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  21067. cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  21068. }
  21069. }
  21070. }
  21071. onBufferFlushing(event, {
  21072. startOffset,
  21073. endOffset,
  21074. endOffsetSubtitles,
  21075. type
  21076. }) {
  21077. const {
  21078. media
  21079. } = this;
  21080. if (!media || media.currentTime < endOffset) {
  21081. return;
  21082. }
  21083. // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
  21084. // Forward cues are never removed because we can loose streamed 608 content from recent fragments
  21085. if (!type || type === 'video') {
  21086. const {
  21087. captionsTracks
  21088. } = this;
  21089. Object.keys(captionsTracks).forEach(trackName => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  21090. }
  21091. if (this.config.renderTextTracksNatively) {
  21092. // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
  21093. if (startOffset === 0 && endOffsetSubtitles !== undefined) {
  21094. const {
  21095. textTracks
  21096. } = this;
  21097. Object.keys(textTracks).forEach(trackName => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  21098. }
  21099. }
  21100. }
  21101. extractCea608Data(byteArray) {
  21102. const actualCCBytes = [[], []];
  21103. const count = byteArray[0] & 0x1f;
  21104. let position = 2;
  21105. for (let j = 0; j < count; j++) {
  21106. const tmpByte = byteArray[position++];
  21107. const ccbyte1 = 0x7f & byteArray[position++];
  21108. const ccbyte2 = 0x7f & byteArray[position++];
  21109. if (ccbyte1 === 0 && ccbyte2 === 0) {
  21110. continue;
  21111. }
  21112. const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels
  21113. if (ccValid) {
  21114. const ccType = 0x03 & tmpByte;
  21115. if (0x00 /* CEA608 field1*/ === ccType || 0x01 /* CEA608 field2*/ === ccType) {
  21116. // Exclude CEA708 CC data.
  21117. actualCCBytes[ccType].push(ccbyte1);
  21118. actualCCBytes[ccType].push(ccbyte2);
  21119. }
  21120. }
  21121. }
  21122. return actualCCBytes;
  21123. }
  21124. }
  21125. function captionsOrSubtitlesFromCharacteristics(track) {
  21126. if (track.characteristics) {
  21127. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  21128. return 'captions';
  21129. }
  21130. }
  21131. return 'subtitles';
  21132. }
  21133. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  21134. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  21135. }
  21136. function intersection(x1, x2, y1, y2) {
  21137. return Math.min(x2, y2) - Math.max(x1, y1);
  21138. }
  21139. function newVTTCCs() {
  21140. return {
  21141. ccOffset: 0,
  21142. presentationOffset: 0,
  21143. 0: {
  21144. start: 0,
  21145. prevCC: -1,
  21146. new: true
  21147. }
  21148. };
  21149. }
  21150. class CapLevelController {
  21151. constructor(hls) {
  21152. this.hls = void 0;
  21153. this.autoLevelCapping = void 0;
  21154. this.firstLevel = void 0;
  21155. this.media = void 0;
  21156. this.restrictedLevels = void 0;
  21157. this.timer = void 0;
  21158. this.clientRect = void 0;
  21159. this.streamController = void 0;
  21160. this.hls = hls;
  21161. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21162. this.firstLevel = -1;
  21163. this.media = null;
  21164. this.restrictedLevels = [];
  21165. this.timer = undefined;
  21166. this.clientRect = null;
  21167. this.registerListeners();
  21168. }
  21169. setStreamController(streamController) {
  21170. this.streamController = streamController;
  21171. }
  21172. destroy() {
  21173. if (this.hls) {
  21174. this.unregisterListener();
  21175. }
  21176. if (this.timer) {
  21177. this.stopCapping();
  21178. }
  21179. this.media = null;
  21180. this.clientRect = null;
  21181. // @ts-ignore
  21182. this.hls = this.streamController = null;
  21183. }
  21184. registerListeners() {
  21185. const {
  21186. hls
  21187. } = this;
  21188. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  21189. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21190. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21191. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21192. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21193. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21194. }
  21195. unregisterListener() {
  21196. const {
  21197. hls
  21198. } = this;
  21199. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  21200. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21201. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21202. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21203. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21204. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21205. }
  21206. onFpsDropLevelCapping(event, data) {
  21207. // Don't add a restricted level more than once
  21208. const level = this.hls.levels[data.droppedLevel];
  21209. if (this.isLevelAllowed(level)) {
  21210. this.restrictedLevels.push({
  21211. bitrate: level.bitrate,
  21212. height: level.height,
  21213. width: level.width
  21214. });
  21215. }
  21216. }
  21217. onMediaAttaching(event, data) {
  21218. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  21219. this.clientRect = null;
  21220. if (this.timer && this.hls.levels.length) {
  21221. this.detectPlayerSize();
  21222. }
  21223. }
  21224. onManifestParsed(event, data) {
  21225. const hls = this.hls;
  21226. this.restrictedLevels = [];
  21227. this.firstLevel = data.firstLevel;
  21228. if (hls.config.capLevelToPlayerSize && data.video) {
  21229. // Start capping immediately if the manifest has signaled video codecs
  21230. this.startCapping();
  21231. }
  21232. }
  21233. onLevelsUpdated(event, data) {
  21234. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  21235. this.detectPlayerSize();
  21236. }
  21237. }
  21238. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  21239. // to the first level
  21240. onBufferCodecs(event, data) {
  21241. const hls = this.hls;
  21242. if (hls.config.capLevelToPlayerSize && data.video) {
  21243. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  21244. this.startCapping();
  21245. }
  21246. }
  21247. onMediaDetaching() {
  21248. this.stopCapping();
  21249. }
  21250. detectPlayerSize() {
  21251. if (this.media) {
  21252. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  21253. this.clientRect = null;
  21254. return;
  21255. }
  21256. const levels = this.hls.levels;
  21257. if (levels.length) {
  21258. const hls = this.hls;
  21259. const maxLevel = this.getMaxLevel(levels.length - 1);
  21260. if (maxLevel !== this.autoLevelCapping) {
  21261. logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  21262. }
  21263. hls.autoLevelCapping = maxLevel;
  21264. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  21265. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  21266. // usually happen when the user go to the fullscreen mode.
  21267. this.streamController.nextLevelSwitch();
  21268. }
  21269. this.autoLevelCapping = hls.autoLevelCapping;
  21270. }
  21271. }
  21272. }
  21273. /*
  21274. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  21275. */
  21276. getMaxLevel(capLevelIndex) {
  21277. const levels = this.hls.levels;
  21278. if (!levels.length) {
  21279. return -1;
  21280. }
  21281. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  21282. this.clientRect = null;
  21283. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  21284. }
  21285. startCapping() {
  21286. if (this.timer) {
  21287. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  21288. return;
  21289. }
  21290. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21291. self.clearInterval(this.timer);
  21292. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  21293. this.detectPlayerSize();
  21294. }
  21295. stopCapping() {
  21296. this.restrictedLevels = [];
  21297. this.firstLevel = -1;
  21298. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21299. if (this.timer) {
  21300. self.clearInterval(this.timer);
  21301. this.timer = undefined;
  21302. }
  21303. }
  21304. getDimensions() {
  21305. if (this.clientRect) {
  21306. return this.clientRect;
  21307. }
  21308. const media = this.media;
  21309. const boundsRect = {
  21310. width: 0,
  21311. height: 0
  21312. };
  21313. if (media) {
  21314. const clientRect = media.getBoundingClientRect();
  21315. boundsRect.width = clientRect.width;
  21316. boundsRect.height = clientRect.height;
  21317. if (!boundsRect.width && !boundsRect.height) {
  21318. // When the media element has no width or height (equivalent to not being in the DOM),
  21319. // then use its width and height attributes (media.width, media.height)
  21320. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  21321. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  21322. }
  21323. }
  21324. this.clientRect = boundsRect;
  21325. return boundsRect;
  21326. }
  21327. get mediaWidth() {
  21328. return this.getDimensions().width * this.contentScaleFactor;
  21329. }
  21330. get mediaHeight() {
  21331. return this.getDimensions().height * this.contentScaleFactor;
  21332. }
  21333. get contentScaleFactor() {
  21334. let pixelRatio = 1;
  21335. if (!this.hls.config.ignoreDevicePixelRatio) {
  21336. try {
  21337. pixelRatio = self.devicePixelRatio;
  21338. } catch (e) {
  21339. /* no-op */
  21340. }
  21341. }
  21342. return pixelRatio;
  21343. }
  21344. isLevelAllowed(level) {
  21345. const restrictedLevels = this.restrictedLevels;
  21346. return !restrictedLevels.some(restrictedLevel => {
  21347. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  21348. });
  21349. }
  21350. static getMaxLevelByMediaSize(levels, width, height) {
  21351. if (!(levels != null && levels.length)) {
  21352. return -1;
  21353. }
  21354. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  21355. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  21356. const atGreatestBandwidth = (curLevel, nextLevel) => {
  21357. if (!nextLevel) {
  21358. return true;
  21359. }
  21360. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  21361. };
  21362. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  21363. // the max level
  21364. let maxLevelIndex = levels.length - 1;
  21365. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  21366. const squareSize = Math.max(width, height);
  21367. for (let i = 0; i < levels.length; i += 1) {
  21368. const level = levels[i];
  21369. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  21370. maxLevelIndex = i;
  21371. break;
  21372. }
  21373. }
  21374. return maxLevelIndex;
  21375. }
  21376. }
  21377. class FPSController {
  21378. constructor(hls) {
  21379. this.hls = void 0;
  21380. this.isVideoPlaybackQualityAvailable = false;
  21381. this.timer = void 0;
  21382. this.media = null;
  21383. this.lastTime = void 0;
  21384. this.lastDroppedFrames = 0;
  21385. this.lastDecodedFrames = 0;
  21386. // stream controller must be provided as a dependency!
  21387. this.streamController = void 0;
  21388. this.hls = hls;
  21389. this.registerListeners();
  21390. }
  21391. setStreamController(streamController) {
  21392. this.streamController = streamController;
  21393. }
  21394. registerListeners() {
  21395. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21396. }
  21397. unregisterListeners() {
  21398. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21399. }
  21400. destroy() {
  21401. if (this.timer) {
  21402. clearInterval(this.timer);
  21403. }
  21404. this.unregisterListeners();
  21405. this.isVideoPlaybackQualityAvailable = false;
  21406. this.media = null;
  21407. }
  21408. onMediaAttaching(event, data) {
  21409. const config = this.hls.config;
  21410. if (config.capLevelOnFPSDrop) {
  21411. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  21412. this.media = media;
  21413. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  21414. this.isVideoPlaybackQualityAvailable = true;
  21415. }
  21416. self.clearInterval(this.timer);
  21417. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  21418. }
  21419. }
  21420. checkFPS(video, decodedFrames, droppedFrames) {
  21421. const currentTime = performance.now();
  21422. if (decodedFrames) {
  21423. if (this.lastTime) {
  21424. const currentPeriod = currentTime - this.lastTime;
  21425. const currentDropped = droppedFrames - this.lastDroppedFrames;
  21426. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  21427. const droppedFPS = 1000 * currentDropped / currentPeriod;
  21428. const hls = this.hls;
  21429. hls.trigger(Events.FPS_DROP, {
  21430. currentDropped: currentDropped,
  21431. currentDecoded: currentDecoded,
  21432. totalDroppedFrames: droppedFrames
  21433. });
  21434. if (droppedFPS > 0) {
  21435. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  21436. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  21437. let currentLevel = hls.currentLevel;
  21438. logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  21439. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  21440. currentLevel = currentLevel - 1;
  21441. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  21442. level: currentLevel,
  21443. droppedLevel: hls.currentLevel
  21444. });
  21445. hls.autoLevelCapping = currentLevel;
  21446. this.streamController.nextLevelSwitch();
  21447. }
  21448. }
  21449. }
  21450. }
  21451. this.lastTime = currentTime;
  21452. this.lastDroppedFrames = droppedFrames;
  21453. this.lastDecodedFrames = decodedFrames;
  21454. }
  21455. }
  21456. checkFPSInterval() {
  21457. const video = this.media;
  21458. if (video) {
  21459. if (this.isVideoPlaybackQualityAvailable) {
  21460. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  21461. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  21462. } else {
  21463. // HTMLVideoElement doesn't include the webkit types
  21464. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  21465. }
  21466. }
  21467. }
  21468. }
  21469. const LOGGER_PREFIX = '[eme]';
  21470. /**
  21471. * Controller to deal with encrypted media extensions (EME)
  21472. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  21473. *
  21474. * @class
  21475. * @constructor
  21476. */
  21477. class EMEController {
  21478. constructor(hls) {
  21479. this.hls = void 0;
  21480. this.config = void 0;
  21481. this.media = null;
  21482. this.keyFormatPromise = null;
  21483. this.keySystemAccessPromises = {};
  21484. this._requestLicenseFailureCount = 0;
  21485. this.mediaKeySessions = [];
  21486. this.keyIdToKeySessionPromise = {};
  21487. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  21488. this.onMediaEncrypted = this._onMediaEncrypted.bind(this);
  21489. this.onWaitingForKey = this._onWaitingForKey.bind(this);
  21490. this.debug = logger.debug.bind(logger, LOGGER_PREFIX);
  21491. this.log = logger.log.bind(logger, LOGGER_PREFIX);
  21492. this.warn = logger.warn.bind(logger, LOGGER_PREFIX);
  21493. this.error = logger.error.bind(logger, LOGGER_PREFIX);
  21494. this.hls = hls;
  21495. this.config = hls.config;
  21496. this.registerListeners();
  21497. }
  21498. destroy() {
  21499. this.unregisterListeners();
  21500. this.onMediaDetached();
  21501. // Remove any references that could be held in config options or callbacks
  21502. const config = this.config;
  21503. config.requestMediaKeySystemAccessFunc = null;
  21504. config.licenseXhrSetup = config.licenseResponseCallback = undefined;
  21505. config.drmSystems = config.drmSystemOptions = {};
  21506. // @ts-ignore
  21507. this.hls = this.onMediaEncrypted = this.onWaitingForKey = this.keyIdToKeySessionPromise = null;
  21508. // @ts-ignore
  21509. this.config = null;
  21510. }
  21511. registerListeners() {
  21512. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21513. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21514. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21515. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21516. }
  21517. unregisterListeners() {
  21518. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21519. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21520. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21521. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21522. }
  21523. getLicenseServerUrl(keySystem) {
  21524. const {
  21525. drmSystems,
  21526. widevineLicenseUrl
  21527. } = this.config;
  21528. const keySystemConfiguration = drmSystems[keySystem];
  21529. if (keySystemConfiguration) {
  21530. return keySystemConfiguration.licenseUrl;
  21531. }
  21532. // For backward compatibility
  21533. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  21534. return widevineLicenseUrl;
  21535. }
  21536. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  21537. }
  21538. getServerCertificateUrl(keySystem) {
  21539. const {
  21540. drmSystems
  21541. } = this.config;
  21542. const keySystemConfiguration = drmSystems[keySystem];
  21543. if (keySystemConfiguration) {
  21544. return keySystemConfiguration.serverCertificateUrl;
  21545. } else {
  21546. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  21547. }
  21548. }
  21549. attemptKeySystemAccess(keySystemsToAttempt) {
  21550. const levels = this.hls.levels;
  21551. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  21552. const audioCodecs = levels.map(level => level.audioCodec).filter(uniqueCodec);
  21553. const videoCodecs = levels.map(level => level.videoCodec).filter(uniqueCodec);
  21554. if (audioCodecs.length + videoCodecs.length === 0) {
  21555. videoCodecs.push('avc1.42e01e');
  21556. }
  21557. return new Promise((resolve, reject) => {
  21558. const attempt = keySystems => {
  21559. const keySystem = keySystems.shift();
  21560. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then(mediaKeys => resolve({
  21561. keySystem,
  21562. mediaKeys
  21563. })).catch(error => {
  21564. if (keySystems.length) {
  21565. attempt(keySystems);
  21566. } else if (error instanceof EMEKeyError) {
  21567. reject(error);
  21568. } else {
  21569. reject(new EMEKeyError({
  21570. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21571. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  21572. error,
  21573. fatal: true
  21574. }, error.message));
  21575. }
  21576. });
  21577. };
  21578. attempt(keySystemsToAttempt);
  21579. });
  21580. }
  21581. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  21582. const {
  21583. requestMediaKeySystemAccessFunc
  21584. } = this.config;
  21585. if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {
  21586. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  21587. if (requestMediaKeySystemAccess === null && self.location.protocol === 'http:') {
  21588. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  21589. }
  21590. return Promise.reject(new Error(errMessage));
  21591. }
  21592. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  21593. }
  21594. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  21595. // This can throw, but is caught in event handler callpath
  21596. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  21597. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  21598. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  21599. if (!keySystemAccess) {
  21600. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${JSON.stringify(mediaKeySystemConfigs)}`);
  21601. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  21602. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  21603. keySystemAccess
  21604. };
  21605. keySystemAccess.catch(error => {
  21606. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  21607. });
  21608. return keySystemAccess.then(mediaKeySystemAccess => {
  21609. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  21610. const certificateRequest = this.fetchServerCertificate(keySystem);
  21611. this.log(`Create media-keys for "${keySystem}"`);
  21612. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then(mediaKeys => {
  21613. this.log(`Media-keys created for "${keySystem}"`);
  21614. return certificateRequest.then(certificate => {
  21615. if (certificate) {
  21616. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  21617. }
  21618. return mediaKeys;
  21619. });
  21620. });
  21621. _keySystemAccessPromises.mediaKeys.catch(error => {
  21622. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  21623. });
  21624. return _keySystemAccessPromises.mediaKeys;
  21625. });
  21626. }
  21627. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  21628. }
  21629. createMediaKeySessionContext({
  21630. decryptdata,
  21631. keySystem,
  21632. mediaKeys
  21633. }) {
  21634. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  21635. const mediaKeysSession = mediaKeys.createSession();
  21636. const mediaKeySessionContext = {
  21637. decryptdata,
  21638. keySystem,
  21639. mediaKeys,
  21640. mediaKeysSession,
  21641. keyStatus: 'status-pending'
  21642. };
  21643. this.mediaKeySessions.push(mediaKeySessionContext);
  21644. return mediaKeySessionContext;
  21645. }
  21646. renewKeySession(mediaKeySessionContext) {
  21647. const decryptdata = mediaKeySessionContext.decryptdata;
  21648. if (decryptdata.pssh) {
  21649. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  21650. const keyId = this.getKeyIdString(decryptdata);
  21651. const scheme = 'cenc';
  21652. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, 'expired');
  21653. } else {
  21654. this.warn(`Could not renew expired session. Missing pssh initData.`);
  21655. }
  21656. this.removeSession(mediaKeySessionContext);
  21657. }
  21658. getKeyIdString(decryptdata) {
  21659. if (!decryptdata) {
  21660. throw new Error('Could not read keyId of undefined decryptdata');
  21661. }
  21662. if (decryptdata.keyId === null) {
  21663. throw new Error('keyId is null');
  21664. }
  21665. return Hex.hexDump(decryptdata.keyId);
  21666. }
  21667. updateKeySession(mediaKeySessionContext, data) {
  21668. var _mediaKeySessionConte;
  21669. const keySession = mediaKeySessionContext.mediaKeysSession;
  21670. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  21671. } (data length: ${data ? data.byteLength : data})`);
  21672. return keySession.update(data);
  21673. }
  21674. selectKeySystemFormat(frag) {
  21675. const keyFormats = Object.keys(frag.levelkeys || {});
  21676. if (!this.keyFormatPromise) {
  21677. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(', ')}`);
  21678. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  21679. }
  21680. return this.keyFormatPromise;
  21681. }
  21682. getKeyFormatPromise(keyFormats) {
  21683. return new Promise((resolve, reject) => {
  21684. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  21685. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter(value => !!value && keySystemsInConfig.indexOf(value) !== -1);
  21686. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  21687. keySystem
  21688. }) => {
  21689. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  21690. if (keySystemFormat) {
  21691. resolve(keySystemFormat);
  21692. } else {
  21693. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  21694. }
  21695. }).catch(reject);
  21696. });
  21697. }
  21698. loadKey(data) {
  21699. const decryptdata = data.keyInfo.decryptdata;
  21700. const keyId = this.getKeyIdString(decryptdata);
  21701. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  21702. this.log(`Starting session for key ${keyDetails}`);
  21703. let keySessionContextPromise = this.keyIdToKeySessionPromise[keyId];
  21704. if (!keySessionContextPromise) {
  21705. keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = this.getKeySystemForKeyPromise(decryptdata).then(({
  21706. keySystem,
  21707. mediaKeys
  21708. }) => {
  21709. this.throwIfDestroyed();
  21710. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  21711. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  21712. this.throwIfDestroyed();
  21713. const keySessionContext = this.createMediaKeySessionContext({
  21714. keySystem,
  21715. mediaKeys,
  21716. decryptdata
  21717. });
  21718. const scheme = 'cenc';
  21719. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, 'playlist-key');
  21720. });
  21721. });
  21722. keySessionContextPromise.catch(error => this.handleError(error));
  21723. }
  21724. return keySessionContextPromise;
  21725. }
  21726. throwIfDestroyed(message = 'Invalid state') {
  21727. if (!this.hls) {
  21728. throw new Error('invalid state');
  21729. }
  21730. }
  21731. handleError(error) {
  21732. if (!this.hls) {
  21733. return;
  21734. }
  21735. this.error(error.message);
  21736. if (error instanceof EMEKeyError) {
  21737. this.hls.trigger(Events.ERROR, error.data);
  21738. } else {
  21739. this.hls.trigger(Events.ERROR, {
  21740. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21741. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  21742. error,
  21743. fatal: true
  21744. });
  21745. }
  21746. }
  21747. getKeySystemForKeyPromise(decryptdata) {
  21748. const keyId = this.getKeyIdString(decryptdata);
  21749. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  21750. if (!mediaKeySessionContext) {
  21751. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  21752. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  21753. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21754. }
  21755. return mediaKeySessionContext;
  21756. }
  21757. getKeySystemSelectionPromise(keySystemsToAttempt) {
  21758. if (!keySystemsToAttempt.length) {
  21759. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  21760. }
  21761. if (keySystemsToAttempt.length === 0) {
  21762. throw new EMEKeyError({
  21763. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21764. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  21765. fatal: true
  21766. }, `Missing key-system license configuration options ${JSON.stringify({
  21767. drmSystems: this.config.drmSystems
  21768. })}`);
  21769. }
  21770. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21771. }
  21772. _onMediaEncrypted(event) {
  21773. const {
  21774. initDataType,
  21775. initData
  21776. } = event;
  21777. const logMessage = `"${event.type}" event: init data type: "${initDataType}"`;
  21778. this.debug(logMessage);
  21779. // Ignore event when initData is null
  21780. if (initData === null) {
  21781. return;
  21782. }
  21783. let keyId;
  21784. let keySystemDomain;
  21785. if (initDataType === 'sinf' && this.config.drmSystems[KeySystems.FAIRPLAY]) {
  21786. // Match sinf keyId to playlist skd://keyId=
  21787. const json = bin2str(new Uint8Array(initData));
  21788. try {
  21789. const sinf = base64Decode(JSON.parse(json).sinf);
  21790. const tenc = parseSinf(new Uint8Array(sinf));
  21791. if (!tenc) {
  21792. throw new Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);
  21793. }
  21794. keyId = tenc.subarray(8, 24);
  21795. keySystemDomain = KeySystems.FAIRPLAY;
  21796. } catch (error) {
  21797. this.warn(`${logMessage} Failed to parse sinf: ${error}`);
  21798. return;
  21799. }
  21800. } else {
  21801. // Support Widevine clear-lead key-session creation (otherwise depend on playlist keys)
  21802. const psshResults = parseMultiPssh(initData);
  21803. const psshInfo = psshResults.filter(pssh => pssh.systemId === KeySystemIds.WIDEVINE)[0];
  21804. if (!psshInfo) {
  21805. if (psshResults.length === 0 || psshResults.some(pssh => !pssh.systemId)) {
  21806. this.warn(`${logMessage} contains incomplete or invalid pssh data`);
  21807. } else {
  21808. this.log(`ignoring ${logMessage} for ${psshResults.map(pssh => keySystemIdToKeySystemDomain(pssh.systemId)).join(',')} pssh data in favor of playlist keys`);
  21809. }
  21810. return;
  21811. }
  21812. keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId);
  21813. if (psshInfo.version === 0 && psshInfo.data) {
  21814. const offset = psshInfo.data.length - 22;
  21815. keyId = psshInfo.data.subarray(offset, offset + 16);
  21816. }
  21817. }
  21818. if (!keySystemDomain || !keyId) {
  21819. return;
  21820. }
  21821. const keyIdHex = Hex.hexDump(keyId);
  21822. const {
  21823. keyIdToKeySessionPromise,
  21824. mediaKeySessions
  21825. } = this;
  21826. let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];
  21827. for (let i = 0; i < mediaKeySessions.length; i++) {
  21828. // Match playlist key
  21829. const keyContext = mediaKeySessions[i];
  21830. const decryptdata = keyContext.decryptdata;
  21831. if (!decryptdata.keyId) {
  21832. continue;
  21833. }
  21834. const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);
  21835. if (keyIdHex === oldKeyIdHex || decryptdata.uri.replace(/-/g, '').indexOf(keyIdHex) !== -1) {
  21836. keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];
  21837. if (decryptdata.pssh) {
  21838. break;
  21839. }
  21840. delete keyIdToKeySessionPromise[oldKeyIdHex];
  21841. decryptdata.pssh = new Uint8Array(initData);
  21842. decryptdata.keyId = keyId;
  21843. keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => {
  21844. return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, 'encrypted-event-key-match');
  21845. });
  21846. break;
  21847. }
  21848. }
  21849. if (!keySessionContextPromise) {
  21850. // Clear-lead key (not encountered in playlist)
  21851. keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = this.getKeySystemSelectionPromise([keySystemDomain]).then(({
  21852. keySystem,
  21853. mediaKeys
  21854. }) => {
  21855. var _keySystemToKeySystem;
  21856. this.throwIfDestroyed();
  21857. const decryptdata = new LevelKey('ISO-23001-7', keyIdHex, (_keySystemToKeySystem = keySystemDomainToKeySystemFormat(keySystem)) != null ? _keySystemToKeySystem : '');
  21858. decryptdata.pssh = new Uint8Array(initData);
  21859. decryptdata.keyId = keyId;
  21860. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  21861. this.throwIfDestroyed();
  21862. const keySessionContext = this.createMediaKeySessionContext({
  21863. decryptdata,
  21864. keySystem,
  21865. mediaKeys
  21866. });
  21867. return this.generateRequestWithPreferredKeySession(keySessionContext, initDataType, initData, 'encrypted-event-no-match');
  21868. });
  21869. });
  21870. }
  21871. keySessionContextPromise.catch(error => this.handleError(error));
  21872. }
  21873. _onWaitingForKey(event) {
  21874. this.log(`"${event.type}" event`);
  21875. }
  21876. attemptSetMediaKeys(keySystem, mediaKeys) {
  21877. const queue = this.setMediaKeysQueue.slice();
  21878. this.log(`Setting media-keys for "${keySystem}"`);
  21879. // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations
  21880. // can be queued for execution for multiple key sessions.
  21881. const setMediaKeysPromise = Promise.all(queue).then(() => {
  21882. if (!this.media) {
  21883. throw new Error('Attempted to set mediaKeys without media element attached');
  21884. }
  21885. return this.media.setMediaKeys(mediaKeys);
  21886. });
  21887. this.setMediaKeysQueue.push(setMediaKeysPromise);
  21888. return setMediaKeysPromise.then(() => {
  21889. this.log(`Media-keys set for "${keySystem}"`);
  21890. queue.push(setMediaKeysPromise);
  21891. this.setMediaKeysQueue = this.setMediaKeysQueue.filter(p => queue.indexOf(p) === -1);
  21892. });
  21893. }
  21894. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  21895. var _this$config$drmSyste, _this$config$drmSyste2;
  21896. 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;
  21897. if (generateRequestFilter) {
  21898. try {
  21899. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  21900. if (!mappedInitData) {
  21901. throw new Error('Invalid response from configured generateRequest filter');
  21902. }
  21903. initDataType = mappedInitData.initDataType;
  21904. initData = context.decryptdata.pssh = mappedInitData.initData ? new Uint8Array(mappedInitData.initData) : null;
  21905. } catch (error) {
  21906. var _this$hls;
  21907. this.warn(error.message);
  21908. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  21909. throw error;
  21910. }
  21911. }
  21912. }
  21913. if (initData === null) {
  21914. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  21915. return Promise.resolve(context);
  21916. }
  21917. const keyId = this.getKeyIdString(context.decryptdata);
  21918. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  21919. const licenseStatus = new EventEmitter();
  21920. const onmessage = context._onmessage = event => {
  21921. const keySession = context.mediaKeysSession;
  21922. if (!keySession) {
  21923. licenseStatus.emit('error', new Error('invalid state'));
  21924. return;
  21925. }
  21926. const {
  21927. messageType,
  21928. message
  21929. } = event;
  21930. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  21931. if (messageType === 'license-request' || messageType === 'license-renewal') {
  21932. this.renewLicense(context, message).catch(error => {
  21933. this.handleError(error);
  21934. licenseStatus.emit('error', error);
  21935. });
  21936. } else if (messageType === 'license-release') {
  21937. if (context.keySystem === KeySystems.FAIRPLAY) {
  21938. this.updateKeySession(context, strToUtf8array('acknowledged'));
  21939. this.removeSession(context);
  21940. }
  21941. } else {
  21942. this.warn(`unhandled media key message type "${messageType}"`);
  21943. }
  21944. };
  21945. const onkeystatuseschange = context._onkeystatuseschange = event => {
  21946. const keySession = context.mediaKeysSession;
  21947. if (!keySession) {
  21948. licenseStatus.emit('error', new Error('invalid state'));
  21949. return;
  21950. }
  21951. this.onKeyStatusChange(context);
  21952. const keyStatus = context.keyStatus;
  21953. licenseStatus.emit('keyStatus', keyStatus);
  21954. if (keyStatus === 'expired') {
  21955. this.warn(`${context.keySystem} expired for key ${keyId}`);
  21956. this.renewKeySession(context);
  21957. }
  21958. };
  21959. context.mediaKeysSession.addEventListener('message', onmessage);
  21960. context.mediaKeysSession.addEventListener('keystatuseschange', onkeystatuseschange);
  21961. const keyUsablePromise = new Promise((resolve, reject) => {
  21962. licenseStatus.on('error', reject);
  21963. licenseStatus.on('keyStatus', keyStatus => {
  21964. if (keyStatus.startsWith('usable')) {
  21965. resolve();
  21966. } else if (keyStatus === 'output-restricted') {
  21967. reject(new EMEKeyError({
  21968. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21969. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  21970. fatal: false
  21971. }, 'HDCP level output restricted'));
  21972. } else if (keyStatus === 'internal-error') {
  21973. reject(new EMEKeyError({
  21974. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21975. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  21976. fatal: true
  21977. }, `key status changed to "${keyStatus}"`));
  21978. } else if (keyStatus === 'expired') {
  21979. reject(new Error('key expired while generating request'));
  21980. } else {
  21981. this.warn(`unhandled key status change "${keyStatus}"`);
  21982. }
  21983. });
  21984. });
  21985. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  21986. var _context$mediaKeysSes;
  21987. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  21988. }).catch(error => {
  21989. throw new EMEKeyError({
  21990. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21991. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  21992. error,
  21993. fatal: false
  21994. }, `Error generating key-session request: ${error}`);
  21995. }).then(() => keyUsablePromise).catch(error => {
  21996. licenseStatus.removeAllListeners();
  21997. this.removeSession(context);
  21998. throw error;
  21999. }).then(() => {
  22000. licenseStatus.removeAllListeners();
  22001. return context;
  22002. });
  22003. }
  22004. onKeyStatusChange(mediaKeySessionContext) {
  22005. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status, keyId) => {
  22006. 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}`);
  22007. mediaKeySessionContext.keyStatus = status;
  22008. });
  22009. }
  22010. fetchServerCertificate(keySystem) {
  22011. const config = this.config;
  22012. const Loader = config.loader;
  22013. const certLoader = new Loader(config);
  22014. const url = this.getServerCertificateUrl(keySystem);
  22015. if (!url) {
  22016. return Promise.resolve();
  22017. }
  22018. this.log(`Fetching server certificate for "${keySystem}"`);
  22019. return new Promise((resolve, reject) => {
  22020. const loaderContext = {
  22021. responseType: 'arraybuffer',
  22022. url
  22023. };
  22024. const loadPolicy = config.certLoadPolicy.default;
  22025. const loaderConfig = {
  22026. loadPolicy,
  22027. timeout: loadPolicy.maxLoadTimeMs,
  22028. maxRetry: 0,
  22029. retryDelay: 0,
  22030. maxRetryDelay: 0
  22031. };
  22032. const loaderCallbacks = {
  22033. onSuccess: (response, stats, context, networkDetails) => {
  22034. resolve(response.data);
  22035. },
  22036. onError: (response, contex, networkDetails, stats) => {
  22037. reject(new EMEKeyError({
  22038. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22039. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  22040. fatal: true,
  22041. networkDetails,
  22042. response: _objectSpread2({
  22043. url: loaderContext.url,
  22044. data: undefined
  22045. }, response)
  22046. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  22047. },
  22048. onTimeout: (stats, context, networkDetails) => {
  22049. reject(new EMEKeyError({
  22050. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22051. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  22052. fatal: true,
  22053. networkDetails,
  22054. response: {
  22055. url: loaderContext.url,
  22056. data: undefined
  22057. }
  22058. }, `"${keySystem}" certificate request timed out (${url})`));
  22059. },
  22060. onAbort: (stats, context, networkDetails) => {
  22061. reject(new Error('aborted'));
  22062. }
  22063. };
  22064. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  22065. });
  22066. }
  22067. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  22068. return new Promise((resolve, reject) => {
  22069. mediaKeys.setServerCertificate(cert).then(success => {
  22070. this.log(`setServerCertificate ${success ? 'success' : 'not supported by CDM'} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  22071. resolve(mediaKeys);
  22072. }).catch(error => {
  22073. reject(new EMEKeyError({
  22074. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22075. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  22076. error,
  22077. fatal: true
  22078. }, error.message));
  22079. });
  22080. });
  22081. }
  22082. renewLicense(context, keyMessage) {
  22083. return this.requestLicense(context, new Uint8Array(keyMessage)).then(data => {
  22084. return this.updateKeySession(context, new Uint8Array(data)).catch(error => {
  22085. throw new EMEKeyError({
  22086. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22087. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  22088. error,
  22089. fatal: true
  22090. }, error.message);
  22091. });
  22092. });
  22093. }
  22094. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  22095. // On Edge, the raw license message is UTF-16-encoded XML. We need
  22096. // to unpack the Challenge element (base64-encoded string containing the
  22097. // actual license request) and any HttpHeader elements (sent as request
  22098. // headers).
  22099. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  22100. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  22101. if (!xmlString.includes('PlayReadyKeyMessage')) {
  22102. // This does not appear to be a wrapped message as on Edge. Some
  22103. // clients do not need this unwrapping, so we will assume this is one of
  22104. // them. Note that "xml" at this point probably looks like random
  22105. // garbage, since we interpreted UTF-8 as UTF-16.
  22106. xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
  22107. return licenseChallenge;
  22108. }
  22109. const keyMessageXml = new DOMParser().parseFromString(xmlString, 'application/xml');
  22110. // Set request headers.
  22111. const headers = keyMessageXml.querySelectorAll('HttpHeader');
  22112. if (headers.length > 0) {
  22113. let header;
  22114. for (let i = 0, len = headers.length; i < len; i++) {
  22115. var _header$querySelector, _header$querySelector2;
  22116. header = headers[i];
  22117. const name = (_header$querySelector = header.querySelector('name')) == null ? void 0 : _header$querySelector.textContent;
  22118. const value = (_header$querySelector2 = header.querySelector('value')) == null ? void 0 : _header$querySelector2.textContent;
  22119. if (name && value) {
  22120. xhr.setRequestHeader(name, value);
  22121. }
  22122. }
  22123. }
  22124. const challengeElement = keyMessageXml.querySelector('Challenge');
  22125. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  22126. if (!challengeText) {
  22127. throw new Error(`Cannot find <Challenge> in key message`);
  22128. }
  22129. return strToUtf8array(atob(challengeText));
  22130. }
  22131. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  22132. const licenseXhrSetup = this.config.licenseXhrSetup;
  22133. if (!licenseXhrSetup) {
  22134. xhr.open('POST', url, true);
  22135. return Promise.resolve({
  22136. xhr,
  22137. licenseChallenge
  22138. });
  22139. }
  22140. return Promise.resolve().then(() => {
  22141. if (!keysListItem.decryptdata) {
  22142. throw new Error('Key removed');
  22143. }
  22144. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  22145. }).catch(error => {
  22146. if (!keysListItem.decryptdata) {
  22147. // Key session removed. Cancel license request.
  22148. throw error;
  22149. }
  22150. // let's try to open before running setup
  22151. xhr.open('POST', url, true);
  22152. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  22153. }).then(licenseXhrSetupResult => {
  22154. // if licenseXhrSetup did not yet call open, let's do it now
  22155. if (!xhr.readyState) {
  22156. xhr.open('POST', url, true);
  22157. }
  22158. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  22159. return {
  22160. xhr,
  22161. licenseChallenge: finalLicenseChallenge
  22162. };
  22163. });
  22164. }
  22165. requestLicense(keySessionContext, licenseChallenge) {
  22166. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  22167. return new Promise((resolve, reject) => {
  22168. const url = this.getLicenseServerUrl(keySessionContext.keySystem);
  22169. this.log(`Sending license request to URL: ${url}`);
  22170. const xhr = new XMLHttpRequest();
  22171. xhr.responseType = 'arraybuffer';
  22172. xhr.onreadystatechange = () => {
  22173. if (!this.hls || !keySessionContext.mediaKeysSession) {
  22174. return reject(new Error('invalid state'));
  22175. }
  22176. if (xhr.readyState === 4) {
  22177. if (xhr.status === 200) {
  22178. this._requestLicenseFailureCount = 0;
  22179. let data = xhr.response;
  22180. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  22181. const licenseResponseCallback = this.config.licenseResponseCallback;
  22182. if (licenseResponseCallback) {
  22183. try {
  22184. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  22185. } catch (error) {
  22186. this.error(error);
  22187. }
  22188. }
  22189. resolve(data);
  22190. } else {
  22191. const retryConfig = keyLoadPolicy.errorRetry;
  22192. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  22193. this._requestLicenseFailureCount++;
  22194. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  22195. reject(new EMEKeyError({
  22196. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22197. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  22198. fatal: true,
  22199. networkDetails: xhr,
  22200. response: {
  22201. url,
  22202. data: undefined,
  22203. code: xhr.status,
  22204. text: xhr.statusText
  22205. }
  22206. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  22207. } else {
  22208. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  22209. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  22210. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  22211. }
  22212. }
  22213. }
  22214. };
  22215. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22216. keySessionContext.licenseXhr.abort();
  22217. }
  22218. keySessionContext.licenseXhr = xhr;
  22219. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  22220. xhr,
  22221. licenseChallenge
  22222. }) => {
  22223. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  22224. licenseChallenge = this.unpackPlayReadyKeyMessage(xhr, licenseChallenge);
  22225. }
  22226. xhr.send(licenseChallenge);
  22227. });
  22228. });
  22229. }
  22230. onMediaAttached(event, data) {
  22231. if (!this.config.emeEnabled) {
  22232. return;
  22233. }
  22234. const media = data.media;
  22235. // keep reference of media
  22236. this.media = media;
  22237. media.addEventListener('encrypted', this.onMediaEncrypted);
  22238. media.addEventListener('waitingforkey', this.onWaitingForKey);
  22239. }
  22240. onMediaDetached() {
  22241. const media = this.media;
  22242. const mediaKeysList = this.mediaKeySessions;
  22243. if (media) {
  22244. media.removeEventListener('encrypted', this.onMediaEncrypted);
  22245. media.removeEventListener('waitingforkey', this.onWaitingForKey);
  22246. this.media = null;
  22247. }
  22248. this._requestLicenseFailureCount = 0;
  22249. this.setMediaKeysQueue = [];
  22250. this.mediaKeySessions = [];
  22251. this.keyIdToKeySessionPromise = {};
  22252. LevelKey.clearKeyUriToKeyIdMap();
  22253. // Close all sessions and remove media keys from the video element.
  22254. const keySessionCount = mediaKeysList.length;
  22255. EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map(mediaKeySessionContext => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : media.setMediaKeys(null).catch(error => {
  22256. this.log(`Could not clear media keys: ${error}`);
  22257. }))).then(() => {
  22258. if (keySessionCount) {
  22259. this.log('finished closing key sessions and clearing media keys');
  22260. mediaKeysList.length = 0;
  22261. }
  22262. }).catch(error => {
  22263. this.log(`Could not close sessions and clear media keys: ${error}`);
  22264. });
  22265. }
  22266. onManifestLoading() {
  22267. this.keyFormatPromise = null;
  22268. }
  22269. onManifestLoaded(event, {
  22270. sessionKeys
  22271. }) {
  22272. if (!sessionKeys || !this.config.emeEnabled) {
  22273. return;
  22274. }
  22275. if (!this.keyFormatPromise) {
  22276. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  22277. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  22278. formats.push(sessionKey.keyFormat);
  22279. }
  22280. return formats;
  22281. }, []);
  22282. this.log(`Selecting key-system from session-keys ${keyFormats.join(', ')}`);
  22283. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  22284. }
  22285. }
  22286. removeSession(mediaKeySessionContext) {
  22287. const {
  22288. mediaKeysSession,
  22289. licenseXhr
  22290. } = mediaKeySessionContext;
  22291. if (mediaKeysSession) {
  22292. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  22293. if (mediaKeySessionContext._onmessage) {
  22294. mediaKeysSession.removeEventListener('message', mediaKeySessionContext._onmessage);
  22295. mediaKeySessionContext._onmessage = undefined;
  22296. }
  22297. if (mediaKeySessionContext._onkeystatuseschange) {
  22298. mediaKeysSession.removeEventListener('keystatuseschange', mediaKeySessionContext._onkeystatuseschange);
  22299. mediaKeySessionContext._onkeystatuseschange = undefined;
  22300. }
  22301. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22302. licenseXhr.abort();
  22303. }
  22304. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = undefined;
  22305. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  22306. if (index > -1) {
  22307. this.mediaKeySessions.splice(index, 1);
  22308. }
  22309. return mediaKeysSession.remove().catch(error => {
  22310. this.log(`Could not remove session: ${error}`);
  22311. }).then(() => {
  22312. return mediaKeysSession.close();
  22313. }).catch(error => {
  22314. this.log(`Could not close session: ${error}`);
  22315. });
  22316. }
  22317. }
  22318. }
  22319. EMEController.CDMCleanupPromise = void 0;
  22320. class EMEKeyError extends Error {
  22321. constructor(data, message) {
  22322. super(message);
  22323. this.data = void 0;
  22324. data.error || (data.error = new Error(message));
  22325. this.data = data;
  22326. data.err = data.error;
  22327. }
  22328. }
  22329. /**
  22330. * Common Media Object Type
  22331. *
  22332. * @group CMCD
  22333. * @group CMSD
  22334. *
  22335. * @beta
  22336. */
  22337. var CmObjectType;
  22338. (function (CmObjectType) {
  22339. /**
  22340. * text file, such as a manifest or playlist
  22341. */
  22342. CmObjectType["MANIFEST"] = "m";
  22343. /**
  22344. * audio only
  22345. */
  22346. CmObjectType["AUDIO"] = "a";
  22347. /**
  22348. * video only
  22349. */
  22350. CmObjectType["VIDEO"] = "v";
  22351. /**
  22352. * muxed audio and video
  22353. */
  22354. CmObjectType["MUXED"] = "av";
  22355. /**
  22356. * init segment
  22357. */
  22358. CmObjectType["INIT"] = "i";
  22359. /**
  22360. * caption or subtitle
  22361. */
  22362. CmObjectType["CAPTION"] = "c";
  22363. /**
  22364. * ISOBMFF timed text track
  22365. */
  22366. CmObjectType["TIMED_TEXT"] = "tt";
  22367. /**
  22368. * cryptographic key, license or certificate.
  22369. */
  22370. CmObjectType["KEY"] = "k";
  22371. /**
  22372. * other
  22373. */
  22374. CmObjectType["OTHER"] = "o";
  22375. })(CmObjectType || (CmObjectType = {}));
  22376. /**
  22377. * Common Media Streaming Format
  22378. *
  22379. * @group CMCD
  22380. * @group CMSD
  22381. *
  22382. * @beta
  22383. */
  22384. var CmStreamingFormat;
  22385. (function (CmStreamingFormat) {
  22386. /**
  22387. * MPEG DASH
  22388. */
  22389. CmStreamingFormat["DASH"] = "d";
  22390. /**
  22391. * HTTP Live Streaming (HLS)
  22392. */
  22393. CmStreamingFormat["HLS"] = "h";
  22394. /**
  22395. * Smooth Streaming
  22396. */
  22397. CmStreamingFormat["SMOOTH"] = "s";
  22398. /**
  22399. * Other
  22400. */
  22401. CmStreamingFormat["OTHER"] = "o";
  22402. })(CmStreamingFormat || (CmStreamingFormat = {}));
  22403. /**
  22404. * CMCD header fields.
  22405. *
  22406. * @group CMCD
  22407. *
  22408. * @beta
  22409. */
  22410. var CmcdHeaderField;
  22411. (function (CmcdHeaderField) {
  22412. /**
  22413. * keys whose values vary with the object being requested.
  22414. */
  22415. CmcdHeaderField["OBJECT"] = "CMCD-Object";
  22416. /**
  22417. * keys whose values vary with each request.
  22418. */
  22419. CmcdHeaderField["REQUEST"] = "CMCD-Request";
  22420. /**
  22421. * keys whose values are expected to be invariant over the life of the session.
  22422. */
  22423. CmcdHeaderField["SESSION"] = "CMCD-Session";
  22424. /**
  22425. * keys whose values do not vary with every request or object.
  22426. */
  22427. CmcdHeaderField["STATUS"] = "CMCD-Status";
  22428. })(CmcdHeaderField || (CmcdHeaderField = {}));
  22429. /**
  22430. * The map of CMCD header fields to official CMCD keys.
  22431. *
  22432. * @internal
  22433. *
  22434. * @group CMCD
  22435. */
  22436. const CmcdHeaderMap = {
  22437. [CmcdHeaderField.OBJECT]: ['br', 'd', 'ot', 'tb'],
  22438. [CmcdHeaderField.REQUEST]: ['bl', 'dl', 'mtp', 'nor', 'nrr', 'su'],
  22439. [CmcdHeaderField.SESSION]: ['cid', 'pr', 'sf', 'sid', 'st', 'v'],
  22440. [CmcdHeaderField.STATUS]: ['bs', 'rtp']
  22441. };
  22442. /**
  22443. * Structured Field Item
  22444. *
  22445. * @group Structured Field
  22446. *
  22447. * @beta
  22448. */
  22449. class SfItem {
  22450. constructor(value, params) {
  22451. this.value = void 0;
  22452. this.params = void 0;
  22453. if (Array.isArray(value)) {
  22454. value = value.map(v => v instanceof SfItem ? v : new SfItem(v));
  22455. }
  22456. this.value = value;
  22457. this.params = params;
  22458. }
  22459. }
  22460. /**
  22461. * A class to represent structured field tokens when `Symbol` is not available.
  22462. *
  22463. * @group Structured Field
  22464. *
  22465. * @beta
  22466. */
  22467. class SfToken {
  22468. constructor(description) {
  22469. this.description = void 0;
  22470. this.description = description;
  22471. }
  22472. }
  22473. const DICT = 'Dict';
  22474. function format(value) {
  22475. if (Array.isArray(value)) {
  22476. return JSON.stringify(value);
  22477. }
  22478. if (value instanceof Map) {
  22479. return 'Map{}';
  22480. }
  22481. if (value instanceof Set) {
  22482. return 'Set{}';
  22483. }
  22484. if (typeof value === 'object') {
  22485. return JSON.stringify(value);
  22486. }
  22487. return String(value);
  22488. }
  22489. function throwError(action, src, type, cause) {
  22490. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  22491. cause
  22492. });
  22493. }
  22494. const BARE_ITEM = 'Bare Item';
  22495. const BOOLEAN = 'Boolean';
  22496. const BYTES = 'Byte Sequence';
  22497. const DECIMAL = 'Decimal';
  22498. const INTEGER = 'Integer';
  22499. function isInvalidInt(value) {
  22500. return value < -999999999999999 || 999999999999999 < value;
  22501. }
  22502. const STRING_REGEX = /[\x00-\x1f\x7f]+/; // eslint-disable-line no-control-regex
  22503. const TOKEN = 'Token';
  22504. const KEY = 'Key';
  22505. function serializeError(src, type, cause) {
  22506. return throwError('serialize', src, type, cause);
  22507. }
  22508. // 4.1.9. Serializing a Boolean
  22509. //
  22510. // Given a Boolean as input_boolean, return an ASCII string suitable for
  22511. // use in a HTTP field value.
  22512. //
  22513. // 1. If input_boolean is not a boolean, fail serialization.
  22514. //
  22515. // 2. Let output be an empty string.
  22516. //
  22517. // 3. Append "?" to output.
  22518. //
  22519. // 4. If input_boolean is true, append "1" to output.
  22520. //
  22521. // 5. If input_boolean is false, append "0" to output.
  22522. //
  22523. // 6. Return output.
  22524. function serializeBoolean(value) {
  22525. if (typeof value !== 'boolean') {
  22526. throw serializeError(value, BOOLEAN);
  22527. }
  22528. return value ? '?1' : '?0';
  22529. }
  22530. /**
  22531. * Encodes binary data to base64
  22532. *
  22533. * @param binary - The binary data to encode
  22534. * @returns The base64 encoded string
  22535. *
  22536. * @group Utils
  22537. *
  22538. * @beta
  22539. */
  22540. function base64encode(binary) {
  22541. return btoa(String.fromCharCode(...binary));
  22542. }
  22543. // 4.1.8. Serializing a Byte Sequence
  22544. //
  22545. // Given a Byte Sequence as input_bytes, return an ASCII string suitable
  22546. // for use in a HTTP field value.
  22547. //
  22548. // 1. If input_bytes is not a sequence of bytes, fail serialization.
  22549. //
  22550. // 2. Let output be an empty string.
  22551. //
  22552. // 3. Append ":" to output.
  22553. //
  22554. // 4. Append the result of base64-encoding input_bytes as per
  22555. // [RFC4648], Section 4, taking account of the requirements below.
  22556. //
  22557. // 5. Append ":" to output.
  22558. //
  22559. // 6. Return output.
  22560. //
  22561. // The encoded data is required to be padded with "=", as per [RFC4648],
  22562. // Section 3.2.
  22563. //
  22564. // Likewise, encoded data SHOULD have pad bits set to zero, as per
  22565. // [RFC4648], Section 3.5, unless it is not possible to do so due to
  22566. // implementation constraints.
  22567. function serializeByteSequence(value) {
  22568. if (ArrayBuffer.isView(value) === false) {
  22569. throw serializeError(value, BYTES);
  22570. }
  22571. return `:${base64encode(value)}:`;
  22572. }
  22573. // 4.1.4. Serializing an Integer
  22574. //
  22575. // Given an Integer as input_integer, return an ASCII string suitable
  22576. // for use in a HTTP field value.
  22577. //
  22578. // 1. If input_integer is not an integer in the range of
  22579. // -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
  22580. // serialization.
  22581. //
  22582. // 2. Let output be an empty string.
  22583. //
  22584. // 3. If input_integer is less than (but not equal to) 0, append "-" to
  22585. // output.
  22586. //
  22587. // 4. Append input_integer's numeric value represented in base 10 using
  22588. // only decimal digits to output.
  22589. //
  22590. // 5. Return output.
  22591. function serializeInteger(value) {
  22592. if (isInvalidInt(value)) {
  22593. throw serializeError(value, INTEGER);
  22594. }
  22595. return value.toString();
  22596. }
  22597. // 4.1.10. Serializing a Date
  22598. //
  22599. // Given a Date as input_integer, return an ASCII string suitable for
  22600. // use in an HTTP field value.
  22601. // 1. Let output be "@".
  22602. // 2. Append to output the result of running Serializing an Integer
  22603. // with input_date (Section 4.1.4).
  22604. // 3. Return output.
  22605. function serializeDate(value) {
  22606. return `@${serializeInteger(value.getTime() / 1000)}`;
  22607. }
  22608. /**
  22609. * This implements the rounding procedure described in step 2 of the "Serializing a Decimal" specification.
  22610. * This rounding style is known as "even rounding", "banker's rounding", or "commercial rounding".
  22611. *
  22612. * @param value - The value to round
  22613. * @param precision - The number of decimal places to round to
  22614. * @returns The rounded value
  22615. *
  22616. * @group Utils
  22617. *
  22618. * @beta
  22619. */
  22620. function roundToEven(value, precision) {
  22621. if (value < 0) {
  22622. return -roundToEven(-value, precision);
  22623. }
  22624. const decimalShift = Math.pow(10, precision);
  22625. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  22626. if (isEquidistant) {
  22627. // If the tail of the decimal place is 'equidistant' we round to the nearest even value
  22628. const flooredValue = Math.floor(value * decimalShift);
  22629. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  22630. } else {
  22631. // Otherwise, proceed as normal
  22632. return Math.round(value * decimalShift) / decimalShift;
  22633. }
  22634. }
  22635. // 4.1.5. Serializing a Decimal
  22636. //
  22637. // Given a decimal number as input_decimal, return an ASCII string
  22638. // suitable for use in a HTTP field value.
  22639. //
  22640. // 1. If input_decimal is not a decimal number, fail serialization.
  22641. //
  22642. // 2. If input_decimal has more than three significant digits to the
  22643. // right of the decimal point, round it to three decimal places,
  22644. // rounding the final digit to the nearest value, or to the even
  22645. // value if it is equidistant.
  22646. //
  22647. // 3. If input_decimal has more than 12 significant digits to the left
  22648. // of the decimal point after rounding, fail serialization.
  22649. //
  22650. // 4. Let output be an empty string.
  22651. //
  22652. // 5. If input_decimal is less than (but not equal to) 0, append "-"
  22653. // to output.
  22654. //
  22655. // 6. Append input_decimal's integer component represented in base 10
  22656. // (using only decimal digits) to output; if it is zero, append
  22657. // "0".
  22658. //
  22659. // 7. Append "." to output.
  22660. //
  22661. // 8. If input_decimal's fractional component is zero, append "0" to
  22662. // output.
  22663. //
  22664. // 9. Otherwise, append the significant digits of input_decimal's
  22665. // fractional component represented in base 10 (using only decimal
  22666. // digits) to output.
  22667. //
  22668. // 10. Return output.
  22669. function serializeDecimal(value) {
  22670. const roundedValue = roundToEven(value, 3); // round to 3 decimal places
  22671. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  22672. throw serializeError(value, DECIMAL);
  22673. }
  22674. const stringValue = roundedValue.toString();
  22675. return stringValue.includes('.') ? stringValue : `${stringValue}.0`;
  22676. }
  22677. const STRING = 'String';
  22678. // 4.1.6. Serializing a String
  22679. //
  22680. // Given a String as input_string, return an ASCII string suitable for
  22681. // use in a HTTP field value.
  22682. //
  22683. // 1. Convert input_string into a sequence of ASCII characters; if
  22684. // conversion fails, fail serialization.
  22685. //
  22686. // 2. If input_string contains characters in the range %x00-1f or %x7f
  22687. // (i.e., not in VCHAR or SP), fail serialization.
  22688. //
  22689. // 3. Let output be the string DQUOTE.
  22690. //
  22691. // 4. For each character char in input_string:
  22692. //
  22693. // 1. If char is "\" or DQUOTE:
  22694. //
  22695. // 1. Append "\" to output.
  22696. //
  22697. // 2. Append char to output.
  22698. //
  22699. // 5. Append DQUOTE to output.
  22700. //
  22701. // 6. Return output.
  22702. function serializeString(value) {
  22703. if (STRING_REGEX.test(value)) {
  22704. throw serializeError(value, STRING);
  22705. }
  22706. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  22707. }
  22708. function symbolToStr(symbol) {
  22709. return symbol.description || symbol.toString().slice(7, -1);
  22710. }
  22711. function serializeToken(token) {
  22712. const value = symbolToStr(token);
  22713. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  22714. throw serializeError(value, TOKEN);
  22715. }
  22716. return value;
  22717. }
  22718. // 4.1.3.1. Serializing a Bare Item
  22719. //
  22720. // Given an Item as input_item, return an ASCII string suitable for use
  22721. // in a HTTP field value.
  22722. //
  22723. // 1. If input_item is an Integer, return the result of running
  22724. // Serializing an Integer (Section 4.1.4) with input_item.
  22725. //
  22726. // 2. If input_item is a Decimal, return the result of running
  22727. // Serializing a Decimal (Section 4.1.5) with input_item.
  22728. //
  22729. // 3. If input_item is a String, return the result of running
  22730. // Serializing a String (Section 4.1.6) with input_item.
  22731. //
  22732. // 4. If input_item is a Token, return the result of running
  22733. // Serializing a Token (Section 4.1.7) with input_item.
  22734. //
  22735. // 5. If input_item is a Boolean, return the result of running
  22736. // Serializing a Boolean (Section 4.1.9) with input_item.
  22737. //
  22738. // 6. If input_item is a Byte Sequence, return the result of running
  22739. // Serializing a Byte Sequence (Section 4.1.8) with input_item.
  22740. //
  22741. // 7. If input_item is a Date, return the result of running Serializing
  22742. // a Date (Section 4.1.10) with input_item.
  22743. //
  22744. // 8. Otherwise, fail serialization.
  22745. function serializeBareItem(value) {
  22746. switch (typeof value) {
  22747. case 'number':
  22748. if (!isFiniteNumber(value)) {
  22749. throw serializeError(value, BARE_ITEM);
  22750. }
  22751. if (Number.isInteger(value)) {
  22752. return serializeInteger(value);
  22753. }
  22754. return serializeDecimal(value);
  22755. case 'string':
  22756. return serializeString(value);
  22757. case 'symbol':
  22758. return serializeToken(value);
  22759. case 'boolean':
  22760. return serializeBoolean(value);
  22761. case 'object':
  22762. if (value instanceof Date) {
  22763. return serializeDate(value);
  22764. }
  22765. if (value instanceof Uint8Array) {
  22766. return serializeByteSequence(value);
  22767. }
  22768. if (value instanceof SfToken) {
  22769. return serializeToken(value);
  22770. }
  22771. default:
  22772. // fail
  22773. throw serializeError(value, BARE_ITEM);
  22774. }
  22775. }
  22776. // 4.1.1.3. Serializing a Key
  22777. //
  22778. // Given a key as input_key, return an ASCII string suitable for use in
  22779. // a HTTP field value.
  22780. //
  22781. // 1. Convert input_key into a sequence of ASCII characters; if
  22782. // conversion fails, fail serialization.
  22783. //
  22784. // 2. If input_key contains characters not in lcalpha, DIGIT, "_", "-",
  22785. // ".", or "*" fail serialization.
  22786. //
  22787. // 3. If the first character of input_key is not lcalpha or "*", fail
  22788. // serialization.
  22789. //
  22790. // 4. Let output be an empty string.
  22791. //
  22792. // 5. Append input_key to output.
  22793. //
  22794. // 6. Return output.
  22795. function serializeKey(value) {
  22796. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  22797. throw serializeError(value, KEY);
  22798. }
  22799. return value;
  22800. }
  22801. // 4.1.1.2. Serializing Parameters
  22802. //
  22803. // Given an ordered Dictionary as input_parameters (each member having a
  22804. // param_name and a param_value), return an ASCII string suitable for
  22805. // use in a HTTP field value.
  22806. //
  22807. // 1. Let output be an empty string.
  22808. //
  22809. // 2. For each param_name with a value of param_value in
  22810. // input_parameters:
  22811. //
  22812. // 1. Append ";" to output.
  22813. //
  22814. // 2. Append the result of running Serializing a Key
  22815. // (Section 4.1.1.3) with param_name to output.
  22816. //
  22817. // 3. If param_value is not Boolean true:
  22818. //
  22819. // 1. Append "=" to output.
  22820. //
  22821. // 2. Append the result of running Serializing a bare Item
  22822. // (Section 4.1.3.1) with param_value to output.
  22823. //
  22824. // 3. Return output.
  22825. function serializeParams(params) {
  22826. if (params == null) {
  22827. return '';
  22828. }
  22829. return Object.entries(params).map(([key, value]) => {
  22830. if (value === true) {
  22831. return `;${serializeKey(key)}`; // omit true
  22832. }
  22833. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  22834. }).join('');
  22835. }
  22836. // 4.1.3. Serializing an Item
  22837. //
  22838. // Given an Item as bare_item and Parameters as item_parameters, return
  22839. // an ASCII string suitable for use in a HTTP field value.
  22840. //
  22841. // 1. Let output be an empty string.
  22842. //
  22843. // 2. Append the result of running Serializing a Bare Item
  22844. // Section 4.1.3.1 with bare_item to output.
  22845. //
  22846. // 3. Append the result of running Serializing Parameters
  22847. // Section 4.1.1.2 with item_parameters to output.
  22848. //
  22849. // 4. Return output.
  22850. function serializeItem(value) {
  22851. if (value instanceof SfItem) {
  22852. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  22853. } else {
  22854. return serializeBareItem(value);
  22855. }
  22856. }
  22857. // 4.1.1.1. Serializing an Inner List
  22858. //
  22859. // Given an array of (member_value, parameters) tuples as inner_list,
  22860. // and parameters as list_parameters, return an ASCII string suitable
  22861. // for use in a HTTP field value.
  22862. //
  22863. // 1. Let output be the string "(".
  22864. //
  22865. // 2. For each (member_value, parameters) of inner_list:
  22866. //
  22867. // 1. Append the result of running Serializing an Item
  22868. // (Section 4.1.3) with (member_value, parameters) to output.
  22869. //
  22870. // 2. If more values remain in inner_list, append a single SP to
  22871. // output.
  22872. //
  22873. // 3. Append ")" to output.
  22874. //
  22875. // 4. Append the result of running Serializing Parameters
  22876. // (Section 4.1.1.2) with list_parameters to output.
  22877. //
  22878. // 5. Return output.
  22879. function serializeInnerList(value) {
  22880. return `(${value.value.map(serializeItem).join(' ')})${serializeParams(value.params)}`;
  22881. }
  22882. // 4.1.2. Serializing a Dictionary
  22883. //
  22884. // Given an ordered Dictionary as input_dictionary (each member having a
  22885. // member_name and a tuple value of (member_value, parameters)), return
  22886. // an ASCII string suitable for use in a HTTP field value.
  22887. //
  22888. // 1. Let output be an empty string.
  22889. //
  22890. // 2. For each member_name with a value of (member_value, parameters)
  22891. // in input_dictionary:
  22892. //
  22893. // 1. Append the result of running Serializing a Key
  22894. // (Section 4.1.1.3) with member's member_name to output.
  22895. //
  22896. // 2. If member_value is Boolean true:
  22897. //
  22898. // 1. Append the result of running Serializing Parameters
  22899. // (Section 4.1.1.2) with parameters to output.
  22900. //
  22901. // 3. Otherwise:
  22902. //
  22903. // 1. Append "=" to output.
  22904. //
  22905. // 2. If member_value is an array, append the result of running
  22906. // Serializing an Inner List (Section 4.1.1.1) with
  22907. // (member_value, parameters) to output.
  22908. //
  22909. // 3. Otherwise, append the result of running Serializing an
  22910. // Item (Section 4.1.3) with (member_value, parameters) to
  22911. // output.
  22912. //
  22913. // 4. If more members remain in input_dictionary:
  22914. //
  22915. // 1. Append "," to output.
  22916. //
  22917. // 2. Append a single SP to output.
  22918. //
  22919. // 3. Return output.
  22920. function serializeDict(dict, options = {
  22921. whitespace: true
  22922. }) {
  22923. if (typeof dict !== 'object') {
  22924. throw serializeError(dict, DICT);
  22925. }
  22926. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  22927. const optionalWhiteSpace = options != null && options.whitespace ? ' ' : '';
  22928. return Array.from(entries).map(([key, item]) => {
  22929. if (item instanceof SfItem === false) {
  22930. item = new SfItem(item);
  22931. }
  22932. let output = serializeKey(key);
  22933. if (item.value === true) {
  22934. output += serializeParams(item.params);
  22935. } else {
  22936. output += '=';
  22937. if (Array.isArray(item.value)) {
  22938. output += serializeInnerList(item);
  22939. } else {
  22940. output += serializeItem(item);
  22941. }
  22942. }
  22943. return output;
  22944. }).join(`,${optionalWhiteSpace}`);
  22945. }
  22946. /**
  22947. * Encode an object into a structured field dictionary
  22948. *
  22949. * @param input - The structured field dictionary to encode
  22950. * @returns The structured field string
  22951. *
  22952. * @group Structured Field
  22953. *
  22954. * @beta
  22955. */
  22956. function encodeSfDict(value, options) {
  22957. return serializeDict(value, options);
  22958. }
  22959. /**
  22960. * Checks if the given key is a token field.
  22961. *
  22962. * @param key - The key to check.
  22963. *
  22964. * @returns `true` if the key is a token field.
  22965. *
  22966. * @internal
  22967. *
  22968. * @group CMCD
  22969. */
  22970. const isTokenField = key => key === 'ot' || key === 'sf' || key === 'st';
  22971. const isValid = value => {
  22972. if (typeof value === 'number') {
  22973. return isFiniteNumber(value);
  22974. }
  22975. return value != null && value !== '' && value !== false;
  22976. };
  22977. /**
  22978. * Constructs a relative path from a URL.
  22979. *
  22980. * @param url - The destination URL
  22981. * @param base - The base URL
  22982. * @returns The relative path
  22983. *
  22984. * @group Utils
  22985. *
  22986. * @beta
  22987. */
  22988. function urlToRelativePath(url, base) {
  22989. const to = new URL(url);
  22990. const from = new URL(base);
  22991. if (to.origin !== from.origin) {
  22992. return url;
  22993. }
  22994. const toPath = to.pathname.split('/').slice(1);
  22995. const fromPath = from.pathname.split('/').slice(1, -1);
  22996. // remove common parents
  22997. while (toPath[0] === fromPath[0]) {
  22998. toPath.shift();
  22999. fromPath.shift();
  23000. }
  23001. // add back paths
  23002. while (fromPath.length) {
  23003. fromPath.shift();
  23004. toPath.unshift('..');
  23005. }
  23006. return toPath.join('/');
  23007. }
  23008. /**
  23009. * Generate a random v4 UUID
  23010. *
  23011. * @returns A random v4 UUID
  23012. *
  23013. * @group Utils
  23014. *
  23015. * @beta
  23016. */
  23017. function uuid() {
  23018. try {
  23019. return crypto.randomUUID();
  23020. } catch (error) {
  23021. try {
  23022. const url = URL.createObjectURL(new Blob());
  23023. const uuid = url.toString();
  23024. URL.revokeObjectURL(url);
  23025. return uuid.slice(uuid.lastIndexOf('/') + 1);
  23026. } catch (error) {
  23027. let dt = new Date().getTime();
  23028. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  23029. const r = (dt + Math.random() * 16) % 16 | 0;
  23030. dt = Math.floor(dt / 16);
  23031. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  23032. });
  23033. return uuid;
  23034. }
  23035. }
  23036. }
  23037. const toRounded = value => Math.round(value);
  23038. const toUrlSafe = (value, options) => {
  23039. if (options != null && options.baseUrl) {
  23040. value = urlToRelativePath(value, options.baseUrl);
  23041. }
  23042. return encodeURIComponent(value);
  23043. };
  23044. const toHundred = value => toRounded(value / 100) * 100;
  23045. /**
  23046. * The default formatters for CMCD values.
  23047. *
  23048. * @group CMCD
  23049. *
  23050. * @beta
  23051. */
  23052. const CmcdFormatters = {
  23053. /**
  23054. * Bitrate (kbps) rounded integer
  23055. */
  23056. br: toRounded,
  23057. /**
  23058. * Duration (milliseconds) rounded integer
  23059. */
  23060. d: toRounded,
  23061. /**
  23062. * Buffer Length (milliseconds) rounded nearest 100ms
  23063. */
  23064. bl: toHundred,
  23065. /**
  23066. * Deadline (milliseconds) rounded nearest 100ms
  23067. */
  23068. dl: toHundred,
  23069. /**
  23070. * Measured Throughput (kbps) rounded nearest 100kbps
  23071. */
  23072. mtp: toHundred,
  23073. /**
  23074. * Next Object Request URL encoded
  23075. */
  23076. nor: toUrlSafe,
  23077. /**
  23078. * Requested maximum throughput (kbps) rounded nearest 100kbps
  23079. */
  23080. rtp: toHundred,
  23081. /**
  23082. * Top Bitrate (kbps) rounded integer
  23083. */
  23084. tb: toRounded
  23085. };
  23086. /**
  23087. * Internal CMCD processing function.
  23088. *
  23089. * @param obj - The CMCD object to process.
  23090. * @param map - The mapping function to use.
  23091. * @param options - Options for encoding.
  23092. *
  23093. * @internal
  23094. *
  23095. * @group CMCD
  23096. */
  23097. function processCmcd(obj, options) {
  23098. const results = {};
  23099. if (obj == null || typeof obj !== 'object') {
  23100. return results;
  23101. }
  23102. const keys = Object.keys(obj).sort();
  23103. const formatters = _extends({}, CmcdFormatters, options == null ? void 0 : options.formatters);
  23104. const filter = options == null ? void 0 : options.filter;
  23105. keys.forEach(key => {
  23106. if (filter != null && filter(key)) {
  23107. return;
  23108. }
  23109. let value = obj[key];
  23110. const formatter = formatters[key];
  23111. if (formatter) {
  23112. value = formatter(value, options);
  23113. }
  23114. // Version should only be reported if not equal to 1.
  23115. if (key === 'v' && value === 1) {
  23116. return;
  23117. }
  23118. // Playback rate should only be sent if not equal to 1.
  23119. if (key == 'pr' && value === 1) {
  23120. return;
  23121. }
  23122. // ignore invalid values
  23123. if (!isValid(value)) {
  23124. return;
  23125. }
  23126. if (isTokenField(key) && typeof value === 'string') {
  23127. value = new SfToken(value);
  23128. }
  23129. results[key] = value;
  23130. });
  23131. return results;
  23132. }
  23133. /**
  23134. * Encode a CMCD object to a string.
  23135. *
  23136. * @param cmcd - The CMCD object to encode.
  23137. * @param options - Options for encoding.
  23138. *
  23139. * @returns The encoded CMCD string.
  23140. *
  23141. * @group CMCD
  23142. *
  23143. * @beta
  23144. */
  23145. function encodeCmcd(cmcd, options = {}) {
  23146. if (!cmcd) {
  23147. return '';
  23148. }
  23149. return encodeSfDict(processCmcd(cmcd, options), _extends({
  23150. whitespace: false
  23151. }, options));
  23152. }
  23153. /**
  23154. * Convert a CMCD data object to request headers
  23155. *
  23156. * @param cmcd - The CMCD data object to convert.
  23157. * @param options - Options for encoding the CMCD object.
  23158. *
  23159. * @returns The CMCD header shards.
  23160. *
  23161. * @group CMCD
  23162. *
  23163. * @beta
  23164. */
  23165. function toCmcdHeaders(cmcd, options = {}) {
  23166. if (!cmcd) {
  23167. return {};
  23168. }
  23169. const entries = Object.entries(cmcd);
  23170. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options == null ? void 0 : options.customHeaderMap) || {}));
  23171. const shards = entries.reduce((acc, entry) => {
  23172. var _headerMap$find, _acc$field;
  23173. const [key, value] = entry;
  23174. const field = ((_headerMap$find = headerMap.find(entry => entry[1].includes(key))) == null ? void 0 : _headerMap$find[0]) || CmcdHeaderField.REQUEST;
  23175. (_acc$field = acc[field]) != null ? _acc$field : acc[field] = {};
  23176. acc[field][key] = value;
  23177. return acc;
  23178. }, {});
  23179. return Object.entries(shards).reduce((acc, [field, value]) => {
  23180. acc[field] = encodeCmcd(value, options);
  23181. return acc;
  23182. }, {});
  23183. }
  23184. /**
  23185. * Append CMCD query args to a header object.
  23186. *
  23187. * @param headers - The headers to append to.
  23188. * @param cmcd - The CMCD object to append.
  23189. * @param customHeaderMap - A map of custom CMCD keys to header fields.
  23190. *
  23191. * @returns The headers with the CMCD header shards appended.
  23192. *
  23193. * @group CMCD
  23194. *
  23195. * @beta
  23196. */
  23197. function appendCmcdHeaders(headers, cmcd, options) {
  23198. return _extends(headers, toCmcdHeaders(cmcd, options));
  23199. }
  23200. /**
  23201. * CMCD parameter name.
  23202. *
  23203. * @group CMCD
  23204. *
  23205. * @beta
  23206. */
  23207. const CMCD_PARAM = 'CMCD';
  23208. /**
  23209. * Convert a CMCD data object to a query arg.
  23210. *
  23211. * @param cmcd - The CMCD object to convert.
  23212. * @param options - Options for encoding the CMCD object.
  23213. *
  23214. * @returns The CMCD query arg.
  23215. *
  23216. * @group CMCD
  23217. *
  23218. * @beta
  23219. */
  23220. function toCmcdQuery(cmcd, options = {}) {
  23221. if (!cmcd) {
  23222. return '';
  23223. }
  23224. const params = encodeCmcd(cmcd, options);
  23225. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  23226. }
  23227. const REGEX = /CMCD=[^&#]+/;
  23228. /**
  23229. * Append CMCD query args to a URL.
  23230. *
  23231. * @param url - The URL to append to.
  23232. * @param cmcd - The CMCD object to append.
  23233. * @param options - Options for encoding the CMCD object.
  23234. *
  23235. * @returns The URL with the CMCD query args appended.
  23236. *
  23237. * @group CMCD
  23238. *
  23239. * @beta
  23240. */
  23241. function appendCmcdQuery(url, cmcd, options) {
  23242. // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.
  23243. // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
  23244. const query = toCmcdQuery(cmcd, options);
  23245. if (!query) {
  23246. return url;
  23247. }
  23248. if (REGEX.test(url)) {
  23249. return url.replace(REGEX, query);
  23250. }
  23251. const separator = url.includes('?') ? '&' : '?';
  23252. return `${url}${separator}${query}`;
  23253. }
  23254. /**
  23255. * Controller to deal with Common Media Client Data (CMCD)
  23256. * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
  23257. */
  23258. class CMCDController {
  23259. // eslint-disable-line no-restricted-globals
  23260. constructor(hls) {
  23261. this.hls = void 0;
  23262. this.config = void 0;
  23263. this.media = void 0;
  23264. this.sid = void 0;
  23265. this.cid = void 0;
  23266. this.useHeaders = false;
  23267. this.includeKeys = void 0;
  23268. this.initialized = false;
  23269. this.starved = false;
  23270. this.buffering = true;
  23271. this.audioBuffer = void 0;
  23272. // eslint-disable-line no-restricted-globals
  23273. this.videoBuffer = void 0;
  23274. this.onWaiting = () => {
  23275. if (this.initialized) {
  23276. this.starved = true;
  23277. }
  23278. this.buffering = true;
  23279. };
  23280. this.onPlaying = () => {
  23281. if (!this.initialized) {
  23282. this.initialized = true;
  23283. }
  23284. this.buffering = false;
  23285. };
  23286. /**
  23287. * Apply CMCD data to a manifest request.
  23288. */
  23289. this.applyPlaylistData = context => {
  23290. try {
  23291. this.apply(context, {
  23292. ot: CmObjectType.MANIFEST,
  23293. su: !this.initialized
  23294. });
  23295. } catch (error) {
  23296. logger.warn('Could not generate manifest CMCD data.', error);
  23297. }
  23298. };
  23299. /**
  23300. * Apply CMCD data to a segment request
  23301. */
  23302. this.applyFragmentData = context => {
  23303. try {
  23304. const fragment = context.frag;
  23305. const level = this.hls.levels[fragment.level];
  23306. const ot = this.getObjectType(fragment);
  23307. const data = {
  23308. d: fragment.duration * 1000,
  23309. ot
  23310. };
  23311. if (ot === CmObjectType.VIDEO || ot === CmObjectType.AUDIO || ot == CmObjectType.MUXED) {
  23312. data.br = level.bitrate / 1000;
  23313. data.tb = this.getTopBandwidth(ot) / 1000;
  23314. data.bl = this.getBufferLength(ot);
  23315. }
  23316. this.apply(context, data);
  23317. } catch (error) {
  23318. logger.warn('Could not generate segment CMCD data.', error);
  23319. }
  23320. };
  23321. this.hls = hls;
  23322. const config = this.config = hls.config;
  23323. const {
  23324. cmcd
  23325. } = config;
  23326. if (cmcd != null) {
  23327. config.pLoader = this.createPlaylistLoader();
  23328. config.fLoader = this.createFragmentLoader();
  23329. this.sid = cmcd.sessionId || uuid();
  23330. this.cid = cmcd.contentId;
  23331. this.useHeaders = cmcd.useHeaders === true;
  23332. this.includeKeys = cmcd.includeKeys;
  23333. this.registerListeners();
  23334. }
  23335. }
  23336. registerListeners() {
  23337. const hls = this.hls;
  23338. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23339. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23340. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23341. }
  23342. unregisterListeners() {
  23343. const hls = this.hls;
  23344. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23345. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23346. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23347. }
  23348. destroy() {
  23349. this.unregisterListeners();
  23350. this.onMediaDetached();
  23351. // @ts-ignore
  23352. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  23353. // @ts-ignore
  23354. this.onWaiting = this.onPlaying = null;
  23355. }
  23356. onMediaAttached(event, data) {
  23357. this.media = data.media;
  23358. this.media.addEventListener('waiting', this.onWaiting);
  23359. this.media.addEventListener('playing', this.onPlaying);
  23360. }
  23361. onMediaDetached() {
  23362. if (!this.media) {
  23363. return;
  23364. }
  23365. this.media.removeEventListener('waiting', this.onWaiting);
  23366. this.media.removeEventListener('playing', this.onPlaying);
  23367. // @ts-ignore
  23368. this.media = null;
  23369. }
  23370. onBufferCreated(event, data) {
  23371. var _data$tracks$audio, _data$tracks$video;
  23372. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  23373. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  23374. }
  23375. /**
  23376. * Create baseline CMCD data
  23377. */
  23378. createData() {
  23379. var _this$media;
  23380. return {
  23381. v: 1,
  23382. sf: CmStreamingFormat.HLS,
  23383. sid: this.sid,
  23384. cid: this.cid,
  23385. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  23386. mtp: this.hls.bandwidthEstimate / 1000
  23387. };
  23388. }
  23389. /**
  23390. * Apply CMCD data to a request.
  23391. */
  23392. apply(context, data = {}) {
  23393. // apply baseline data
  23394. _extends(data, this.createData());
  23395. const isVideo = data.ot === CmObjectType.INIT || data.ot === CmObjectType.VIDEO || data.ot === CmObjectType.MUXED;
  23396. if (this.starved && isVideo) {
  23397. data.bs = true;
  23398. data.su = true;
  23399. this.starved = false;
  23400. }
  23401. if (data.su == null) {
  23402. data.su = this.buffering;
  23403. }
  23404. // TODO: Implement rtp, nrr, nor, dl
  23405. const {
  23406. includeKeys
  23407. } = this;
  23408. if (includeKeys) {
  23409. data = Object.keys(data).reduce((acc, key) => {
  23410. includeKeys.includes(key) && (acc[key] = data[key]);
  23411. return acc;
  23412. }, {});
  23413. }
  23414. if (this.useHeaders) {
  23415. if (!context.headers) {
  23416. context.headers = {};
  23417. }
  23418. appendCmcdHeaders(context.headers, data);
  23419. } else {
  23420. context.url = appendCmcdQuery(context.url, data);
  23421. }
  23422. }
  23423. /**
  23424. * The CMCD object type.
  23425. */
  23426. getObjectType(fragment) {
  23427. const {
  23428. type
  23429. } = fragment;
  23430. if (type === 'subtitle') {
  23431. return CmObjectType.TIMED_TEXT;
  23432. }
  23433. if (fragment.sn === 'initSegment') {
  23434. return CmObjectType.INIT;
  23435. }
  23436. if (type === 'audio') {
  23437. return CmObjectType.AUDIO;
  23438. }
  23439. if (type === 'main') {
  23440. if (!this.hls.audioTracks.length) {
  23441. return CmObjectType.MUXED;
  23442. }
  23443. return CmObjectType.VIDEO;
  23444. }
  23445. return undefined;
  23446. }
  23447. /**
  23448. * Get the highest bitrate.
  23449. */
  23450. getTopBandwidth(type) {
  23451. let bitrate = 0;
  23452. let levels;
  23453. const hls = this.hls;
  23454. if (type === CmObjectType.AUDIO) {
  23455. levels = hls.audioTracks;
  23456. } else {
  23457. const max = hls.maxAutoLevel;
  23458. const len = max > -1 ? max + 1 : hls.levels.length;
  23459. levels = hls.levels.slice(0, len);
  23460. }
  23461. for (const level of levels) {
  23462. if (level.bitrate > bitrate) {
  23463. bitrate = level.bitrate;
  23464. }
  23465. }
  23466. return bitrate > 0 ? bitrate : NaN;
  23467. }
  23468. /**
  23469. * Get the buffer length for a media type in milliseconds
  23470. */
  23471. getBufferLength(type) {
  23472. const media = this.hls.media;
  23473. const buffer = type === CmObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  23474. if (!buffer || !media) {
  23475. return NaN;
  23476. }
  23477. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  23478. return info.len * 1000;
  23479. }
  23480. /**
  23481. * Create a playlist loader
  23482. */
  23483. createPlaylistLoader() {
  23484. const {
  23485. pLoader
  23486. } = this.config;
  23487. const apply = this.applyPlaylistData;
  23488. const Ctor = pLoader || this.config.loader;
  23489. return class CmcdPlaylistLoader {
  23490. constructor(config) {
  23491. this.loader = void 0;
  23492. this.loader = new Ctor(config);
  23493. }
  23494. get stats() {
  23495. return this.loader.stats;
  23496. }
  23497. get context() {
  23498. return this.loader.context;
  23499. }
  23500. destroy() {
  23501. this.loader.destroy();
  23502. }
  23503. abort() {
  23504. this.loader.abort();
  23505. }
  23506. load(context, config, callbacks) {
  23507. apply(context);
  23508. this.loader.load(context, config, callbacks);
  23509. }
  23510. };
  23511. }
  23512. /**
  23513. * Create a playlist loader
  23514. */
  23515. createFragmentLoader() {
  23516. const {
  23517. fLoader
  23518. } = this.config;
  23519. const apply = this.applyFragmentData;
  23520. const Ctor = fLoader || this.config.loader;
  23521. return class CmcdFragmentLoader {
  23522. constructor(config) {
  23523. this.loader = void 0;
  23524. this.loader = new Ctor(config);
  23525. }
  23526. get stats() {
  23527. return this.loader.stats;
  23528. }
  23529. get context() {
  23530. return this.loader.context;
  23531. }
  23532. destroy() {
  23533. this.loader.destroy();
  23534. }
  23535. abort() {
  23536. this.loader.abort();
  23537. }
  23538. load(context, config, callbacks) {
  23539. apply(context);
  23540. this.loader.load(context, config, callbacks);
  23541. }
  23542. };
  23543. }
  23544. }
  23545. const PATHWAY_PENALTY_DURATION_MS = 300000;
  23546. class ContentSteeringController {
  23547. constructor(hls) {
  23548. this.hls = void 0;
  23549. this.log = void 0;
  23550. this.loader = null;
  23551. this.uri = null;
  23552. this.pathwayId = '.';
  23553. this.pathwayPriority = null;
  23554. this.timeToLoad = 300;
  23555. this.reloadTimer = -1;
  23556. this.updated = 0;
  23557. this.started = false;
  23558. this.enabled = true;
  23559. this.levels = null;
  23560. this.audioTracks = null;
  23561. this.subtitleTracks = null;
  23562. this.penalizedPathways = {};
  23563. this.hls = hls;
  23564. this.log = logger.log.bind(logger, `[content-steering]:`);
  23565. this.registerListeners();
  23566. }
  23567. registerListeners() {
  23568. const hls = this.hls;
  23569. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23570. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23571. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23572. hls.on(Events.ERROR, this.onError, this);
  23573. }
  23574. unregisterListeners() {
  23575. const hls = this.hls;
  23576. if (!hls) {
  23577. return;
  23578. }
  23579. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23580. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23581. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23582. hls.off(Events.ERROR, this.onError, this);
  23583. }
  23584. startLoad() {
  23585. this.started = true;
  23586. this.clearTimeout();
  23587. if (this.enabled && this.uri) {
  23588. if (this.updated) {
  23589. const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  23590. if (ttl > 0) {
  23591. this.scheduleRefresh(this.uri, ttl);
  23592. return;
  23593. }
  23594. }
  23595. this.loadSteeringManifest(this.uri);
  23596. }
  23597. }
  23598. stopLoad() {
  23599. this.started = false;
  23600. if (this.loader) {
  23601. this.loader.destroy();
  23602. this.loader = null;
  23603. }
  23604. this.clearTimeout();
  23605. }
  23606. clearTimeout() {
  23607. if (this.reloadTimer !== -1) {
  23608. self.clearTimeout(this.reloadTimer);
  23609. this.reloadTimer = -1;
  23610. }
  23611. }
  23612. destroy() {
  23613. this.unregisterListeners();
  23614. this.stopLoad();
  23615. // @ts-ignore
  23616. this.hls = null;
  23617. this.levels = this.audioTracks = this.subtitleTracks = null;
  23618. }
  23619. removeLevel(levelToRemove) {
  23620. const levels = this.levels;
  23621. if (levels) {
  23622. this.levels = levels.filter(level => level !== levelToRemove);
  23623. }
  23624. }
  23625. onManifestLoading() {
  23626. this.stopLoad();
  23627. this.enabled = true;
  23628. this.timeToLoad = 300;
  23629. this.updated = 0;
  23630. this.uri = null;
  23631. this.pathwayId = '.';
  23632. this.levels = this.audioTracks = this.subtitleTracks = null;
  23633. }
  23634. onManifestLoaded(event, data) {
  23635. const {
  23636. contentSteering
  23637. } = data;
  23638. if (contentSteering === null) {
  23639. return;
  23640. }
  23641. this.pathwayId = contentSteering.pathwayId;
  23642. this.uri = contentSteering.uri;
  23643. if (this.started) {
  23644. this.startLoad();
  23645. }
  23646. }
  23647. onManifestParsed(event, data) {
  23648. this.audioTracks = data.audioTracks;
  23649. this.subtitleTracks = data.subtitleTracks;
  23650. }
  23651. onError(event, data) {
  23652. const {
  23653. errorAction
  23654. } = data;
  23655. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  23656. const levels = this.levels;
  23657. let pathwayPriority = this.pathwayPriority;
  23658. let errorPathway = this.pathwayId;
  23659. if (data.context) {
  23660. const {
  23661. groupId,
  23662. pathwayId,
  23663. type
  23664. } = data.context;
  23665. if (groupId && levels) {
  23666. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  23667. } else if (pathwayId) {
  23668. errorPathway = pathwayId;
  23669. }
  23670. }
  23671. if (!(errorPathway in this.penalizedPathways)) {
  23672. this.penalizedPathways[errorPathway] = performance.now();
  23673. }
  23674. if (!pathwayPriority && levels) {
  23675. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  23676. pathwayPriority = levels.reduce((pathways, level) => {
  23677. if (pathways.indexOf(level.pathwayId) === -1) {
  23678. pathways.push(level.pathwayId);
  23679. }
  23680. return pathways;
  23681. }, []);
  23682. }
  23683. if (pathwayPriority && pathwayPriority.length > 1) {
  23684. this.updatePathwayPriority(pathwayPriority);
  23685. errorAction.resolved = this.pathwayId !== errorPathway;
  23686. }
  23687. if (!errorAction.resolved) {
  23688. logger.warn(`Could not resolve ${data.details} ("${data.error.message}") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${JSON.stringify(pathwayPriority)} penalized: ${JSON.stringify(this.penalizedPathways)}`);
  23689. }
  23690. }
  23691. }
  23692. filterParsedLevels(levels) {
  23693. // Filter levels to only include those that are in the initial pathway
  23694. this.levels = levels;
  23695. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  23696. if (pathwayLevels.length === 0) {
  23697. const pathwayId = levels[0].pathwayId;
  23698. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  23699. pathwayLevels = this.getLevelsForPathway(pathwayId);
  23700. this.pathwayId = pathwayId;
  23701. }
  23702. if (pathwayLevels.length !== levels.length) {
  23703. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  23704. return pathwayLevels;
  23705. }
  23706. return levels;
  23707. }
  23708. getLevelsForPathway(pathwayId) {
  23709. if (this.levels === null) {
  23710. return [];
  23711. }
  23712. return this.levels.filter(level => pathwayId === level.pathwayId);
  23713. }
  23714. updatePathwayPriority(pathwayPriority) {
  23715. this.pathwayPriority = pathwayPriority;
  23716. let levels;
  23717. // Evaluate if we should remove the pathway from the penalized list
  23718. const penalizedPathways = this.penalizedPathways;
  23719. const now = performance.now();
  23720. Object.keys(penalizedPathways).forEach(pathwayId => {
  23721. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  23722. delete penalizedPathways[pathwayId];
  23723. }
  23724. });
  23725. for (let i = 0; i < pathwayPriority.length; i++) {
  23726. const pathwayId = pathwayPriority[i];
  23727. if (pathwayId in penalizedPathways) {
  23728. continue;
  23729. }
  23730. if (pathwayId === this.pathwayId) {
  23731. return;
  23732. }
  23733. const selectedIndex = this.hls.nextLoadLevel;
  23734. const selectedLevel = this.hls.levels[selectedIndex];
  23735. levels = this.getLevelsForPathway(pathwayId);
  23736. if (levels.length > 0) {
  23737. this.log(`Setting Pathway to "${pathwayId}"`);
  23738. this.pathwayId = pathwayId;
  23739. reassignFragmentLevelIndexes(levels);
  23740. this.hls.trigger(Events.LEVELS_UPDATED, {
  23741. levels
  23742. });
  23743. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  23744. const levelAfterChange = this.hls.levels[selectedIndex];
  23745. if (selectedLevel && levelAfterChange && this.levels) {
  23746. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  23747. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  23748. }
  23749. this.hls.nextLoadLevel = selectedIndex;
  23750. }
  23751. break;
  23752. }
  23753. }
  23754. }
  23755. getPathwayForGroupId(groupId, type, defaultPathway) {
  23756. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  23757. for (let i = 0; i < levels.length; i++) {
  23758. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  23759. return levels[i].pathwayId;
  23760. }
  23761. }
  23762. return defaultPathway;
  23763. }
  23764. clonePathways(pathwayClones) {
  23765. const levels = this.levels;
  23766. if (!levels) {
  23767. return;
  23768. }
  23769. const audioGroupCloneMap = {};
  23770. const subtitleGroupCloneMap = {};
  23771. pathwayClones.forEach(pathwayClone => {
  23772. const {
  23773. ID: cloneId,
  23774. 'BASE-ID': baseId,
  23775. 'URI-REPLACEMENT': uriReplacement
  23776. } = pathwayClone;
  23777. if (levels.some(level => level.pathwayId === cloneId)) {
  23778. return;
  23779. }
  23780. const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {
  23781. const attributes = new AttrList(baseLevel.attrs);
  23782. attributes['PATHWAY-ID'] = cloneId;
  23783. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  23784. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  23785. if (clonedAudioGroupId) {
  23786. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  23787. attributes.AUDIO = clonedAudioGroupId;
  23788. }
  23789. if (clonedSubtitleGroupId) {
  23790. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  23791. attributes.SUBTITLES = clonedSubtitleGroupId;
  23792. }
  23793. const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  23794. const clonedLevel = new Level({
  23795. attrs: attributes,
  23796. audioCodec: baseLevel.audioCodec,
  23797. bitrate: baseLevel.bitrate,
  23798. height: baseLevel.height,
  23799. name: baseLevel.name,
  23800. url,
  23801. videoCodec: baseLevel.videoCodec,
  23802. width: baseLevel.width
  23803. });
  23804. if (baseLevel.audioGroups) {
  23805. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  23806. clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  23807. }
  23808. }
  23809. if (baseLevel.subtitleGroups) {
  23810. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  23811. clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  23812. }
  23813. }
  23814. return clonedLevel;
  23815. });
  23816. levels.push(...clonedVariants);
  23817. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  23818. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  23819. });
  23820. }
  23821. loadSteeringManifest(uri) {
  23822. const config = this.hls.config;
  23823. const Loader = config.loader;
  23824. if (this.loader) {
  23825. this.loader.destroy();
  23826. }
  23827. this.loader = new Loader(config);
  23828. let url;
  23829. try {
  23830. url = new self.URL(uri);
  23831. } catch (error) {
  23832. this.enabled = false;
  23833. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  23834. return;
  23835. }
  23836. if (url.protocol !== 'data:') {
  23837. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  23838. url.searchParams.set('_HLS_pathway', this.pathwayId);
  23839. url.searchParams.set('_HLS_throughput', '' + throughput);
  23840. }
  23841. const context = {
  23842. responseType: 'json',
  23843. url: url.href
  23844. };
  23845. const loadPolicy = config.steeringManifestLoadPolicy.default;
  23846. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  23847. const loaderConfig = {
  23848. loadPolicy,
  23849. timeout: loadPolicy.maxLoadTimeMs,
  23850. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  23851. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  23852. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  23853. };
  23854. const callbacks = {
  23855. onSuccess: (response, stats, context, networkDetails) => {
  23856. this.log(`Loaded steering manifest: "${url}"`);
  23857. const steeringData = response.data;
  23858. if (steeringData.VERSION !== 1) {
  23859. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  23860. return;
  23861. }
  23862. this.updated = performance.now();
  23863. this.timeToLoad = steeringData.TTL;
  23864. const {
  23865. 'RELOAD-URI': reloadUri,
  23866. 'PATHWAY-CLONES': pathwayClones,
  23867. 'PATHWAY-PRIORITY': pathwayPriority
  23868. } = steeringData;
  23869. if (reloadUri) {
  23870. try {
  23871. this.uri = new self.URL(reloadUri, url).href;
  23872. } catch (error) {
  23873. this.enabled = false;
  23874. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  23875. return;
  23876. }
  23877. }
  23878. this.scheduleRefresh(this.uri || context.url);
  23879. if (pathwayClones) {
  23880. this.clonePathways(pathwayClones);
  23881. }
  23882. const loadedSteeringData = {
  23883. steeringManifest: steeringData,
  23884. url: url.toString()
  23885. };
  23886. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  23887. if (pathwayPriority) {
  23888. this.updatePathwayPriority(pathwayPriority);
  23889. }
  23890. },
  23891. onError: (error, context, networkDetails, stats) => {
  23892. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);
  23893. this.stopLoad();
  23894. if (error.code === 410) {
  23895. this.enabled = false;
  23896. this.log(`Steering manifest ${context.url} no longer available`);
  23897. return;
  23898. }
  23899. let ttl = this.timeToLoad * 1000;
  23900. if (error.code === 429) {
  23901. const loader = this.loader;
  23902. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  23903. const retryAfter = loader.getResponseHeader('Retry-After');
  23904. if (retryAfter) {
  23905. ttl = parseFloat(retryAfter) * 1000;
  23906. }
  23907. }
  23908. this.log(`Steering manifest ${context.url} rate limited`);
  23909. return;
  23910. }
  23911. this.scheduleRefresh(this.uri || context.url, ttl);
  23912. },
  23913. onTimeout: (stats, context, networkDetails) => {
  23914. this.log(`Timeout loading steering manifest (${context.url})`);
  23915. this.scheduleRefresh(this.uri || context.url);
  23916. }
  23917. };
  23918. this.log(`Requesting steering manifest: ${url}`);
  23919. this.loader.load(context, loaderConfig, callbacks);
  23920. }
  23921. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {
  23922. this.clearTimeout();
  23923. this.reloadTimer = self.setTimeout(() => {
  23924. var _this$hls;
  23925. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  23926. if (media && !media.ended) {
  23927. this.loadSteeringManifest(uri);
  23928. return;
  23929. }
  23930. this.scheduleRefresh(uri, this.timeToLoad * 1000);
  23931. }, ttlMs);
  23932. }
  23933. }
  23934. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  23935. if (!tracks) {
  23936. return;
  23937. }
  23938. Object.keys(groupCloneMap).forEach(audioGroupId => {
  23939. const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {
  23940. const clonedTrack = _extends({}, track);
  23941. clonedTrack.details = undefined;
  23942. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  23943. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  23944. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  23945. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  23946. return clonedTrack;
  23947. });
  23948. tracks.push(...clonedTracks);
  23949. });
  23950. }
  23951. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  23952. const {
  23953. HOST: host,
  23954. PARAMS: params,
  23955. [perOptionKey]: perOptionUris
  23956. } = uriReplacement;
  23957. let perVariantUri;
  23958. if (stableId) {
  23959. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  23960. if (perVariantUri) {
  23961. uri = perVariantUri;
  23962. }
  23963. }
  23964. const url = new self.URL(uri);
  23965. if (host && !perVariantUri) {
  23966. url.host = host;
  23967. }
  23968. if (params) {
  23969. Object.keys(params).sort().forEach(key => {
  23970. if (key) {
  23971. url.searchParams.set(key, params[key]);
  23972. }
  23973. });
  23974. }
  23975. return url.href;
  23976. }
  23977. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  23978. class XhrLoader {
  23979. constructor(config) {
  23980. this.xhrSetup = void 0;
  23981. this.requestTimeout = void 0;
  23982. this.retryTimeout = void 0;
  23983. this.retryDelay = void 0;
  23984. this.config = null;
  23985. this.callbacks = null;
  23986. this.context = null;
  23987. this.loader = null;
  23988. this.stats = void 0;
  23989. this.xhrSetup = config ? config.xhrSetup || null : null;
  23990. this.stats = new LoadStats();
  23991. this.retryDelay = 0;
  23992. }
  23993. destroy() {
  23994. this.callbacks = null;
  23995. this.abortInternal();
  23996. this.loader = null;
  23997. this.config = null;
  23998. this.context = null;
  23999. this.xhrSetup = null;
  24000. }
  24001. abortInternal() {
  24002. const loader = this.loader;
  24003. self.clearTimeout(this.requestTimeout);
  24004. self.clearTimeout(this.retryTimeout);
  24005. if (loader) {
  24006. loader.onreadystatechange = null;
  24007. loader.onprogress = null;
  24008. if (loader.readyState !== 4) {
  24009. this.stats.aborted = true;
  24010. loader.abort();
  24011. }
  24012. }
  24013. }
  24014. abort() {
  24015. var _this$callbacks;
  24016. this.abortInternal();
  24017. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  24018. this.callbacks.onAbort(this.stats, this.context, this.loader);
  24019. }
  24020. }
  24021. load(context, config, callbacks) {
  24022. if (this.stats.loading.start) {
  24023. throw new Error('Loader can only be used once.');
  24024. }
  24025. this.stats.loading.start = self.performance.now();
  24026. this.context = context;
  24027. this.config = config;
  24028. this.callbacks = callbacks;
  24029. this.loadInternal();
  24030. }
  24031. loadInternal() {
  24032. const {
  24033. config,
  24034. context
  24035. } = this;
  24036. if (!config || !context) {
  24037. return;
  24038. }
  24039. const xhr = this.loader = new self.XMLHttpRequest();
  24040. const stats = this.stats;
  24041. stats.loading.first = 0;
  24042. stats.loaded = 0;
  24043. stats.aborted = false;
  24044. const xhrSetup = this.xhrSetup;
  24045. if (xhrSetup) {
  24046. Promise.resolve().then(() => {
  24047. if (this.loader !== xhr || this.stats.aborted) return;
  24048. return xhrSetup(xhr, context.url);
  24049. }).catch(error => {
  24050. if (this.loader !== xhr || this.stats.aborted) return;
  24051. xhr.open('GET', context.url, true);
  24052. return xhrSetup(xhr, context.url);
  24053. }).then(() => {
  24054. if (this.loader !== xhr || this.stats.aborted) return;
  24055. this.openAndSendXhr(xhr, context, config);
  24056. }).catch(error => {
  24057. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  24058. this.callbacks.onError({
  24059. code: xhr.status,
  24060. text: error.message
  24061. }, context, xhr, stats);
  24062. return;
  24063. });
  24064. } else {
  24065. this.openAndSendXhr(xhr, context, config);
  24066. }
  24067. }
  24068. openAndSendXhr(xhr, context, config) {
  24069. if (!xhr.readyState) {
  24070. xhr.open('GET', context.url, true);
  24071. }
  24072. const headers = context.headers;
  24073. const {
  24074. maxTimeToFirstByteMs,
  24075. maxLoadTimeMs
  24076. } = config.loadPolicy;
  24077. if (headers) {
  24078. for (const header in headers) {
  24079. xhr.setRequestHeader(header, headers[header]);
  24080. }
  24081. }
  24082. if (context.rangeEnd) {
  24083. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  24084. }
  24085. xhr.onreadystatechange = this.readystatechange.bind(this);
  24086. xhr.onprogress = this.loadprogress.bind(this);
  24087. xhr.responseType = context.responseType;
  24088. // setup timeout before we perform request
  24089. self.clearTimeout(this.requestTimeout);
  24090. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  24091. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  24092. xhr.send();
  24093. }
  24094. readystatechange() {
  24095. const {
  24096. context,
  24097. loader: xhr,
  24098. stats
  24099. } = this;
  24100. if (!context || !xhr) {
  24101. return;
  24102. }
  24103. const readyState = xhr.readyState;
  24104. const config = this.config;
  24105. // don't proceed if xhr has been aborted
  24106. if (stats.aborted) {
  24107. return;
  24108. }
  24109. // >= HEADERS_RECEIVED
  24110. if (readyState >= 2) {
  24111. if (stats.loading.first === 0) {
  24112. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  24113. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  24114. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  24115. self.clearTimeout(this.requestTimeout);
  24116. config.timeout = config.loadPolicy.maxLoadTimeMs;
  24117. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  24118. }
  24119. }
  24120. if (readyState === 4) {
  24121. self.clearTimeout(this.requestTimeout);
  24122. xhr.onreadystatechange = null;
  24123. xhr.onprogress = null;
  24124. const status = xhr.status;
  24125. // http status between 200 to 299 are all successful
  24126. const useResponse = xhr.responseType !== 'text';
  24127. if (status >= 200 && status < 300 && (useResponse && xhr.response || xhr.responseText !== null)) {
  24128. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  24129. const data = useResponse ? xhr.response : xhr.responseText;
  24130. const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  24131. stats.loaded = stats.total = len;
  24132. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  24133. if (!this.callbacks) {
  24134. return;
  24135. }
  24136. const onProgress = this.callbacks.onProgress;
  24137. if (onProgress) {
  24138. onProgress(stats, context, data, xhr);
  24139. }
  24140. if (!this.callbacks) {
  24141. return;
  24142. }
  24143. const response = {
  24144. url: xhr.responseURL,
  24145. data: data,
  24146. code: status
  24147. };
  24148. this.callbacks.onSuccess(response, stats, context, xhr);
  24149. } else {
  24150. const retryConfig = config.loadPolicy.errorRetry;
  24151. const retryCount = stats.retry;
  24152. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  24153. const response = {
  24154. url: context.url,
  24155. data: undefined,
  24156. code: status
  24157. };
  24158. if (shouldRetry(retryConfig, retryCount, false, response)) {
  24159. this.retry(retryConfig);
  24160. } else {
  24161. logger.error(`${status} while loading ${context.url}`);
  24162. this.callbacks.onError({
  24163. code: status,
  24164. text: xhr.statusText
  24165. }, context, xhr, stats);
  24166. }
  24167. }
  24168. }
  24169. }
  24170. }
  24171. loadtimeout() {
  24172. if (!this.config) return;
  24173. const retryConfig = this.config.loadPolicy.timeoutRetry;
  24174. const retryCount = this.stats.retry;
  24175. if (shouldRetry(retryConfig, retryCount, true)) {
  24176. this.retry(retryConfig);
  24177. } else {
  24178. var _this$context;
  24179. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  24180. const callbacks = this.callbacks;
  24181. if (callbacks) {
  24182. this.abortInternal();
  24183. callbacks.onTimeout(this.stats, this.context, this.loader);
  24184. }
  24185. }
  24186. }
  24187. retry(retryConfig) {
  24188. const {
  24189. context,
  24190. stats
  24191. } = this;
  24192. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  24193. stats.retry++;
  24194. logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  24195. // abort and reset internal state
  24196. this.abortInternal();
  24197. this.loader = null;
  24198. // schedule retry
  24199. self.clearTimeout(this.retryTimeout);
  24200. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  24201. }
  24202. loadprogress(event) {
  24203. const stats = this.stats;
  24204. stats.loaded = event.loaded;
  24205. if (event.lengthComputable) {
  24206. stats.total = event.total;
  24207. }
  24208. }
  24209. getCacheAge() {
  24210. let result = null;
  24211. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  24212. const ageHeader = this.loader.getResponseHeader('age');
  24213. result = ageHeader ? parseFloat(ageHeader) : null;
  24214. }
  24215. return result;
  24216. }
  24217. getResponseHeader(name) {
  24218. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {
  24219. return this.loader.getResponseHeader(name);
  24220. }
  24221. return null;
  24222. }
  24223. }
  24224. function fetchSupported() {
  24225. if (
  24226. // @ts-ignore
  24227. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  24228. try {
  24229. new self.ReadableStream({}); // eslint-disable-line no-new
  24230. return true;
  24231. } catch (e) {
  24232. /* noop */
  24233. }
  24234. }
  24235. return false;
  24236. }
  24237. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  24238. class FetchLoader {
  24239. constructor(config /* HlsConfig */) {
  24240. this.fetchSetup = void 0;
  24241. this.requestTimeout = void 0;
  24242. this.request = null;
  24243. this.response = null;
  24244. this.controller = void 0;
  24245. this.context = null;
  24246. this.config = null;
  24247. this.callbacks = null;
  24248. this.stats = void 0;
  24249. this.loader = null;
  24250. this.fetchSetup = config.fetchSetup || getRequest;
  24251. this.controller = new self.AbortController();
  24252. this.stats = new LoadStats();
  24253. }
  24254. destroy() {
  24255. this.loader = this.callbacks = this.context = this.config = this.request = null;
  24256. this.abortInternal();
  24257. this.response = null;
  24258. // @ts-ignore
  24259. this.fetchSetup = this.controller = this.stats = null;
  24260. }
  24261. abortInternal() {
  24262. if (this.controller && !this.stats.loading.end) {
  24263. this.stats.aborted = true;
  24264. this.controller.abort();
  24265. }
  24266. }
  24267. abort() {
  24268. var _this$callbacks;
  24269. this.abortInternal();
  24270. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  24271. this.callbacks.onAbort(this.stats, this.context, this.response);
  24272. }
  24273. }
  24274. load(context, config, callbacks) {
  24275. const stats = this.stats;
  24276. if (stats.loading.start) {
  24277. throw new Error('Loader can only be used once.');
  24278. }
  24279. stats.loading.start = self.performance.now();
  24280. const initParams = getRequestParameters(context, this.controller.signal);
  24281. const onProgress = callbacks.onProgress;
  24282. const isArrayBuffer = context.responseType === 'arraybuffer';
  24283. const LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  24284. const {
  24285. maxTimeToFirstByteMs,
  24286. maxLoadTimeMs
  24287. } = config.loadPolicy;
  24288. this.context = context;
  24289. this.config = config;
  24290. this.callbacks = callbacks;
  24291. this.request = this.fetchSetup(context, initParams);
  24292. self.clearTimeout(this.requestTimeout);
  24293. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  24294. this.requestTimeout = self.setTimeout(() => {
  24295. this.abortInternal();
  24296. callbacks.onTimeout(stats, context, this.response);
  24297. }, config.timeout);
  24298. self.fetch(this.request).then(response => {
  24299. this.response = this.loader = response;
  24300. const first = Math.max(self.performance.now(), stats.loading.start);
  24301. self.clearTimeout(this.requestTimeout);
  24302. config.timeout = maxLoadTimeMs;
  24303. this.requestTimeout = self.setTimeout(() => {
  24304. this.abortInternal();
  24305. callbacks.onTimeout(stats, context, this.response);
  24306. }, maxLoadTimeMs - (first - stats.loading.start));
  24307. if (!response.ok) {
  24308. const {
  24309. status,
  24310. statusText
  24311. } = response;
  24312. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  24313. }
  24314. stats.loading.first = first;
  24315. stats.total = getContentLength(response.headers) || stats.total;
  24316. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  24317. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  24318. }
  24319. if (isArrayBuffer) {
  24320. return response.arrayBuffer();
  24321. }
  24322. if (context.responseType === 'json') {
  24323. return response.json();
  24324. }
  24325. return response.text();
  24326. }).then(responseData => {
  24327. const response = this.response;
  24328. if (!response) {
  24329. throw new Error('loader destroyed');
  24330. }
  24331. self.clearTimeout(this.requestTimeout);
  24332. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  24333. const total = responseData[LENGTH];
  24334. if (total) {
  24335. stats.loaded = stats.total = total;
  24336. }
  24337. const loaderResponse = {
  24338. url: response.url,
  24339. data: responseData,
  24340. code: response.status
  24341. };
  24342. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  24343. onProgress(stats, context, responseData, response);
  24344. }
  24345. callbacks.onSuccess(loaderResponse, stats, context, response);
  24346. }).catch(error => {
  24347. self.clearTimeout(this.requestTimeout);
  24348. if (stats.aborted) {
  24349. return;
  24350. }
  24351. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  24352. // when destroying, 'error' itself can be undefined
  24353. const code = !error ? 0 : error.code || 0;
  24354. const text = !error ? null : error.message;
  24355. callbacks.onError({
  24356. code,
  24357. text
  24358. }, context, error ? error.details : null, stats);
  24359. });
  24360. }
  24361. getCacheAge() {
  24362. let result = null;
  24363. if (this.response) {
  24364. const ageHeader = this.response.headers.get('age');
  24365. result = ageHeader ? parseFloat(ageHeader) : null;
  24366. }
  24367. return result;
  24368. }
  24369. getResponseHeader(name) {
  24370. return this.response ? this.response.headers.get(name) : null;
  24371. }
  24372. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  24373. const chunkCache = new ChunkCache();
  24374. const reader = response.body.getReader();
  24375. const pump = () => {
  24376. return reader.read().then(data => {
  24377. if (data.done) {
  24378. if (chunkCache.dataLength) {
  24379. onProgress(stats, context, chunkCache.flush(), response);
  24380. }
  24381. return Promise.resolve(new ArrayBuffer(0));
  24382. }
  24383. const chunk = data.value;
  24384. const len = chunk.length;
  24385. stats.loaded += len;
  24386. if (len < highWaterMark || chunkCache.dataLength) {
  24387. // The current chunk is too small to to be emitted or the cache already has data
  24388. // Push it to the cache
  24389. chunkCache.push(chunk);
  24390. if (chunkCache.dataLength >= highWaterMark) {
  24391. // flush in order to join the typed arrays
  24392. onProgress(stats, context, chunkCache.flush(), response);
  24393. }
  24394. } else {
  24395. // If there's nothing cached already, and the chache is large enough
  24396. // just emit the progress event
  24397. onProgress(stats, context, chunk, response);
  24398. }
  24399. return pump();
  24400. }).catch(() => {
  24401. /* aborted */
  24402. return Promise.reject();
  24403. });
  24404. };
  24405. return pump();
  24406. }
  24407. }
  24408. function getRequestParameters(context, signal) {
  24409. const initParams = {
  24410. method: 'GET',
  24411. mode: 'cors',
  24412. credentials: 'same-origin',
  24413. signal,
  24414. headers: new self.Headers(_extends({}, context.headers))
  24415. };
  24416. if (context.rangeEnd) {
  24417. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  24418. }
  24419. return initParams;
  24420. }
  24421. function getByteRangeLength(byteRangeHeader) {
  24422. const result = BYTERANGE.exec(byteRangeHeader);
  24423. if (result) {
  24424. return parseInt(result[2]) - parseInt(result[1]) + 1;
  24425. }
  24426. }
  24427. function getContentLength(headers) {
  24428. const contentRange = headers.get('Content-Range');
  24429. if (contentRange) {
  24430. const byteRangeLength = getByteRangeLength(contentRange);
  24431. if (isFiniteNumber(byteRangeLength)) {
  24432. return byteRangeLength;
  24433. }
  24434. }
  24435. const contentLength = headers.get('Content-Length');
  24436. if (contentLength) {
  24437. return parseInt(contentLength);
  24438. }
  24439. }
  24440. function getRequest(context, initParams) {
  24441. return new self.Request(context.url, initParams);
  24442. }
  24443. class FetchError extends Error {
  24444. constructor(message, code, details) {
  24445. super(message);
  24446. this.code = void 0;
  24447. this.details = void 0;
  24448. this.code = code;
  24449. this.details = details;
  24450. }
  24451. }
  24452. const WHITESPACE_CHAR = /\s/;
  24453. const Cues = {
  24454. newCue(track, startTime, endTime, captionScreen) {
  24455. const result = [];
  24456. let row;
  24457. // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
  24458. let cue;
  24459. let indenting;
  24460. let indent;
  24461. let text;
  24462. const Cue = self.VTTCue || self.TextTrackCue;
  24463. for (let r = 0; r < captionScreen.rows.length; r++) {
  24464. row = captionScreen.rows[r];
  24465. indenting = true;
  24466. indent = 0;
  24467. text = '';
  24468. if (!row.isEmpty()) {
  24469. var _track$cues;
  24470. for (let c = 0; c < row.chars.length; c++) {
  24471. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  24472. indent++;
  24473. } else {
  24474. text += row.chars[c].uchar;
  24475. indenting = false;
  24476. }
  24477. }
  24478. // To be used for cleaning-up orphaned roll-up captions
  24479. row.cueStartTime = startTime;
  24480. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  24481. if (startTime === endTime) {
  24482. endTime += 0.0001;
  24483. }
  24484. if (indent >= 16) {
  24485. indent--;
  24486. } else {
  24487. indent++;
  24488. }
  24489. const cueText = fixLineBreaks(text.trim());
  24490. const id = generateCueId(startTime, endTime, cueText);
  24491. // If this cue already exists in the track do not push it
  24492. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  24493. cue = new Cue(startTime, endTime, cueText);
  24494. cue.id = id;
  24495. cue.line = r + 1;
  24496. cue.align = 'left';
  24497. // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
  24498. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  24499. // Firefox throws an exception and captions break with out of bounds 0-100 values
  24500. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  24501. result.push(cue);
  24502. }
  24503. }
  24504. }
  24505. if (track && result.length) {
  24506. // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
  24507. result.sort((cueA, cueB) => {
  24508. if (cueA.line === 'auto' || cueB.line === 'auto') {
  24509. return 0;
  24510. }
  24511. if (cueA.line > 8 && cueB.line > 8) {
  24512. return cueB.line - cueA.line;
  24513. }
  24514. return cueA.line - cueB.line;
  24515. });
  24516. result.forEach(cue => addCueToTrack(track, cue));
  24517. }
  24518. return result;
  24519. }
  24520. };
  24521. /**
  24522. * @deprecated use fragLoadPolicy.default
  24523. */
  24524. /**
  24525. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  24526. */
  24527. const defaultLoadPolicy = {
  24528. maxTimeToFirstByteMs: 8000,
  24529. maxLoadTimeMs: 20000,
  24530. timeoutRetry: null,
  24531. errorRetry: null
  24532. };
  24533. /**
  24534. * @ignore
  24535. * If possible, keep hlsDefaultConfig shallow
  24536. * It is cloned whenever a new Hls instance is created, by keeping the config
  24537. * shallow the properties are cloned, and we don't end up manipulating the default
  24538. */
  24539. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  24540. autoStartLoad: true,
  24541. // used by stream-controller
  24542. startPosition: -1,
  24543. // used by stream-controller
  24544. defaultAudioCodec: undefined,
  24545. // used by stream-controller
  24546. debug: false,
  24547. // used by logger
  24548. capLevelOnFPSDrop: false,
  24549. // used by fps-controller
  24550. capLevelToPlayerSize: false,
  24551. // used by cap-level-controller
  24552. ignoreDevicePixelRatio: false,
  24553. // used by cap-level-controller
  24554. preferManagedMediaSource: true,
  24555. initialLiveManifestSize: 1,
  24556. // used by stream-controller
  24557. maxBufferLength: 30,
  24558. // used by stream-controller
  24559. backBufferLength: Infinity,
  24560. // used by buffer-controller
  24561. frontBufferFlushThreshold: Infinity,
  24562. maxBufferSize: 60 * 1000 * 1000,
  24563. // used by stream-controller
  24564. maxBufferHole: 0.1,
  24565. // used by stream-controller
  24566. highBufferWatchdogPeriod: 2,
  24567. // used by stream-controller
  24568. nudgeOffset: 0.1,
  24569. // used by stream-controller
  24570. nudgeMaxRetry: 3,
  24571. // used by stream-controller
  24572. maxFragLookUpTolerance: 0.25,
  24573. // used by stream-controller
  24574. liveSyncDurationCount: 3,
  24575. // used by latency-controller
  24576. liveMaxLatencyDurationCount: Infinity,
  24577. // used by latency-controller
  24578. liveSyncDuration: undefined,
  24579. // used by latency-controller
  24580. liveMaxLatencyDuration: undefined,
  24581. // used by latency-controller
  24582. maxLiveSyncPlaybackRate: 1,
  24583. // used by latency-controller
  24584. liveDurationInfinity: false,
  24585. // used by buffer-controller
  24586. /**
  24587. * @deprecated use backBufferLength
  24588. */
  24589. liveBackBufferLength: null,
  24590. // used by buffer-controller
  24591. maxMaxBufferLength: 600,
  24592. // used by stream-controller
  24593. enableWorker: true,
  24594. // used by transmuxer
  24595. workerPath: null,
  24596. // used by transmuxer
  24597. enableSoftwareAES: true,
  24598. // used by decrypter
  24599. startLevel: undefined,
  24600. // used by level-controller
  24601. startFragPrefetch: false,
  24602. // used by stream-controller
  24603. fpsDroppedMonitoringPeriod: 5000,
  24604. // used by fps-controller
  24605. fpsDroppedMonitoringThreshold: 0.2,
  24606. // used by fps-controller
  24607. appendErrorMaxRetry: 3,
  24608. // used by buffer-controller
  24609. loader: XhrLoader,
  24610. // loader: FetchLoader,
  24611. fLoader: undefined,
  24612. // used by fragment-loader
  24613. pLoader: undefined,
  24614. // used by playlist-loader
  24615. xhrSetup: undefined,
  24616. // used by xhr-loader
  24617. licenseXhrSetup: undefined,
  24618. // used by eme-controller
  24619. licenseResponseCallback: undefined,
  24620. // used by eme-controller
  24621. abrController: AbrController,
  24622. bufferController: BufferController,
  24623. capLevelController: CapLevelController,
  24624. errorController: ErrorController,
  24625. fpsController: FPSController,
  24626. stretchShortVideoTrack: false,
  24627. // used by mp4-remuxer
  24628. maxAudioFramesDrift: 1,
  24629. // used by mp4-remuxer
  24630. forceKeyFrameOnDiscontinuity: true,
  24631. // used by ts-demuxer
  24632. abrEwmaFastLive: 3,
  24633. // used by abr-controller
  24634. abrEwmaSlowLive: 9,
  24635. // used by abr-controller
  24636. abrEwmaFastVoD: 3,
  24637. // used by abr-controller
  24638. abrEwmaSlowVoD: 9,
  24639. // used by abr-controller
  24640. abrEwmaDefaultEstimate: 5e5,
  24641. // 500 kbps // used by abr-controller
  24642. abrEwmaDefaultEstimateMax: 5e6,
  24643. // 5 mbps
  24644. abrBandWidthFactor: 0.95,
  24645. // used by abr-controller
  24646. abrBandWidthUpFactor: 0.7,
  24647. // used by abr-controller
  24648. abrMaxWithRealBitrate: false,
  24649. // used by abr-controller
  24650. maxStarvationDelay: 4,
  24651. // used by abr-controller
  24652. maxLoadingDelay: 4,
  24653. // used by abr-controller
  24654. minAutoBitrate: 0,
  24655. // used by hls
  24656. emeEnabled: false,
  24657. // used by eme-controller
  24658. widevineLicenseUrl: undefined,
  24659. // used by eme-controller
  24660. drmSystems: {},
  24661. // used by eme-controller
  24662. drmSystemOptions: {},
  24663. // used by eme-controller
  24664. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess ,
  24665. // used by eme-controller
  24666. testBandwidth: true,
  24667. progressive: false,
  24668. lowLatencyMode: true,
  24669. cmcd: undefined,
  24670. enableDateRangeMetadataCues: true,
  24671. enableEmsgMetadataCues: true,
  24672. enableID3MetadataCues: true,
  24673. useMediaCapabilities: true,
  24674. certLoadPolicy: {
  24675. default: defaultLoadPolicy
  24676. },
  24677. keyLoadPolicy: {
  24678. default: {
  24679. maxTimeToFirstByteMs: 8000,
  24680. maxLoadTimeMs: 20000,
  24681. timeoutRetry: {
  24682. maxNumRetry: 1,
  24683. retryDelayMs: 1000,
  24684. maxRetryDelayMs: 20000,
  24685. backoff: 'linear'
  24686. },
  24687. errorRetry: {
  24688. maxNumRetry: 8,
  24689. retryDelayMs: 1000,
  24690. maxRetryDelayMs: 20000,
  24691. backoff: 'linear'
  24692. }
  24693. }
  24694. },
  24695. manifestLoadPolicy: {
  24696. default: {
  24697. maxTimeToFirstByteMs: Infinity,
  24698. maxLoadTimeMs: 20000,
  24699. timeoutRetry: {
  24700. maxNumRetry: 2,
  24701. retryDelayMs: 0,
  24702. maxRetryDelayMs: 0
  24703. },
  24704. errorRetry: {
  24705. maxNumRetry: 1,
  24706. retryDelayMs: 1000,
  24707. maxRetryDelayMs: 8000
  24708. }
  24709. }
  24710. },
  24711. playlistLoadPolicy: {
  24712. default: {
  24713. maxTimeToFirstByteMs: 10000,
  24714. maxLoadTimeMs: 20000,
  24715. timeoutRetry: {
  24716. maxNumRetry: 2,
  24717. retryDelayMs: 0,
  24718. maxRetryDelayMs: 0
  24719. },
  24720. errorRetry: {
  24721. maxNumRetry: 2,
  24722. retryDelayMs: 1000,
  24723. maxRetryDelayMs: 8000
  24724. }
  24725. }
  24726. },
  24727. fragLoadPolicy: {
  24728. default: {
  24729. maxTimeToFirstByteMs: 10000,
  24730. maxLoadTimeMs: 120000,
  24731. timeoutRetry: {
  24732. maxNumRetry: 4,
  24733. retryDelayMs: 0,
  24734. maxRetryDelayMs: 0
  24735. },
  24736. errorRetry: {
  24737. maxNumRetry: 6,
  24738. retryDelayMs: 1000,
  24739. maxRetryDelayMs: 8000
  24740. }
  24741. }
  24742. },
  24743. steeringManifestLoadPolicy: {
  24744. default: {
  24745. maxTimeToFirstByteMs: 10000,
  24746. maxLoadTimeMs: 20000,
  24747. timeoutRetry: {
  24748. maxNumRetry: 2,
  24749. retryDelayMs: 0,
  24750. maxRetryDelayMs: 0
  24751. },
  24752. errorRetry: {
  24753. maxNumRetry: 1,
  24754. retryDelayMs: 1000,
  24755. maxRetryDelayMs: 8000
  24756. }
  24757. }
  24758. },
  24759. // These default settings are deprecated in favor of the above policies
  24760. // and are maintained for backwards compatibility
  24761. manifestLoadingTimeOut: 10000,
  24762. manifestLoadingMaxRetry: 1,
  24763. manifestLoadingRetryDelay: 1000,
  24764. manifestLoadingMaxRetryTimeout: 64000,
  24765. levelLoadingTimeOut: 10000,
  24766. levelLoadingMaxRetry: 4,
  24767. levelLoadingRetryDelay: 1000,
  24768. levelLoadingMaxRetryTimeout: 64000,
  24769. fragLoadingTimeOut: 20000,
  24770. fragLoadingMaxRetry: 6,
  24771. fragLoadingRetryDelay: 1000,
  24772. fragLoadingMaxRetryTimeout: 64000
  24773. }, timelineConfig()), {}, {
  24774. subtitleStreamController: SubtitleStreamController ,
  24775. subtitleTrackController: SubtitleTrackController ,
  24776. timelineController: TimelineController ,
  24777. audioStreamController: AudioStreamController ,
  24778. audioTrackController: AudioTrackController ,
  24779. emeController: EMEController ,
  24780. cmcdController: CMCDController ,
  24781. contentSteeringController: ContentSteeringController
  24782. });
  24783. function timelineConfig() {
  24784. return {
  24785. cueHandler: Cues,
  24786. // used by timeline-controller
  24787. enableWebVTT: true,
  24788. // used by timeline-controller
  24789. enableIMSC1: true,
  24790. // used by timeline-controller
  24791. enableCEA708Captions: true,
  24792. // used by timeline-controller
  24793. captionsTextTrack1Label: 'English',
  24794. // used by timeline-controller
  24795. captionsTextTrack1LanguageCode: 'en',
  24796. // used by timeline-controller
  24797. captionsTextTrack2Label: 'Spanish',
  24798. // used by timeline-controller
  24799. captionsTextTrack2LanguageCode: 'es',
  24800. // used by timeline-controller
  24801. captionsTextTrack3Label: 'Unknown CC',
  24802. // used by timeline-controller
  24803. captionsTextTrack3LanguageCode: '',
  24804. // used by timeline-controller
  24805. captionsTextTrack4Label: 'Unknown CC',
  24806. // used by timeline-controller
  24807. captionsTextTrack4LanguageCode: '',
  24808. // used by timeline-controller
  24809. renderTextTracksNatively: true
  24810. };
  24811. }
  24812. /**
  24813. * @ignore
  24814. */
  24815. function mergeConfig(defaultConfig, userConfig) {
  24816. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  24817. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  24818. }
  24819. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  24820. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  24821. }
  24822. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  24823. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  24824. }
  24825. const defaultsCopy = deepCpy(defaultConfig);
  24826. // Backwards compatibility with deprecated config values
  24827. const deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  24828. const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  24829. deprecatedSettingTypes.forEach(type => {
  24830. const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;
  24831. const policyNotSet = userConfig[policyName] === undefined;
  24832. const report = [];
  24833. deprecatedSettings.forEach(setting => {
  24834. const deprecatedSetting = `${type}Loading${setting}`;
  24835. const value = userConfig[deprecatedSetting];
  24836. if (value !== undefined && policyNotSet) {
  24837. report.push(deprecatedSetting);
  24838. const settings = defaultsCopy[policyName].default;
  24839. userConfig[policyName] = {
  24840. default: settings
  24841. };
  24842. switch (setting) {
  24843. case 'TimeOut':
  24844. settings.maxLoadTimeMs = value;
  24845. settings.maxTimeToFirstByteMs = value;
  24846. break;
  24847. case 'MaxRetry':
  24848. settings.errorRetry.maxNumRetry = value;
  24849. settings.timeoutRetry.maxNumRetry = value;
  24850. break;
  24851. case 'RetryDelay':
  24852. settings.errorRetry.retryDelayMs = value;
  24853. settings.timeoutRetry.retryDelayMs = value;
  24854. break;
  24855. case 'MaxRetryTimeout':
  24856. settings.errorRetry.maxRetryDelayMs = value;
  24857. settings.timeoutRetry.maxRetryDelayMs = value;
  24858. break;
  24859. }
  24860. }
  24861. });
  24862. if (report.length) {
  24863. logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${JSON.stringify(userConfig[policyName])}`);
  24864. }
  24865. });
  24866. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  24867. }
  24868. function deepCpy(obj) {
  24869. if (obj && typeof obj === 'object') {
  24870. if (Array.isArray(obj)) {
  24871. return obj.map(deepCpy);
  24872. }
  24873. return Object.keys(obj).reduce((result, key) => {
  24874. result[key] = deepCpy(obj[key]);
  24875. return result;
  24876. }, {});
  24877. }
  24878. return obj;
  24879. }
  24880. /**
  24881. * @ignore
  24882. */
  24883. function enableStreamingMode(config) {
  24884. const currentLoader = config.loader;
  24885. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  24886. // If a developer has configured their own loader, respect that choice
  24887. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  24888. config.progressive = false;
  24889. } else {
  24890. const canStreamProgressively = fetchSupported();
  24891. if (canStreamProgressively) {
  24892. config.loader = FetchLoader;
  24893. config.progressive = true;
  24894. config.enableSoftwareAES = true;
  24895. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  24896. }
  24897. }
  24898. }
  24899. let chromeOrFirefox;
  24900. class LevelController extends BasePlaylistController {
  24901. constructor(hls, contentSteeringController) {
  24902. super(hls, '[level-controller]');
  24903. this._levels = [];
  24904. this._firstLevel = -1;
  24905. this._maxAutoLevel = -1;
  24906. this._startLevel = void 0;
  24907. this.currentLevel = null;
  24908. this.currentLevelIndex = -1;
  24909. this.manualLevelIndex = -1;
  24910. this.steering = void 0;
  24911. this.onParsedComplete = void 0;
  24912. this.steering = contentSteeringController;
  24913. this._registerListeners();
  24914. }
  24915. _registerListeners() {
  24916. const {
  24917. hls
  24918. } = this;
  24919. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24920. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24921. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24922. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  24923. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  24924. hls.on(Events.ERROR, this.onError, this);
  24925. }
  24926. _unregisterListeners() {
  24927. const {
  24928. hls
  24929. } = this;
  24930. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24931. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24932. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24933. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  24934. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  24935. hls.off(Events.ERROR, this.onError, this);
  24936. }
  24937. destroy() {
  24938. this._unregisterListeners();
  24939. this.steering = null;
  24940. this.resetLevels();
  24941. super.destroy();
  24942. }
  24943. stopLoad() {
  24944. const levels = this._levels;
  24945. // clean up live level details to force reload them, and reset load errors
  24946. levels.forEach(level => {
  24947. level.loadError = 0;
  24948. level.fragmentError = 0;
  24949. });
  24950. super.stopLoad();
  24951. }
  24952. resetLevels() {
  24953. this._startLevel = undefined;
  24954. this.manualLevelIndex = -1;
  24955. this.currentLevelIndex = -1;
  24956. this.currentLevel = null;
  24957. this._levels = [];
  24958. this._maxAutoLevel = -1;
  24959. }
  24960. onManifestLoading(event, data) {
  24961. this.resetLevels();
  24962. }
  24963. onManifestLoaded(event, data) {
  24964. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  24965. const levels = [];
  24966. const redundantSet = {};
  24967. const generatePathwaySet = {};
  24968. let resolutionFound = false;
  24969. let videoCodecFound = false;
  24970. let audioCodecFound = false;
  24971. data.levels.forEach(levelParsed => {
  24972. var _audioCodec, _videoCodec;
  24973. const attributes = levelParsed.attrs;
  24974. // erase audio codec info if browser does not support mp4a.40.34.
  24975. // demuxer will autodetect codec and fallback to mpeg/audio
  24976. let {
  24977. audioCodec,
  24978. videoCodec
  24979. } = levelParsed;
  24980. if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf('mp4a.40.34')) !== -1) {
  24981. chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent));
  24982. if (chromeOrFirefox) {
  24983. levelParsed.audioCodec = audioCodec = undefined;
  24984. }
  24985. }
  24986. if (audioCodec) {
  24987. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource);
  24988. }
  24989. if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {
  24990. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  24991. }
  24992. // only keep levels with supported audio/video codecs
  24993. const {
  24994. width,
  24995. height,
  24996. unknownCodecs
  24997. } = levelParsed;
  24998. resolutionFound || (resolutionFound = !!(width && height));
  24999. videoCodecFound || (videoCodecFound = !!videoCodec);
  25000. audioCodecFound || (audioCodecFound = !!audioCodec);
  25001. if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, 'audio', preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, 'video', preferManagedMediaSource)) {
  25002. return;
  25003. }
  25004. const {
  25005. CODECS,
  25006. 'FRAME-RATE': FRAMERATE,
  25007. 'HDCP-LEVEL': HDCP,
  25008. 'PATHWAY-ID': PATHWAY,
  25009. RESOLUTION,
  25010. 'VIDEO-RANGE': VIDEO_RANGE
  25011. } = attributes;
  25012. const contentSteeringPrefix = `${PATHWAY || '.'}-`;
  25013. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  25014. if (!redundantSet[levelKey]) {
  25015. const level = new Level(levelParsed);
  25016. redundantSet[levelKey] = level;
  25017. generatePathwaySet[levelKey] = 1;
  25018. levels.push(level);
  25019. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  25020. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  25021. // Content Steering controller to handles Pathway fallback on error
  25022. const pathwayCount = generatePathwaySet[levelKey] += 1;
  25023. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  25024. const level = new Level(levelParsed);
  25025. redundantSet[levelKey] = level;
  25026. levels.push(level);
  25027. } else {
  25028. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  25029. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  25030. }
  25031. });
  25032. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  25033. }
  25034. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  25035. let audioTracks = [];
  25036. let subtitleTracks = [];
  25037. let levels = filteredLevels;
  25038. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  25039. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  25040. levels = levels.filter(({
  25041. videoCodec,
  25042. videoRange,
  25043. width,
  25044. height
  25045. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  25046. }
  25047. if (levels.length === 0) {
  25048. // Dispatch error after MANIFEST_LOADED is done propagating
  25049. Promise.resolve().then(() => {
  25050. if (this.hls) {
  25051. if (data.levels.length) {
  25052. this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(data.levels[0].attrs)}`);
  25053. }
  25054. const error = new Error('no level with compatible codecs found in manifest');
  25055. this.hls.trigger(Events.ERROR, {
  25056. type: ErrorTypes.MEDIA_ERROR,
  25057. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  25058. fatal: true,
  25059. url: data.url,
  25060. error,
  25061. reason: error.message
  25062. });
  25063. }
  25064. });
  25065. return;
  25066. }
  25067. if (data.audioTracks) {
  25068. const {
  25069. preferManagedMediaSource
  25070. } = this.hls.config;
  25071. audioTracks = data.audioTracks.filter(track => !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, 'audio', preferManagedMediaSource));
  25072. // Assign ids after filtering as array indices by group-id
  25073. assignTrackIdsByGroup(audioTracks);
  25074. }
  25075. if (data.subtitles) {
  25076. subtitleTracks = data.subtitles;
  25077. assignTrackIdsByGroup(subtitleTracks);
  25078. }
  25079. // start bitrate is the first bitrate of the manifest
  25080. const unsortedLevels = levels.slice(0);
  25081. // sort levels from lowest to highest
  25082. levels.sort((a, b) => {
  25083. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  25084. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  25085. }
  25086. // sort on height before bitrate for cap-level-controller
  25087. if (resolutionFound && a.height !== b.height) {
  25088. return a.height - b.height;
  25089. }
  25090. if (a.frameRate !== b.frameRate) {
  25091. return a.frameRate - b.frameRate;
  25092. }
  25093. if (a.videoRange !== b.videoRange) {
  25094. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  25095. }
  25096. if (a.videoCodec !== b.videoCodec) {
  25097. const valueA = videoCodecPreferenceValue(a.videoCodec);
  25098. const valueB = videoCodecPreferenceValue(b.videoCodec);
  25099. if (valueA !== valueB) {
  25100. return valueB - valueA;
  25101. }
  25102. }
  25103. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  25104. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  25105. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  25106. if (valueA !== valueB) {
  25107. return valueB - valueA;
  25108. }
  25109. }
  25110. if (a.averageBitrate !== b.averageBitrate) {
  25111. return a.averageBitrate - b.averageBitrate;
  25112. }
  25113. return 0;
  25114. });
  25115. let firstLevelInPlaylist = unsortedLevels[0];
  25116. if (this.steering) {
  25117. levels = this.steering.filterParsedLevels(levels);
  25118. if (levels.length !== unsortedLevels.length) {
  25119. for (let i = 0; i < unsortedLevels.length; i++) {
  25120. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  25121. firstLevelInPlaylist = unsortedLevels[i];
  25122. break;
  25123. }
  25124. }
  25125. }
  25126. }
  25127. this._levels = levels;
  25128. // find index of first level in sorted levels
  25129. for (let i = 0; i < levels.length; i++) {
  25130. if (levels[i] === firstLevelInPlaylist) {
  25131. var _this$hls$userConfig;
  25132. this._firstLevel = i;
  25133. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  25134. const bandwidthEstimate = this.hls.bandwidthEstimate;
  25135. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  25136. // Update default bwe to first variant bitrate as long it has not been configured or set
  25137. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  25138. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  25139. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) {
  25140. this.hls.bandwidthEstimate = startingBwEstimate;
  25141. }
  25142. }
  25143. break;
  25144. }
  25145. }
  25146. // Audio is only alternate if manifest include a URI along with the audio group tag,
  25147. // and this is not an audio-only stream where levels contain audio-only
  25148. const audioOnly = audioCodecFound && !videoCodecFound;
  25149. const edata = {
  25150. levels,
  25151. audioTracks,
  25152. subtitleTracks,
  25153. sessionData: data.sessionData,
  25154. sessionKeys: data.sessionKeys,
  25155. firstLevel: this._firstLevel,
  25156. stats: data.stats,
  25157. audio: audioCodecFound,
  25158. video: videoCodecFound,
  25159. altAudio: !audioOnly && audioTracks.some(t => !!t.url)
  25160. };
  25161. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  25162. // Initiate loading after all controllers have received MANIFEST_PARSED
  25163. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  25164. this.hls.startLoad(this.hls.config.startPosition);
  25165. }
  25166. }
  25167. get levels() {
  25168. if (this._levels.length === 0) {
  25169. return null;
  25170. }
  25171. return this._levels;
  25172. }
  25173. get level() {
  25174. return this.currentLevelIndex;
  25175. }
  25176. set level(newLevel) {
  25177. const levels = this._levels;
  25178. if (levels.length === 0) {
  25179. return;
  25180. }
  25181. // check if level idx is valid
  25182. if (newLevel < 0 || newLevel >= levels.length) {
  25183. // invalid level id given, trigger error
  25184. const error = new Error('invalid level idx');
  25185. const fatal = newLevel < 0;
  25186. this.hls.trigger(Events.ERROR, {
  25187. type: ErrorTypes.OTHER_ERROR,
  25188. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  25189. level: newLevel,
  25190. fatal,
  25191. error,
  25192. reason: error.message
  25193. });
  25194. if (fatal) {
  25195. return;
  25196. }
  25197. newLevel = Math.min(newLevel, levels.length - 1);
  25198. }
  25199. const lastLevelIndex = this.currentLevelIndex;
  25200. const lastLevel = this.currentLevel;
  25201. const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  25202. const level = levels[newLevel];
  25203. const pathwayId = level.attrs['PATHWAY-ID'];
  25204. this.currentLevelIndex = newLevel;
  25205. this.currentLevel = level;
  25206. if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) {
  25207. return;
  25208. }
  25209. 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 : ''}`);
  25210. const levelSwitchingData = {
  25211. level: newLevel,
  25212. attrs: level.attrs,
  25213. details: level.details,
  25214. bitrate: level.bitrate,
  25215. averageBitrate: level.averageBitrate,
  25216. maxBitrate: level.maxBitrate,
  25217. realBitrate: level.realBitrate,
  25218. width: level.width,
  25219. height: level.height,
  25220. codecSet: level.codecSet,
  25221. audioCodec: level.audioCodec,
  25222. videoCodec: level.videoCodec,
  25223. audioGroups: level.audioGroups,
  25224. subtitleGroups: level.subtitleGroups,
  25225. loaded: level.loaded,
  25226. loadError: level.loadError,
  25227. fragmentError: level.fragmentError,
  25228. name: level.name,
  25229. id: level.id,
  25230. uri: level.uri,
  25231. url: level.url,
  25232. urlId: 0,
  25233. audioGroupIds: level.audioGroupIds,
  25234. textGroupIds: level.textGroupIds
  25235. };
  25236. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  25237. // check if we need to load playlist for this level
  25238. const levelDetails = level.details;
  25239. if (!levelDetails || levelDetails.live) {
  25240. // level not retrieved yet, or live playlist we need to (re)load it
  25241. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  25242. this.loadPlaylist(hlsUrlParameters);
  25243. }
  25244. }
  25245. get manualLevel() {
  25246. return this.manualLevelIndex;
  25247. }
  25248. set manualLevel(newLevel) {
  25249. this.manualLevelIndex = newLevel;
  25250. if (this._startLevel === undefined) {
  25251. this._startLevel = newLevel;
  25252. }
  25253. if (newLevel !== -1) {
  25254. this.level = newLevel;
  25255. }
  25256. }
  25257. get firstLevel() {
  25258. return this._firstLevel;
  25259. }
  25260. set firstLevel(newLevel) {
  25261. this._firstLevel = newLevel;
  25262. }
  25263. get startLevel() {
  25264. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  25265. if (this._startLevel === undefined) {
  25266. const configStartLevel = this.hls.config.startLevel;
  25267. if (configStartLevel !== undefined) {
  25268. return configStartLevel;
  25269. }
  25270. return this.hls.firstAutoLevel;
  25271. }
  25272. return this._startLevel;
  25273. }
  25274. set startLevel(newLevel) {
  25275. this._startLevel = newLevel;
  25276. }
  25277. onError(event, data) {
  25278. if (data.fatal || !data.context) {
  25279. return;
  25280. }
  25281. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  25282. this.checkRetry(data);
  25283. }
  25284. }
  25285. // reset errors on the successful load of a fragment
  25286. onFragBuffered(event, {
  25287. frag
  25288. }) {
  25289. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  25290. const el = frag.elementaryStreams;
  25291. if (!Object.keys(el).some(type => !!el[type])) {
  25292. return;
  25293. }
  25294. const level = this._levels[frag.level];
  25295. if (level != null && level.loadError) {
  25296. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  25297. level.loadError = 0;
  25298. }
  25299. }
  25300. }
  25301. onLevelLoaded(event, data) {
  25302. var _data$deliveryDirecti2;
  25303. const {
  25304. level,
  25305. details
  25306. } = data;
  25307. const curLevel = this._levels[level];
  25308. if (!curLevel) {
  25309. var _data$deliveryDirecti;
  25310. this.warn(`Invalid level index ${level}`);
  25311. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  25312. details.deltaUpdateFailed = true;
  25313. }
  25314. return;
  25315. }
  25316. // only process level loaded events matching with expected level
  25317. if (level === this.currentLevelIndex) {
  25318. // reset level load error counter on successful level loaded only if there is no issues with fragments
  25319. if (curLevel.fragmentError === 0) {
  25320. curLevel.loadError = 0;
  25321. }
  25322. this.playlistLoaded(level, data, curLevel.details);
  25323. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  25324. // received a delta playlist update that cannot be merged
  25325. details.deltaUpdateFailed = true;
  25326. }
  25327. }
  25328. loadPlaylist(hlsUrlParameters) {
  25329. super.loadPlaylist();
  25330. const currentLevelIndex = this.currentLevelIndex;
  25331. const currentLevel = this.currentLevel;
  25332. if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {
  25333. let url = currentLevel.uri;
  25334. if (hlsUrlParameters) {
  25335. try {
  25336. url = hlsUrlParameters.addDirectives(url);
  25337. } catch (error) {
  25338. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  25339. }
  25340. }
  25341. const pathwayId = currentLevel.attrs['PATHWAY-ID'];
  25342. this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''} with${pathwayId ? ' Pathway ' + pathwayId : ''} ${url}`);
  25343. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  25344. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  25345. this.clearTimer();
  25346. this.hls.trigger(Events.LEVEL_LOADING, {
  25347. url,
  25348. level: currentLevelIndex,
  25349. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  25350. id: 0,
  25351. // Deprecated Level urlId
  25352. deliveryDirectives: hlsUrlParameters || null
  25353. });
  25354. }
  25355. }
  25356. get nextLoadLevel() {
  25357. if (this.manualLevelIndex !== -1) {
  25358. return this.manualLevelIndex;
  25359. } else {
  25360. return this.hls.nextAutoLevel;
  25361. }
  25362. }
  25363. set nextLoadLevel(nextLevel) {
  25364. this.level = nextLevel;
  25365. if (this.manualLevelIndex === -1) {
  25366. this.hls.nextAutoLevel = nextLevel;
  25367. }
  25368. }
  25369. removeLevel(levelIndex) {
  25370. var _this$currentLevel;
  25371. const levels = this._levels.filter((level, index) => {
  25372. if (index !== levelIndex) {
  25373. return true;
  25374. }
  25375. if (this.steering) {
  25376. this.steering.removeLevel(level);
  25377. }
  25378. if (level === this.currentLevel) {
  25379. this.currentLevel = null;
  25380. this.currentLevelIndex = -1;
  25381. if (level.details) {
  25382. level.details.fragments.forEach(f => f.level = -1);
  25383. }
  25384. }
  25385. return false;
  25386. });
  25387. reassignFragmentLevelIndexes(levels);
  25388. this._levels = levels;
  25389. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  25390. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  25391. }
  25392. this.hls.trigger(Events.LEVELS_UPDATED, {
  25393. levels
  25394. });
  25395. }
  25396. onLevelsUpdated(event, {
  25397. levels
  25398. }) {
  25399. this._levels = levels;
  25400. }
  25401. checkMaxAutoUpdated() {
  25402. const {
  25403. autoLevelCapping,
  25404. maxAutoLevel,
  25405. maxHdcpLevel
  25406. } = this.hls;
  25407. if (this._maxAutoLevel !== maxAutoLevel) {
  25408. this._maxAutoLevel = maxAutoLevel;
  25409. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  25410. autoLevelCapping,
  25411. levels: this.levels,
  25412. maxAutoLevel,
  25413. minAutoLevel: this.hls.minAutoLevel,
  25414. maxHdcpLevel
  25415. });
  25416. }
  25417. }
  25418. }
  25419. function assignTrackIdsByGroup(tracks) {
  25420. const groups = {};
  25421. tracks.forEach(track => {
  25422. const groupId = track.groupId || '';
  25423. track.id = groups[groupId] = groups[groupId] || 0;
  25424. groups[groupId]++;
  25425. });
  25426. }
  25427. class KeyLoader {
  25428. constructor(config) {
  25429. this.config = void 0;
  25430. this.keyUriToKeyInfo = {};
  25431. this.emeController = null;
  25432. this.config = config;
  25433. }
  25434. abort(type) {
  25435. for (const uri in this.keyUriToKeyInfo) {
  25436. const loader = this.keyUriToKeyInfo[uri].loader;
  25437. if (loader) {
  25438. var _loader$context;
  25439. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  25440. return;
  25441. }
  25442. loader.abort();
  25443. }
  25444. }
  25445. }
  25446. detach() {
  25447. for (const uri in this.keyUriToKeyInfo) {
  25448. const keyInfo = this.keyUriToKeyInfo[uri];
  25449. // Remove cached EME keys on detach
  25450. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  25451. delete this.keyUriToKeyInfo[uri];
  25452. }
  25453. }
  25454. }
  25455. destroy() {
  25456. this.detach();
  25457. for (const uri in this.keyUriToKeyInfo) {
  25458. const loader = this.keyUriToKeyInfo[uri].loader;
  25459. if (loader) {
  25460. loader.destroy();
  25461. }
  25462. }
  25463. this.keyUriToKeyInfo = {};
  25464. }
  25465. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  25466. return new LoadError({
  25467. type: ErrorTypes.NETWORK_ERROR,
  25468. details,
  25469. fatal: false,
  25470. frag,
  25471. response,
  25472. error,
  25473. networkDetails
  25474. });
  25475. }
  25476. loadClear(loadingFrag, encryptedFragments) {
  25477. if (this.emeController && this.config.emeEnabled) {
  25478. // access key-system with nearest key on start (loaidng frag is unencrypted)
  25479. const {
  25480. sn,
  25481. cc
  25482. } = loadingFrag;
  25483. for (let i = 0; i < encryptedFragments.length; i++) {
  25484. const frag = encryptedFragments[i];
  25485. if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {
  25486. this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  25487. frag.setKeyFormat(keySystemFormat);
  25488. });
  25489. break;
  25490. }
  25491. }
  25492. }
  25493. }
  25494. load(frag) {
  25495. if (!frag.decryptdata && frag.encrypted && this.emeController) {
  25496. // Multiple keys, but none selected, resolve in eme-controller
  25497. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  25498. return this.loadInternal(frag, keySystemFormat);
  25499. });
  25500. }
  25501. return this.loadInternal(frag);
  25502. }
  25503. loadInternal(frag, keySystemFormat) {
  25504. var _keyInfo, _keyInfo2;
  25505. if (keySystemFormat) {
  25506. frag.setKeyFormat(keySystemFormat);
  25507. }
  25508. const decryptdata = frag.decryptdata;
  25509. if (!decryptdata) {
  25510. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');
  25511. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  25512. }
  25513. const uri = decryptdata.uri;
  25514. if (!uri) {
  25515. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  25516. }
  25517. let keyInfo = this.keyUriToKeyInfo[uri];
  25518. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  25519. decryptdata.key = keyInfo.decryptdata.key;
  25520. return Promise.resolve({
  25521. frag,
  25522. keyInfo
  25523. });
  25524. }
  25525. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  25526. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  25527. var _keyInfo$mediaKeySess;
  25528. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  25529. case undefined:
  25530. case 'status-pending':
  25531. case 'usable':
  25532. case 'usable-in-future':
  25533. return keyInfo.keyLoadPromise.then(keyLoadedData => {
  25534. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  25535. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  25536. return {
  25537. frag,
  25538. keyInfo
  25539. };
  25540. });
  25541. }
  25542. // If we have a key session and status and it is not pending or usable, continue
  25543. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  25544. }
  25545. // Load the key or return the loading promise
  25546. keyInfo = this.keyUriToKeyInfo[uri] = {
  25547. decryptdata,
  25548. keyLoadPromise: null,
  25549. loader: null,
  25550. mediaKeySessionContext: null
  25551. };
  25552. switch (decryptdata.method) {
  25553. case 'ISO-23001-7':
  25554. case 'SAMPLE-AES':
  25555. case 'SAMPLE-AES-CENC':
  25556. case 'SAMPLE-AES-CTR':
  25557. if (decryptdata.keyFormat === 'identity') {
  25558. // loadKeyHTTP handles http(s) and data URLs
  25559. return this.loadKeyHTTP(keyInfo, frag);
  25560. }
  25561. return this.loadKeyEME(keyInfo, frag);
  25562. case 'AES-128':
  25563. return this.loadKeyHTTP(keyInfo, frag);
  25564. default:
  25565. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  25566. }
  25567. }
  25568. loadKeyEME(keyInfo, frag) {
  25569. const keyLoadedData = {
  25570. frag,
  25571. keyInfo
  25572. };
  25573. if (this.emeController && this.config.emeEnabled) {
  25574. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  25575. if (keySessionContextPromise) {
  25576. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {
  25577. keyInfo.mediaKeySessionContext = keySessionContext;
  25578. return keyLoadedData;
  25579. })).catch(error => {
  25580. // Remove promise for license renewal or retry
  25581. keyInfo.keyLoadPromise = null;
  25582. throw error;
  25583. });
  25584. }
  25585. }
  25586. return Promise.resolve(keyLoadedData);
  25587. }
  25588. loadKeyHTTP(keyInfo, frag) {
  25589. const config = this.config;
  25590. const Loader = config.loader;
  25591. const keyLoader = new Loader(config);
  25592. frag.keyLoader = keyInfo.loader = keyLoader;
  25593. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  25594. const loaderContext = {
  25595. keyInfo,
  25596. frag,
  25597. responseType: 'arraybuffer',
  25598. url: keyInfo.decryptdata.uri
  25599. };
  25600. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  25601. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  25602. // this will also align retry logic with fragment-loader
  25603. const loadPolicy = config.keyLoadPolicy.default;
  25604. const loaderConfig = {
  25605. loadPolicy,
  25606. timeout: loadPolicy.maxLoadTimeMs,
  25607. maxRetry: 0,
  25608. retryDelay: 0,
  25609. maxRetryDelay: 0
  25610. };
  25611. const loaderCallbacks = {
  25612. onSuccess: (response, stats, context, networkDetails) => {
  25613. const {
  25614. frag,
  25615. keyInfo,
  25616. url: uri
  25617. } = context;
  25618. if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {
  25619. return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  25620. }
  25621. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  25622. // detach fragment key loader on load success
  25623. frag.keyLoader = null;
  25624. keyInfo.loader = null;
  25625. resolve({
  25626. frag,
  25627. keyInfo
  25628. });
  25629. },
  25630. onError: (response, context, networkDetails, stats) => {
  25631. this.resetLoader(context);
  25632. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  25633. url: loaderContext.url,
  25634. data: undefined
  25635. }, response)));
  25636. },
  25637. onTimeout: (stats, context, networkDetails) => {
  25638. this.resetLoader(context);
  25639. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  25640. },
  25641. onAbort: (stats, context, networkDetails) => {
  25642. this.resetLoader(context);
  25643. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  25644. }
  25645. };
  25646. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  25647. });
  25648. }
  25649. resetLoader(context) {
  25650. const {
  25651. frag,
  25652. keyInfo,
  25653. url: uri
  25654. } = context;
  25655. const loader = keyInfo.loader;
  25656. if (frag.keyLoader === loader) {
  25657. frag.keyLoader = null;
  25658. keyInfo.loader = null;
  25659. }
  25660. delete this.keyUriToKeyInfo[uri];
  25661. if (loader) {
  25662. loader.destroy();
  25663. }
  25664. }
  25665. }
  25666. function getSourceBuffer() {
  25667. return self.SourceBuffer || self.WebKitSourceBuffer;
  25668. }
  25669. function isMSESupported() {
  25670. const mediaSource = getMediaSource();
  25671. if (!mediaSource) {
  25672. return false;
  25673. }
  25674. // if SourceBuffer is exposed ensure its API is valid
  25675. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  25676. const sourceBuffer = getSourceBuffer();
  25677. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  25678. }
  25679. function isSupported() {
  25680. if (!isMSESupported()) {
  25681. return false;
  25682. }
  25683. const mediaSource = getMediaSource();
  25684. 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'))));
  25685. }
  25686. function changeTypeSupported() {
  25687. var _sourceBuffer$prototy;
  25688. const sourceBuffer = getSourceBuffer();
  25689. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  25690. }
  25691. const STALL_MINIMUM_DURATION_MS = 250;
  25692. const MAX_START_GAP_JUMP = 2.0;
  25693. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  25694. const SKIP_BUFFER_RANGE_START = 0.05;
  25695. class GapController {
  25696. constructor(config, media, fragmentTracker, hls) {
  25697. this.config = void 0;
  25698. this.media = null;
  25699. this.fragmentTracker = void 0;
  25700. this.hls = void 0;
  25701. this.nudgeRetry = 0;
  25702. this.stallReported = false;
  25703. this.stalled = null;
  25704. this.moved = false;
  25705. this.seeking = false;
  25706. this.config = config;
  25707. this.media = media;
  25708. this.fragmentTracker = fragmentTracker;
  25709. this.hls = hls;
  25710. }
  25711. destroy() {
  25712. this.media = null;
  25713. // @ts-ignore
  25714. this.hls = this.fragmentTracker = null;
  25715. }
  25716. /**
  25717. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  25718. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  25719. *
  25720. * @param lastCurrentTime - Previously read playhead position
  25721. */
  25722. poll(lastCurrentTime, activeFrag) {
  25723. const {
  25724. config,
  25725. media,
  25726. stalled
  25727. } = this;
  25728. if (media === null) {
  25729. return;
  25730. }
  25731. const {
  25732. currentTime,
  25733. seeking
  25734. } = media;
  25735. const seeked = this.seeking && !seeking;
  25736. const beginSeek = !this.seeking && seeking;
  25737. this.seeking = seeking;
  25738. // The playhead is moving, no-op
  25739. if (currentTime !== lastCurrentTime) {
  25740. this.moved = true;
  25741. if (!seeking) {
  25742. this.nudgeRetry = 0;
  25743. }
  25744. if (stalled !== null) {
  25745. // The playhead is now moving, but was previously stalled
  25746. if (this.stallReported) {
  25747. const _stalledDuration = self.performance.now() - stalled;
  25748. logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(_stalledDuration)}ms`);
  25749. this.stallReported = false;
  25750. }
  25751. this.stalled = null;
  25752. }
  25753. return;
  25754. }
  25755. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  25756. if (beginSeek || seeked) {
  25757. this.stalled = null;
  25758. return;
  25759. }
  25760. // The playhead should not be moving
  25761. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) {
  25762. this.nudgeRetry = 0;
  25763. return;
  25764. }
  25765. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  25766. const nextStart = bufferInfo.nextStart || 0;
  25767. if (seeking) {
  25768. // Waiting for seeking in a buffered range to complete
  25769. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  25770. // Next buffered range is too far ahead to jump to while still seeking
  25771. const noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  25772. if (hasEnoughBuffer || noBufferGap) {
  25773. return;
  25774. }
  25775. // Reset moved state when seeking to a point in or before a gap
  25776. this.moved = false;
  25777. }
  25778. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  25779. // The addition poll gives the browser a chance to jump the gap for us
  25780. if (!this.moved && this.stalled !== null) {
  25781. var _level$details;
  25782. // There is no playable buffer (seeked, waiting for buffer)
  25783. const isBuffered = bufferInfo.len > 0;
  25784. if (!isBuffered && !nextStart) {
  25785. return;
  25786. }
  25787. // Jump start gaps within jump threshold
  25788. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  25789. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  25790. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  25791. // that begins over 1 target duration after the video start position.
  25792. const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  25793. const isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live;
  25794. const maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  25795. const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);
  25796. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  25797. if (!media.paused) {
  25798. this._trySkipBufferHole(partialOrGap);
  25799. }
  25800. return;
  25801. }
  25802. }
  25803. // Start tracking stall time
  25804. const tnow = self.performance.now();
  25805. if (stalled === null) {
  25806. this.stalled = tnow;
  25807. return;
  25808. }
  25809. const stalledDuration = tnow - stalled;
  25810. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  25811. // Report stalling after trying to fix
  25812. this._reportStall(bufferInfo);
  25813. if (!this.media) {
  25814. return;
  25815. }
  25816. }
  25817. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  25818. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  25819. }
  25820. /**
  25821. * Detects and attempts to fix known buffer stalling issues.
  25822. * @param bufferInfo - The properties of the current buffer.
  25823. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  25824. * @private
  25825. */
  25826. _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  25827. const {
  25828. config,
  25829. fragmentTracker,
  25830. media
  25831. } = this;
  25832. if (media === null) {
  25833. return;
  25834. }
  25835. const currentTime = media.currentTime;
  25836. const partial = fragmentTracker.getPartialFragment(currentTime);
  25837. if (partial) {
  25838. // Try to skip over the buffer hole caused by a partial fragment
  25839. // This method isn't limited by the size of the gap between buffered ranges
  25840. const targetTime = this._trySkipBufferHole(partial);
  25841. // we return here in this case, meaning
  25842. // the branch below only executes when we haven't seeked to a new position
  25843. if (targetTime || !this.media) {
  25844. return;
  25845. }
  25846. }
  25847. // if we haven't had to skip over a buffer hole of a partial fragment
  25848. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  25849. // needs to cross some sort of threshold covering all source-buffers content
  25850. // to start playing properly.
  25851. if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  25852. logger.warn('Trying to nudge playhead over buffer-hole');
  25853. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  25854. // We only try to jump the hole if it's under the configured size
  25855. // Reset stalled so to rearm watchdog timer
  25856. this.stalled = null;
  25857. this._tryNudgeBuffer();
  25858. }
  25859. }
  25860. /**
  25861. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  25862. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  25863. * @private
  25864. */
  25865. _reportStall(bufferInfo) {
  25866. const {
  25867. hls,
  25868. media,
  25869. stallReported
  25870. } = this;
  25871. if (!stallReported && media) {
  25872. // Report stalled error once
  25873. this.stallReported = true;
  25874. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${JSON.stringify(bufferInfo)})`);
  25875. logger.warn(error.message);
  25876. hls.trigger(Events.ERROR, {
  25877. type: ErrorTypes.MEDIA_ERROR,
  25878. details: ErrorDetails.BUFFER_STALLED_ERROR,
  25879. fatal: false,
  25880. error,
  25881. buffer: bufferInfo.len
  25882. });
  25883. }
  25884. }
  25885. /**
  25886. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  25887. * @param partial - The partial fragment found at the current time (where playback is stalling).
  25888. * @private
  25889. */
  25890. _trySkipBufferHole(partial) {
  25891. const {
  25892. config,
  25893. hls,
  25894. media
  25895. } = this;
  25896. if (media === null) {
  25897. return 0;
  25898. }
  25899. // Check if currentTime is between unbuffered regions of partial fragments
  25900. const currentTime = media.currentTime;
  25901. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  25902. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  25903. if (startTime) {
  25904. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  25905. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  25906. const gapLength = startTime - currentTime;
  25907. if (gapLength > 0 && (bufferStarved || waiting)) {
  25908. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  25909. if (gapLength > config.maxBufferHole) {
  25910. const {
  25911. fragmentTracker
  25912. } = this;
  25913. let startGap = false;
  25914. if (currentTime === 0) {
  25915. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  25916. if (startFrag && startTime < startFrag.end) {
  25917. startGap = true;
  25918. }
  25919. }
  25920. if (!startGap) {
  25921. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  25922. if (startProvisioned) {
  25923. let moreToLoad = false;
  25924. let pos = startProvisioned.end;
  25925. while (pos < startTime) {
  25926. const provisioned = fragmentTracker.getPartialFragment(pos);
  25927. if (provisioned) {
  25928. pos += provisioned.duration;
  25929. } else {
  25930. moreToLoad = true;
  25931. break;
  25932. }
  25933. }
  25934. if (moreToLoad) {
  25935. return 0;
  25936. }
  25937. }
  25938. }
  25939. }
  25940. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  25941. logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  25942. this.moved = true;
  25943. this.stalled = null;
  25944. media.currentTime = targetTime;
  25945. if (partial && !partial.gap) {
  25946. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  25947. hls.trigger(Events.ERROR, {
  25948. type: ErrorTypes.MEDIA_ERROR,
  25949. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  25950. fatal: false,
  25951. error,
  25952. reason: error.message,
  25953. frag: partial
  25954. });
  25955. }
  25956. return targetTime;
  25957. }
  25958. }
  25959. return 0;
  25960. }
  25961. /**
  25962. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  25963. * @private
  25964. */
  25965. _tryNudgeBuffer() {
  25966. const {
  25967. config,
  25968. hls,
  25969. media,
  25970. nudgeRetry
  25971. } = this;
  25972. if (media === null) {
  25973. return;
  25974. }
  25975. const currentTime = media.currentTime;
  25976. this.nudgeRetry++;
  25977. if (nudgeRetry < config.nudgeMaxRetry) {
  25978. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  25979. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  25980. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  25981. logger.warn(error.message);
  25982. media.currentTime = targetTime;
  25983. hls.trigger(Events.ERROR, {
  25984. type: ErrorTypes.MEDIA_ERROR,
  25985. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  25986. error,
  25987. fatal: false
  25988. });
  25989. } else {
  25990. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  25991. logger.error(error.message);
  25992. hls.trigger(Events.ERROR, {
  25993. type: ErrorTypes.MEDIA_ERROR,
  25994. details: ErrorDetails.BUFFER_STALLED_ERROR,
  25995. error,
  25996. fatal: true
  25997. });
  25998. }
  25999. }
  26000. }
  26001. const TICK_INTERVAL = 100; // how often to tick in ms
  26002. class StreamController extends BaseStreamController {
  26003. constructor(hls, fragmentTracker, keyLoader) {
  26004. super(hls, fragmentTracker, keyLoader, '[stream-controller]', PlaylistLevelType.MAIN);
  26005. this.audioCodecSwap = false;
  26006. this.gapController = null;
  26007. this.level = -1;
  26008. this._forceStartLoad = false;
  26009. this.altAudio = false;
  26010. this.audioOnly = false;
  26011. this.fragPlaying = null;
  26012. this.onvplaying = null;
  26013. this.onvseeked = null;
  26014. this.fragLastKbps = 0;
  26015. this.couldBacktrack = false;
  26016. this.backtrackFragment = null;
  26017. this.audioCodecSwitch = false;
  26018. this.videoBuffer = null;
  26019. this._registerListeners();
  26020. }
  26021. _registerListeners() {
  26022. const {
  26023. hls
  26024. } = this;
  26025. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26026. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26027. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26028. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26029. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  26030. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  26031. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  26032. hls.on(Events.ERROR, this.onError, this);
  26033. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  26034. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  26035. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  26036. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  26037. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  26038. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  26039. }
  26040. _unregisterListeners() {
  26041. const {
  26042. hls
  26043. } = this;
  26044. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26045. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26046. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26047. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26048. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  26049. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  26050. hls.off(Events.ERROR, this.onError, this);
  26051. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  26052. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  26053. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  26054. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  26055. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  26056. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  26057. }
  26058. onHandlerDestroying() {
  26059. this._unregisterListeners();
  26060. super.onHandlerDestroying();
  26061. }
  26062. startLoad(startPosition) {
  26063. if (this.levels) {
  26064. const {
  26065. lastCurrentTime,
  26066. hls
  26067. } = this;
  26068. this.stopLoad();
  26069. this.setInterval(TICK_INTERVAL);
  26070. this.level = -1;
  26071. if (!this.startFragRequested) {
  26072. // determine load level
  26073. let startLevel = hls.startLevel;
  26074. if (startLevel === -1) {
  26075. if (hls.config.testBandwidth && this.levels.length > 1) {
  26076. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  26077. startLevel = 0;
  26078. this.bitrateTest = true;
  26079. } else {
  26080. startLevel = hls.firstAutoLevel;
  26081. }
  26082. }
  26083. // set new level to playlist loader : this will trigger start level load
  26084. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  26085. hls.nextLoadLevel = startLevel;
  26086. this.level = hls.loadLevel;
  26087. this.loadedmetadata = false;
  26088. }
  26089. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  26090. if (lastCurrentTime > 0 && startPosition === -1) {
  26091. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  26092. startPosition = lastCurrentTime;
  26093. }
  26094. this.state = State.IDLE;
  26095. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  26096. this.tick();
  26097. } else {
  26098. this._forceStartLoad = true;
  26099. this.state = State.STOPPED;
  26100. }
  26101. }
  26102. stopLoad() {
  26103. this._forceStartLoad = false;
  26104. super.stopLoad();
  26105. }
  26106. doTick() {
  26107. switch (this.state) {
  26108. case State.WAITING_LEVEL:
  26109. {
  26110. const {
  26111. levels,
  26112. level
  26113. } = this;
  26114. const currentLevel = levels == null ? void 0 : levels[level];
  26115. const details = currentLevel == null ? void 0 : currentLevel.details;
  26116. if (details && (!details.live || this.levelLastLoaded === currentLevel)) {
  26117. if (this.waitForCdnTuneIn(details)) {
  26118. break;
  26119. }
  26120. this.state = State.IDLE;
  26121. break;
  26122. } else if (this.hls.nextLoadLevel !== this.level) {
  26123. this.state = State.IDLE;
  26124. break;
  26125. }
  26126. break;
  26127. }
  26128. case State.FRAG_LOADING_WAITING_RETRY:
  26129. {
  26130. var _this$media;
  26131. const now = self.performance.now();
  26132. const retryDate = this.retryDate;
  26133. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  26134. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  26135. const {
  26136. levels,
  26137. level
  26138. } = this;
  26139. const currentLevel = levels == null ? void 0 : levels[level];
  26140. this.resetStartWhenNotLoaded(currentLevel || null);
  26141. this.state = State.IDLE;
  26142. }
  26143. }
  26144. break;
  26145. }
  26146. if (this.state === State.IDLE) {
  26147. this.doTickIdle();
  26148. }
  26149. this.onTickEnd();
  26150. }
  26151. onTickEnd() {
  26152. super.onTickEnd();
  26153. this.checkBuffer();
  26154. this.checkFragmentChanged();
  26155. }
  26156. doTickIdle() {
  26157. const {
  26158. hls,
  26159. levelLastLoaded,
  26160. levels,
  26161. media
  26162. } = this;
  26163. // if start level not parsed yet OR
  26164. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  26165. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  26166. if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  26167. return;
  26168. }
  26169. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  26170. if (this.altAudio && this.audioOnly) {
  26171. return;
  26172. }
  26173. const level = hls.nextLoadLevel;
  26174. if (!(levels != null && levels[level])) {
  26175. return;
  26176. }
  26177. const levelInfo = levels[level];
  26178. // if buffer length is less than maxBufLen try to load a new fragment
  26179. const bufferInfo = this.getMainFwdBufferInfo();
  26180. if (bufferInfo === null) {
  26181. return;
  26182. }
  26183. const lastDetails = this.getLevelDetails();
  26184. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  26185. const data = {};
  26186. if (this.altAudio) {
  26187. data.type = 'video';
  26188. }
  26189. this.hls.trigger(Events.BUFFER_EOS, data);
  26190. this.state = State.ENDED;
  26191. return;
  26192. }
  26193. // set next load level : this will trigger a playlist load if needed
  26194. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  26195. this.log(`Adapting to level ${level} from level ${this.level}`);
  26196. }
  26197. this.level = hls.nextLoadLevel = level;
  26198. const levelDetails = levelInfo.details;
  26199. // if level info not retrieved yet, switch state and wait for level retrieval
  26200. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  26201. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  26202. if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) {
  26203. this.level = level;
  26204. this.state = State.WAITING_LEVEL;
  26205. return;
  26206. }
  26207. const bufferLen = bufferInfo.len;
  26208. // 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
  26209. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  26210. // Stay idle if we are still with buffer margins
  26211. if (bufferLen >= maxBufLen) {
  26212. return;
  26213. }
  26214. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  26215. this.backtrackFragment = null;
  26216. }
  26217. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  26218. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  26219. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  26220. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  26221. var _this$backtrackFragme;
  26222. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  26223. const fragIdx = backtrackSn - levelDetails.startSN;
  26224. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  26225. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  26226. frag = backtrackFrag;
  26227. this.fragmentTracker.removeFragment(backtrackFrag);
  26228. }
  26229. } else if (this.backtrackFragment && bufferInfo.len) {
  26230. this.backtrackFragment = null;
  26231. }
  26232. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  26233. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  26234. const gapStart = frag.gap;
  26235. if (!gapStart) {
  26236. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  26237. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  26238. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  26239. if (mediaBuffer) {
  26240. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  26241. }
  26242. }
  26243. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  26244. }
  26245. if (!frag) {
  26246. return;
  26247. }
  26248. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  26249. frag = frag.initSegment;
  26250. }
  26251. this.loadFragment(frag, levelInfo, targetBufferTime);
  26252. }
  26253. loadFragment(frag, level, targetBufferTime) {
  26254. // Check if fragment is not loaded
  26255. const fragState = this.fragmentTracker.getState(frag);
  26256. this.fragCurrent = frag;
  26257. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  26258. if (frag.sn === 'initSegment') {
  26259. this._loadInitSegment(frag, level);
  26260. } else if (this.bitrateTest) {
  26261. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  26262. this._loadBitrateTestFrag(frag, level);
  26263. } else {
  26264. this.startFragRequested = true;
  26265. super.loadFragment(frag, level, targetBufferTime);
  26266. }
  26267. } else {
  26268. this.clearTrackerIfNeeded(frag);
  26269. }
  26270. }
  26271. getBufferedFrag(position) {
  26272. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  26273. }
  26274. followingBufferedFrag(frag) {
  26275. if (frag) {
  26276. // try to get range of next fragment (500ms after this range)
  26277. return this.getBufferedFrag(frag.end + 0.5);
  26278. }
  26279. return null;
  26280. }
  26281. /*
  26282. on immediate level switch :
  26283. - pause playback if playing
  26284. - cancel any pending load request
  26285. - and trigger a buffer flush
  26286. */
  26287. immediateLevelSwitch() {
  26288. this.abortCurrentFrag();
  26289. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  26290. }
  26291. /**
  26292. * try to switch ASAP without breaking video playback:
  26293. * in order to ensure smooth but quick level switching,
  26294. * we need to find the next flushable buffer range
  26295. * we should take into account new segment fetch time
  26296. */
  26297. nextLevelSwitch() {
  26298. const {
  26299. levels,
  26300. media
  26301. } = this;
  26302. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  26303. if (media != null && media.readyState) {
  26304. let fetchdelay;
  26305. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  26306. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  26307. // flush buffer preceding current fragment (flush until current fragment start offset)
  26308. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  26309. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  26310. }
  26311. const levelDetails = this.getLevelDetails();
  26312. if (levelDetails != null && levelDetails.live) {
  26313. const bufferInfo = this.getMainFwdBufferInfo();
  26314. // Do not flush in live stream with low buffer
  26315. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  26316. return;
  26317. }
  26318. }
  26319. if (!media.paused && levels) {
  26320. // add a safety delay of 1s
  26321. const nextLevelId = this.hls.nextLoadLevel;
  26322. const nextLevel = levels[nextLevelId];
  26323. const fragLastKbps = this.fragLastKbps;
  26324. if (fragLastKbps && this.fragCurrent) {
  26325. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  26326. } else {
  26327. fetchdelay = 0;
  26328. }
  26329. } else {
  26330. fetchdelay = 0;
  26331. }
  26332. // this.log('fetchdelay:'+fetchdelay);
  26333. // find buffer range that will be reached once new fragment will be fetched
  26334. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  26335. if (bufferedFrag) {
  26336. // we can flush buffer range following this one without stalling playback
  26337. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  26338. if (nextBufferedFrag) {
  26339. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  26340. this.abortCurrentFrag();
  26341. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  26342. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  26343. const fragDuration = nextBufferedFrag.duration;
  26344. 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)));
  26345. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  26346. }
  26347. }
  26348. }
  26349. }
  26350. abortCurrentFrag() {
  26351. const fragCurrent = this.fragCurrent;
  26352. this.fragCurrent = null;
  26353. this.backtrackFragment = null;
  26354. if (fragCurrent) {
  26355. fragCurrent.abortRequests();
  26356. this.fragmentTracker.removeFragment(fragCurrent);
  26357. }
  26358. switch (this.state) {
  26359. case State.KEY_LOADING:
  26360. case State.FRAG_LOADING:
  26361. case State.FRAG_LOADING_WAITING_RETRY:
  26362. case State.PARSING:
  26363. case State.PARSED:
  26364. this.state = State.IDLE;
  26365. break;
  26366. }
  26367. this.nextLoadPosition = this.getLoadPosition();
  26368. }
  26369. flushMainBuffer(startOffset, endOffset) {
  26370. super.flushMainBuffer(startOffset, endOffset, this.altAudio ? 'video' : null);
  26371. }
  26372. onMediaAttached(event, data) {
  26373. super.onMediaAttached(event, data);
  26374. const media = data.media;
  26375. this.onvplaying = this.onMediaPlaying.bind(this);
  26376. this.onvseeked = this.onMediaSeeked.bind(this);
  26377. media.addEventListener('playing', this.onvplaying);
  26378. media.addEventListener('seeked', this.onvseeked);
  26379. this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls);
  26380. }
  26381. onMediaDetaching() {
  26382. const {
  26383. media
  26384. } = this;
  26385. if (media && this.onvplaying && this.onvseeked) {
  26386. media.removeEventListener('playing', this.onvplaying);
  26387. media.removeEventListener('seeked', this.onvseeked);
  26388. this.onvplaying = this.onvseeked = null;
  26389. this.videoBuffer = null;
  26390. }
  26391. this.fragPlaying = null;
  26392. if (this.gapController) {
  26393. this.gapController.destroy();
  26394. this.gapController = null;
  26395. }
  26396. super.onMediaDetaching();
  26397. }
  26398. onMediaPlaying() {
  26399. // tick to speed up FRAG_CHANGED triggering
  26400. this.tick();
  26401. }
  26402. onMediaSeeked() {
  26403. const media = this.media;
  26404. const currentTime = media ? media.currentTime : null;
  26405. if (isFiniteNumber(currentTime)) {
  26406. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  26407. }
  26408. // If seeked was issued before buffer was appended do not tick immediately
  26409. const bufferInfo = this.getMainFwdBufferInfo();
  26410. if (bufferInfo === null || bufferInfo.len === 0) {
  26411. this.warn(`Main forward buffer length on "seeked" event ${bufferInfo ? bufferInfo.len : 'empty'})`);
  26412. return;
  26413. }
  26414. // tick to speed up FRAG_CHANGED triggering
  26415. this.tick();
  26416. }
  26417. onManifestLoading() {
  26418. // reset buffer on manifest loading
  26419. this.log('Trigger BUFFER_RESET');
  26420. this.hls.trigger(Events.BUFFER_RESET, undefined);
  26421. this.fragmentTracker.removeAllFragments();
  26422. this.couldBacktrack = false;
  26423. this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
  26424. this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null;
  26425. this.altAudio = this.audioOnly = this.startFragRequested = false;
  26426. }
  26427. onManifestParsed(event, data) {
  26428. // detect if we have different kind of audio codecs used amongst playlists
  26429. let aac = false;
  26430. let heaac = false;
  26431. data.levels.forEach(level => {
  26432. const codec = level.audioCodec;
  26433. if (codec) {
  26434. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  26435. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  26436. }
  26437. });
  26438. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  26439. if (this.audioCodecSwitch) {
  26440. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  26441. }
  26442. this.levels = data.levels;
  26443. this.startFragRequested = false;
  26444. }
  26445. onLevelLoading(event, data) {
  26446. const {
  26447. levels
  26448. } = this;
  26449. if (!levels || this.state !== State.IDLE) {
  26450. return;
  26451. }
  26452. const level = levels[data.level];
  26453. if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) {
  26454. this.state = State.WAITING_LEVEL;
  26455. }
  26456. }
  26457. onLevelLoaded(event, data) {
  26458. var _curLevel$details;
  26459. const {
  26460. levels
  26461. } = this;
  26462. const newLevelId = data.level;
  26463. const newDetails = data.details;
  26464. const duration = newDetails.totalduration;
  26465. if (!levels) {
  26466. this.warn(`Levels were reset while loading level ${newLevelId}`);
  26467. return;
  26468. }
  26469. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  26470. const curLevel = levels[newLevelId];
  26471. const fragCurrent = this.fragCurrent;
  26472. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  26473. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  26474. this.abortCurrentFrag();
  26475. }
  26476. }
  26477. let sliding = 0;
  26478. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  26479. var _this$levelLastLoaded;
  26480. this.checkLiveUpdate(newDetails);
  26481. if (newDetails.deltaUpdateFailed) {
  26482. return;
  26483. }
  26484. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  26485. }
  26486. // override level info
  26487. curLevel.details = newDetails;
  26488. this.levelLastLoaded = curLevel;
  26489. this.hls.trigger(Events.LEVEL_UPDATED, {
  26490. details: newDetails,
  26491. level: newLevelId
  26492. });
  26493. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  26494. if (this.state === State.WAITING_LEVEL) {
  26495. if (this.waitForCdnTuneIn(newDetails)) {
  26496. // Wait for Low-Latency CDN Tune-in
  26497. return;
  26498. }
  26499. this.state = State.IDLE;
  26500. }
  26501. if (!this.startFragRequested) {
  26502. this.setStartPosition(newDetails, sliding);
  26503. } else if (newDetails.live) {
  26504. this.synchronizeToLiveEdge(newDetails);
  26505. }
  26506. // trigger handler right now
  26507. this.tick();
  26508. }
  26509. _handleFragmentLoadProgress(data) {
  26510. var _frag$initSegment;
  26511. const {
  26512. frag,
  26513. part,
  26514. payload
  26515. } = data;
  26516. const {
  26517. levels
  26518. } = this;
  26519. if (!levels) {
  26520. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  26521. return;
  26522. }
  26523. const currentLevel = levels[frag.level];
  26524. const details = currentLevel.details;
  26525. if (!details) {
  26526. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  26527. this.fragmentTracker.removeFragment(frag);
  26528. return;
  26529. }
  26530. const videoCodec = currentLevel.videoCodec;
  26531. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  26532. const accurateTimeOffset = details.PTSKnown || !details.live;
  26533. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  26534. const audioCodec = this._getAudioCodec(currentLevel);
  26535. // transmux the MPEG-TS data to ISO-BMFF segments
  26536. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  26537. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  26538. const partIndex = part ? part.index : -1;
  26539. const partial = partIndex !== -1;
  26540. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  26541. const initPTS = this.initPTS[frag.cc];
  26542. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  26543. }
  26544. onAudioTrackSwitching(event, data) {
  26545. // if any URL found on new audio track, it is an alternate audio track
  26546. const fromAltAudio = this.altAudio;
  26547. const altAudio = !!data.url;
  26548. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  26549. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  26550. // we will just have to change buffer scheduling on audioTrackSwitched
  26551. if (!altAudio) {
  26552. if (this.mediaBuffer !== this.media) {
  26553. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  26554. this.mediaBuffer = this.media;
  26555. const fragCurrent = this.fragCurrent;
  26556. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  26557. if (fragCurrent) {
  26558. this.log('Switching to main audio track, cancel main fragment load');
  26559. fragCurrent.abortRequests();
  26560. this.fragmentTracker.removeFragment(fragCurrent);
  26561. }
  26562. // destroy transmuxer to force init segment generation (following audio switch)
  26563. this.resetTransmuxer();
  26564. // switch to IDLE state to load new fragment
  26565. this.resetLoadingState();
  26566. } else if (this.audioOnly) {
  26567. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  26568. this.resetTransmuxer();
  26569. }
  26570. const hls = this.hls;
  26571. // If switching from alt to main audio, flush all audio and trigger track switched
  26572. if (fromAltAudio) {
  26573. hls.trigger(Events.BUFFER_FLUSHING, {
  26574. startOffset: 0,
  26575. endOffset: Number.POSITIVE_INFINITY,
  26576. type: null
  26577. });
  26578. this.fragmentTracker.removeAllFragments();
  26579. }
  26580. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  26581. }
  26582. }
  26583. onAudioTrackSwitched(event, data) {
  26584. const trackId = data.id;
  26585. const altAudio = !!this.hls.audioTracks[trackId].url;
  26586. if (altAudio) {
  26587. const videoBuffer = this.videoBuffer;
  26588. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  26589. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  26590. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  26591. this.mediaBuffer = videoBuffer;
  26592. }
  26593. }
  26594. this.altAudio = altAudio;
  26595. this.tick();
  26596. }
  26597. onBufferCreated(event, data) {
  26598. const tracks = data.tracks;
  26599. let mediaTrack;
  26600. let name;
  26601. let alternate = false;
  26602. for (const type in tracks) {
  26603. const track = tracks[type];
  26604. if (track.id === 'main') {
  26605. name = type;
  26606. mediaTrack = track;
  26607. // keep video source buffer reference
  26608. if (type === 'video') {
  26609. const videoTrack = tracks[type];
  26610. if (videoTrack) {
  26611. this.videoBuffer = videoTrack.buffer;
  26612. }
  26613. }
  26614. } else {
  26615. alternate = true;
  26616. }
  26617. }
  26618. if (alternate && mediaTrack) {
  26619. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  26620. this.mediaBuffer = mediaTrack.buffer;
  26621. } else {
  26622. this.mediaBuffer = this.media;
  26623. }
  26624. }
  26625. onFragBuffered(event, data) {
  26626. const {
  26627. frag,
  26628. part
  26629. } = data;
  26630. if (frag && frag.type !== PlaylistLevelType.MAIN) {
  26631. return;
  26632. }
  26633. if (this.fragContextChanged(frag)) {
  26634. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  26635. // Avoid setting state back to IDLE, since that will interfere with a level switch
  26636. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  26637. if (this.state === State.PARSED) {
  26638. this.state = State.IDLE;
  26639. }
  26640. return;
  26641. }
  26642. const stats = part ? part.stats : frag.stats;
  26643. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  26644. if (frag.sn !== 'initSegment') {
  26645. this.fragPrevious = frag;
  26646. }
  26647. this.fragBufferedComplete(frag, part);
  26648. }
  26649. onError(event, data) {
  26650. var _data$context;
  26651. if (data.fatal) {
  26652. this.state = State.ERROR;
  26653. return;
  26654. }
  26655. switch (data.details) {
  26656. case ErrorDetails.FRAG_GAP:
  26657. case ErrorDetails.FRAG_PARSING_ERROR:
  26658. case ErrorDetails.FRAG_DECRYPT_ERROR:
  26659. case ErrorDetails.FRAG_LOAD_ERROR:
  26660. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  26661. case ErrorDetails.KEY_LOAD_ERROR:
  26662. case ErrorDetails.KEY_LOAD_TIMEOUT:
  26663. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  26664. break;
  26665. case ErrorDetails.LEVEL_LOAD_ERROR:
  26666. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  26667. case ErrorDetails.LEVEL_PARSING_ERROR:
  26668. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  26669. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  26670. this.state = State.IDLE;
  26671. }
  26672. break;
  26673. case ErrorDetails.BUFFER_APPEND_ERROR:
  26674. case ErrorDetails.BUFFER_FULL_ERROR:
  26675. if (!data.parent || data.parent !== 'main') {
  26676. return;
  26677. }
  26678. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  26679. this.resetLoadingState();
  26680. return;
  26681. }
  26682. if (this.reduceLengthAndFlushBuffer(data)) {
  26683. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  26684. }
  26685. break;
  26686. case ErrorDetails.INTERNAL_EXCEPTION:
  26687. this.recoverWorkerError(data);
  26688. break;
  26689. }
  26690. }
  26691. // Checks the health of the buffer and attempts to resolve playback stalls.
  26692. checkBuffer() {
  26693. const {
  26694. media,
  26695. gapController
  26696. } = this;
  26697. if (!media || !gapController || !media.readyState) {
  26698. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  26699. return;
  26700. }
  26701. if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
  26702. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  26703. const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;
  26704. gapController.poll(this.lastCurrentTime, activeFrag);
  26705. }
  26706. this.lastCurrentTime = media.currentTime;
  26707. }
  26708. onFragLoadEmergencyAborted() {
  26709. this.state = State.IDLE;
  26710. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  26711. // in that case, reset startFragRequested flag
  26712. if (!this.loadedmetadata) {
  26713. this.startFragRequested = false;
  26714. this.nextLoadPosition = this.startPosition;
  26715. }
  26716. this.tickImmediate();
  26717. }
  26718. onBufferFlushed(event, {
  26719. type
  26720. }) {
  26721. if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  26722. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  26723. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  26724. this.tick();
  26725. }
  26726. }
  26727. onLevelsUpdated(event, data) {
  26728. if (this.level > -1 && this.fragCurrent) {
  26729. this.level = this.fragCurrent.level;
  26730. }
  26731. this.levels = data.levels;
  26732. }
  26733. swapAudioCodec() {
  26734. this.audioCodecSwap = !this.audioCodecSwap;
  26735. }
  26736. /**
  26737. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  26738. */
  26739. seekToStartPos() {
  26740. const {
  26741. media
  26742. } = this;
  26743. if (!media) {
  26744. return;
  26745. }
  26746. const currentTime = media.currentTime;
  26747. let startPosition = this.startPosition;
  26748. // only adjust currentTime if different from startPosition or if startPosition not buffered
  26749. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  26750. if (startPosition >= 0 && currentTime < startPosition) {
  26751. if (media.seeking) {
  26752. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  26753. return;
  26754. }
  26755. const buffered = BufferHelper.getBuffered(media);
  26756. const bufferStart = buffered.length ? buffered.start(0) : 0;
  26757. const delta = bufferStart - startPosition;
  26758. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  26759. this.log(`adjusting start position by ${delta} to match buffer start`);
  26760. startPosition += delta;
  26761. this.startPosition = startPosition;
  26762. }
  26763. this.log(`seek to target start position ${startPosition} from current time ${currentTime}`);
  26764. media.currentTime = startPosition;
  26765. }
  26766. }
  26767. _getAudioCodec(currentLevel) {
  26768. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  26769. if (this.audioCodecSwap && audioCodec) {
  26770. this.log('Swapping audio codec');
  26771. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  26772. audioCodec = 'mp4a.40.2';
  26773. } else {
  26774. audioCodec = 'mp4a.40.5';
  26775. }
  26776. }
  26777. return audioCodec;
  26778. }
  26779. _loadBitrateTestFrag(frag, level) {
  26780. frag.bitrateTest = true;
  26781. this._doFragLoad(frag, level).then(data => {
  26782. const {
  26783. hls
  26784. } = this;
  26785. if (!data || this.fragContextChanged(frag)) {
  26786. return;
  26787. }
  26788. level.fragmentError = 0;
  26789. this.state = State.IDLE;
  26790. this.startFragRequested = false;
  26791. this.bitrateTest = false;
  26792. const stats = frag.stats;
  26793. // Bitrate tests fragments are neither parsed nor buffered
  26794. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  26795. hls.trigger(Events.FRAG_LOADED, data);
  26796. frag.bitrateTest = false;
  26797. });
  26798. }
  26799. _handleTransmuxComplete(transmuxResult) {
  26800. var _id3$samples;
  26801. const id = 'main';
  26802. const {
  26803. hls
  26804. } = this;
  26805. const {
  26806. remuxResult,
  26807. chunkMeta
  26808. } = transmuxResult;
  26809. const context = this.getCurrentContext(chunkMeta);
  26810. if (!context) {
  26811. this.resetWhenMissingContext(chunkMeta);
  26812. return;
  26813. }
  26814. const {
  26815. frag,
  26816. part,
  26817. level
  26818. } = context;
  26819. const {
  26820. video,
  26821. text,
  26822. id3,
  26823. initSegment
  26824. } = remuxResult;
  26825. const {
  26826. details
  26827. } = level;
  26828. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  26829. const audio = this.altAudio ? undefined : remuxResult.audio;
  26830. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  26831. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  26832. if (this.fragContextChanged(frag)) {
  26833. this.fragmentTracker.removeFragment(frag);
  26834. return;
  26835. }
  26836. this.state = State.PARSING;
  26837. if (initSegment) {
  26838. if (initSegment != null && initSegment.tracks) {
  26839. const mapFragment = frag.initSegment || frag;
  26840. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  26841. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  26842. frag: mapFragment,
  26843. id,
  26844. tracks: initSegment.tracks
  26845. });
  26846. }
  26847. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  26848. const initPTS = initSegment.initPTS;
  26849. const timescale = initSegment.timescale;
  26850. if (isFiniteNumber(initPTS)) {
  26851. this.initPTS[frag.cc] = {
  26852. baseTime: initPTS,
  26853. timescale
  26854. };
  26855. hls.trigger(Events.INIT_PTS_FOUND, {
  26856. frag,
  26857. id,
  26858. initPTS,
  26859. timescale
  26860. });
  26861. }
  26862. }
  26863. // Avoid buffering if backtracking this fragment
  26864. if (video && details && frag.sn !== 'initSegment') {
  26865. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  26866. const isFirstFragment = frag.sn === details.startSN;
  26867. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  26868. if (remuxResult.independent !== false) {
  26869. const {
  26870. startPTS,
  26871. endPTS,
  26872. startDTS,
  26873. endDTS
  26874. } = video;
  26875. if (part) {
  26876. part.elementaryStreams[video.type] = {
  26877. startPTS,
  26878. endPTS,
  26879. startDTS,
  26880. endDTS
  26881. };
  26882. } else {
  26883. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  26884. this.couldBacktrack = true;
  26885. }
  26886. if (video.dropped && video.independent) {
  26887. // Backtrack if dropped frames create a gap after currentTime
  26888. const bufferInfo = this.getMainFwdBufferInfo();
  26889. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  26890. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  26891. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  26892. this.backtrack(frag);
  26893. return;
  26894. } else if (isFirstInDiscontinuity) {
  26895. // Mark segment with a gap to avoid loop loading
  26896. frag.gap = true;
  26897. }
  26898. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  26899. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  26900. } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {
  26901. // Mark segment with a gap to skip large start gap
  26902. frag.gap = true;
  26903. }
  26904. }
  26905. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  26906. if (this.backtrackFragment) {
  26907. this.backtrackFragment = frag;
  26908. }
  26909. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  26910. } else if (isFirstFragment || isFirstInDiscontinuity) {
  26911. // Mark segment with a gap to avoid loop loading
  26912. frag.gap = true;
  26913. } else {
  26914. this.backtrack(frag);
  26915. return;
  26916. }
  26917. }
  26918. if (audio) {
  26919. const {
  26920. startPTS,
  26921. endPTS,
  26922. startDTS,
  26923. endDTS
  26924. } = audio;
  26925. if (part) {
  26926. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  26927. startPTS,
  26928. endPTS,
  26929. startDTS,
  26930. endDTS
  26931. };
  26932. }
  26933. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  26934. this.bufferFragmentData(audio, frag, part, chunkMeta);
  26935. }
  26936. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  26937. const emittedID3 = {
  26938. id,
  26939. frag,
  26940. details,
  26941. samples: id3.samples
  26942. };
  26943. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  26944. }
  26945. if (details && text) {
  26946. const emittedText = {
  26947. id,
  26948. frag,
  26949. details,
  26950. samples: text.samples
  26951. };
  26952. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  26953. }
  26954. }
  26955. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  26956. if (this.state !== State.PARSING) {
  26957. return;
  26958. }
  26959. this.audioOnly = !!tracks.audio && !tracks.video;
  26960. // if audio track is expected to come from audio stream controller, discard any coming from main
  26961. if (this.altAudio && !this.audioOnly) {
  26962. delete tracks.audio;
  26963. }
  26964. // include levelCodec in audio and video tracks
  26965. const {
  26966. audio,
  26967. video,
  26968. audiovideo
  26969. } = tracks;
  26970. if (audio) {
  26971. let audioCodec = currentLevel.audioCodec;
  26972. const ua = navigator.userAgent.toLowerCase();
  26973. if (this.audioCodecSwitch) {
  26974. if (audioCodec) {
  26975. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  26976. audioCodec = 'mp4a.40.2';
  26977. } else {
  26978. audioCodec = 'mp4a.40.5';
  26979. }
  26980. }
  26981. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  26982. // force HE-AAC, as it seems that most browsers prefers it.
  26983. // don't force HE-AAC if mono stream, or in Firefox
  26984. const audioMetadata = audio.metadata;
  26985. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  26986. audioCodec = 'mp4a.40.5';
  26987. }
  26988. }
  26989. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  26990. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  26991. // Exclude mpeg audio
  26992. audioCodec = 'mp4a.40.2';
  26993. this.log(`Android: force audio codec to ${audioCodec}`);
  26994. }
  26995. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  26996. this.log(`Swapping manifest audio codec "${currentLevel.audioCodec}" for "${audioCodec}"`);
  26997. }
  26998. audio.levelCodec = audioCodec;
  26999. audio.id = 'main';
  27000. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${currentLevel.audioCodec || ''}/${audio.codec}]`);
  27001. }
  27002. if (video) {
  27003. video.levelCodec = currentLevel.videoCodec;
  27004. video.id = 'main';
  27005. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${video.codec}]`);
  27006. }
  27007. if (audiovideo) {
  27008. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  27009. }
  27010. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  27011. // loop through tracks that are going to be provided to bufferController
  27012. Object.keys(tracks).forEach(trackName => {
  27013. const track = tracks[trackName];
  27014. const initSegment = track.initSegment;
  27015. if (initSegment != null && initSegment.byteLength) {
  27016. this.hls.trigger(Events.BUFFER_APPENDING, {
  27017. type: trackName,
  27018. data: initSegment,
  27019. frag,
  27020. part: null,
  27021. chunkMeta,
  27022. parent: frag.type
  27023. });
  27024. }
  27025. });
  27026. // trigger handler right now
  27027. this.tickImmediate();
  27028. }
  27029. getMainFwdBufferInfo() {
  27030. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN);
  27031. }
  27032. backtrack(frag) {
  27033. this.couldBacktrack = true;
  27034. // Causes findFragments to backtrack through fragments to find the keyframe
  27035. this.backtrackFragment = frag;
  27036. this.resetTransmuxer();
  27037. this.flushBufferGap(frag);
  27038. this.fragmentTracker.removeFragment(frag);
  27039. this.fragPrevious = null;
  27040. this.nextLoadPosition = frag.start;
  27041. this.state = State.IDLE;
  27042. }
  27043. checkFragmentChanged() {
  27044. const video = this.media;
  27045. let fragPlayingCurrent = null;
  27046. if (video && video.readyState > 1 && video.seeking === false) {
  27047. const currentTime = video.currentTime;
  27048. /* if video element is in seeked state, currentTime can only increase.
  27049. (assuming that playback rate is positive ...)
  27050. As sometimes currentTime jumps back to zero after a
  27051. media decode error, check this, to avoid seeking back to
  27052. wrong position after a media decode error
  27053. */
  27054. if (BufferHelper.isBuffered(video, currentTime)) {
  27055. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  27056. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  27057. /* ensure that FRAG_CHANGED event is triggered at startup,
  27058. when first video frame is displayed and playback is paused.
  27059. add a tolerance of 100ms, in case current position is not buffered,
  27060. check if current pos+100ms is buffered and use that buffer range
  27061. for FRAG_CHANGED event reporting */
  27062. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  27063. }
  27064. if (fragPlayingCurrent) {
  27065. this.backtrackFragment = null;
  27066. const fragPlaying = this.fragPlaying;
  27067. const fragCurrentLevel = fragPlayingCurrent.level;
  27068. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  27069. this.fragPlaying = fragPlayingCurrent;
  27070. this.hls.trigger(Events.FRAG_CHANGED, {
  27071. frag: fragPlayingCurrent
  27072. });
  27073. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  27074. this.hls.trigger(Events.LEVEL_SWITCHED, {
  27075. level: fragCurrentLevel
  27076. });
  27077. }
  27078. }
  27079. }
  27080. }
  27081. }
  27082. get nextLevel() {
  27083. const frag = this.nextBufferedFrag;
  27084. if (frag) {
  27085. return frag.level;
  27086. }
  27087. return -1;
  27088. }
  27089. get currentFrag() {
  27090. const media = this.media;
  27091. if (media) {
  27092. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  27093. }
  27094. return null;
  27095. }
  27096. get currentProgramDateTime() {
  27097. const media = this.media;
  27098. if (media) {
  27099. const currentTime = media.currentTime;
  27100. const frag = this.currentFrag;
  27101. if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) {
  27102. const epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  27103. return new Date(epocMs);
  27104. }
  27105. }
  27106. return null;
  27107. }
  27108. get currentLevel() {
  27109. const frag = this.currentFrag;
  27110. if (frag) {
  27111. return frag.level;
  27112. }
  27113. return -1;
  27114. }
  27115. get nextBufferedFrag() {
  27116. const frag = this.currentFrag;
  27117. if (frag) {
  27118. return this.followingBufferedFrag(frag);
  27119. }
  27120. return null;
  27121. }
  27122. get forceStartLoad() {
  27123. return this._forceStartLoad;
  27124. }
  27125. }
  27126. /**
  27127. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  27128. * @public
  27129. */
  27130. class Hls {
  27131. /**
  27132. * Get the video-dev/hls.js package version.
  27133. */
  27134. static get version() {
  27135. return "1.5.15";
  27136. }
  27137. /**
  27138. * Check if the required MediaSource Extensions are available.
  27139. */
  27140. static isMSESupported() {
  27141. return isMSESupported();
  27142. }
  27143. /**
  27144. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  27145. */
  27146. static isSupported() {
  27147. return isSupported();
  27148. }
  27149. /**
  27150. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  27151. */
  27152. static getMediaSource() {
  27153. return getMediaSource();
  27154. }
  27155. static get Events() {
  27156. return Events;
  27157. }
  27158. static get ErrorTypes() {
  27159. return ErrorTypes;
  27160. }
  27161. static get ErrorDetails() {
  27162. return ErrorDetails;
  27163. }
  27164. /**
  27165. * Get the default configuration applied to new instances.
  27166. */
  27167. static get DefaultConfig() {
  27168. if (!Hls.defaultConfig) {
  27169. return hlsDefaultConfig;
  27170. }
  27171. return Hls.defaultConfig;
  27172. }
  27173. /**
  27174. * Replace the default configuration applied to new instances.
  27175. */
  27176. static set DefaultConfig(defaultConfig) {
  27177. Hls.defaultConfig = defaultConfig;
  27178. }
  27179. /**
  27180. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  27181. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  27182. */
  27183. constructor(userConfig = {}) {
  27184. /**
  27185. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  27186. */
  27187. this.config = void 0;
  27188. /**
  27189. * The configuration object provided on player instantiation.
  27190. */
  27191. this.userConfig = void 0;
  27192. this.coreComponents = void 0;
  27193. this.networkControllers = void 0;
  27194. this.started = false;
  27195. this._emitter = new EventEmitter();
  27196. this._autoLevelCapping = -1;
  27197. this._maxHdcpLevel = null;
  27198. this.abrController = void 0;
  27199. this.bufferController = void 0;
  27200. this.capLevelController = void 0;
  27201. this.latencyController = void 0;
  27202. this.levelController = void 0;
  27203. this.streamController = void 0;
  27204. this.audioTrackController = void 0;
  27205. this.subtitleTrackController = void 0;
  27206. this.emeController = void 0;
  27207. this.cmcdController = void 0;
  27208. this._media = null;
  27209. this.url = null;
  27210. this.triggeringException = void 0;
  27211. enableLogs(userConfig.debug || false, 'Hls instance');
  27212. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig);
  27213. this.userConfig = userConfig;
  27214. if (config.progressive) {
  27215. enableStreamingMode(config);
  27216. }
  27217. // core controllers and network loaders
  27218. const {
  27219. abrController: ConfigAbrController,
  27220. bufferController: ConfigBufferController,
  27221. capLevelController: ConfigCapLevelController,
  27222. errorController: ConfigErrorController,
  27223. fpsController: ConfigFpsController
  27224. } = config;
  27225. const errorController = new ConfigErrorController(this);
  27226. const abrController = this.abrController = new ConfigAbrController(this);
  27227. const bufferController = this.bufferController = new ConfigBufferController(this);
  27228. const capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  27229. const fpsController = new ConfigFpsController(this);
  27230. const playListLoader = new PlaylistLoader(this);
  27231. const id3TrackController = new ID3TrackController(this);
  27232. const ConfigContentSteeringController = config.contentSteeringController;
  27233. // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first
  27234. const contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null;
  27235. const levelController = this.levelController = new LevelController(this, contentSteering);
  27236. // FragmentTracker must be defined before StreamController because the order of event handling is important
  27237. const fragmentTracker = new FragmentTracker(this);
  27238. const keyLoader = new KeyLoader(this.config);
  27239. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  27240. // Cap level controller uses streamController to flush the buffer
  27241. capLevelController.setStreamController(streamController);
  27242. // fpsController uses streamController to switch when frames are being dropped
  27243. fpsController.setStreamController(streamController);
  27244. const networkControllers = [playListLoader, levelController, streamController];
  27245. if (contentSteering) {
  27246. networkControllers.splice(1, 0, contentSteering);
  27247. }
  27248. this.networkControllers = networkControllers;
  27249. const coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  27250. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  27251. const AudioStreamControllerClass = config.audioStreamController;
  27252. if (AudioStreamControllerClass) {
  27253. networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  27254. }
  27255. // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important
  27256. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  27257. const SubtitleStreamControllerClass = config.subtitleStreamController;
  27258. if (SubtitleStreamControllerClass) {
  27259. networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  27260. }
  27261. this.createController(config.timelineController, coreComponents);
  27262. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  27263. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  27264. this.latencyController = this.createController(LatencyController, coreComponents);
  27265. this.coreComponents = coreComponents;
  27266. // Error controller handles errors before and after all other controllers
  27267. // This listener will be invoked after all other controllers error listeners
  27268. networkControllers.push(errorController);
  27269. const onErrorOut = errorController.onErrorOut;
  27270. if (typeof onErrorOut === 'function') {
  27271. this.on(Events.ERROR, onErrorOut, errorController);
  27272. }
  27273. }
  27274. createController(ControllerClass, components) {
  27275. if (ControllerClass) {
  27276. const controllerInstance = new ControllerClass(this);
  27277. if (components) {
  27278. components.push(controllerInstance);
  27279. }
  27280. return controllerInstance;
  27281. }
  27282. return null;
  27283. }
  27284. // Delegate the EventEmitter through the public API of Hls.js
  27285. on(event, listener, context = this) {
  27286. this._emitter.on(event, listener, context);
  27287. }
  27288. once(event, listener, context = this) {
  27289. this._emitter.once(event, listener, context);
  27290. }
  27291. removeAllListeners(event) {
  27292. this._emitter.removeAllListeners(event);
  27293. }
  27294. off(event, listener, context = this, once) {
  27295. this._emitter.off(event, listener, context, once);
  27296. }
  27297. listeners(event) {
  27298. return this._emitter.listeners(event);
  27299. }
  27300. emit(event, name, eventObject) {
  27301. return this._emitter.emit(event, name, eventObject);
  27302. }
  27303. trigger(event, eventObject) {
  27304. if (this.config.debug) {
  27305. return this.emit(event, event, eventObject);
  27306. } else {
  27307. try {
  27308. return this.emit(event, event, eventObject);
  27309. } catch (error) {
  27310. logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  27311. // Prevent recursion in error event handlers that throw #5497
  27312. if (!this.triggeringException) {
  27313. this.triggeringException = true;
  27314. const fatal = event === Events.ERROR;
  27315. this.trigger(Events.ERROR, {
  27316. type: ErrorTypes.OTHER_ERROR,
  27317. details: ErrorDetails.INTERNAL_EXCEPTION,
  27318. fatal,
  27319. event,
  27320. error
  27321. });
  27322. this.triggeringException = false;
  27323. }
  27324. }
  27325. }
  27326. return false;
  27327. }
  27328. listenerCount(event) {
  27329. return this._emitter.listenerCount(event);
  27330. }
  27331. /**
  27332. * Dispose of the instance
  27333. */
  27334. destroy() {
  27335. logger.log('destroy');
  27336. this.trigger(Events.DESTROYING, undefined);
  27337. this.detachMedia();
  27338. this.removeAllListeners();
  27339. this._autoLevelCapping = -1;
  27340. this.url = null;
  27341. this.networkControllers.forEach(component => component.destroy());
  27342. this.networkControllers.length = 0;
  27343. this.coreComponents.forEach(component => component.destroy());
  27344. this.coreComponents.length = 0;
  27345. // Remove any references that could be held in config options or callbacks
  27346. const config = this.config;
  27347. config.xhrSetup = config.fetchSetup = undefined;
  27348. // @ts-ignore
  27349. this.userConfig = null;
  27350. }
  27351. /**
  27352. * Attaches Hls.js to a media element
  27353. */
  27354. attachMedia(media) {
  27355. logger.log('attachMedia');
  27356. this._media = media;
  27357. this.trigger(Events.MEDIA_ATTACHING, {
  27358. media: media
  27359. });
  27360. }
  27361. /**
  27362. * Detach Hls.js from the media
  27363. */
  27364. detachMedia() {
  27365. logger.log('detachMedia');
  27366. this.trigger(Events.MEDIA_DETACHING, undefined);
  27367. this._media = null;
  27368. }
  27369. /**
  27370. * Set the source URL. Can be relative or absolute.
  27371. */
  27372. loadSource(url) {
  27373. this.stopLoad();
  27374. const media = this.media;
  27375. const loadedSource = this.url;
  27376. const loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  27377. alwaysNormalize: true
  27378. });
  27379. this._autoLevelCapping = -1;
  27380. this._maxHdcpLevel = null;
  27381. logger.log(`loadSource:${loadingSource}`);
  27382. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  27383. this.detachMedia();
  27384. this.attachMedia(media);
  27385. }
  27386. // when attaching to a source URL, trigger a playlist load
  27387. this.trigger(Events.MANIFEST_LOADING, {
  27388. url: url
  27389. });
  27390. }
  27391. /**
  27392. * Start loading data from the stream source.
  27393. * Depending on default config, client starts loading automatically when a source is set.
  27394. *
  27395. * @param startPosition - Set the start position to stream from.
  27396. * Defaults to -1 (None: starts from earliest point)
  27397. */
  27398. startLoad(startPosition = -1) {
  27399. logger.log(`startLoad(${startPosition})`);
  27400. this.started = true;
  27401. this.networkControllers.forEach(controller => {
  27402. controller.startLoad(startPosition);
  27403. });
  27404. }
  27405. /**
  27406. * Stop loading of any stream data.
  27407. */
  27408. stopLoad() {
  27409. logger.log('stopLoad');
  27410. this.started = false;
  27411. this.networkControllers.forEach(controller => {
  27412. controller.stopLoad();
  27413. });
  27414. }
  27415. /**
  27416. * Resumes stream controller segment loading if previously started.
  27417. */
  27418. resumeBuffering() {
  27419. if (this.started) {
  27420. this.networkControllers.forEach(controller => {
  27421. if ('fragmentLoader' in controller) {
  27422. controller.startLoad(-1);
  27423. }
  27424. });
  27425. }
  27426. }
  27427. /**
  27428. * Stops stream controller segment loading without changing 'started' state like stopLoad().
  27429. * This allows for media buffering to be paused without interupting playlist loading.
  27430. */
  27431. pauseBuffering() {
  27432. this.networkControllers.forEach(controller => {
  27433. if ('fragmentLoader' in controller) {
  27434. controller.stopLoad();
  27435. }
  27436. });
  27437. }
  27438. /**
  27439. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  27440. */
  27441. swapAudioCodec() {
  27442. logger.log('swapAudioCodec');
  27443. this.streamController.swapAudioCodec();
  27444. }
  27445. /**
  27446. * When the media-element fails, this allows to detach and then re-attach it
  27447. * as one call (convenience method).
  27448. *
  27449. * Automatic recovery of media-errors by this process is configurable.
  27450. */
  27451. recoverMediaError() {
  27452. logger.log('recoverMediaError');
  27453. const media = this._media;
  27454. this.detachMedia();
  27455. if (media) {
  27456. this.attachMedia(media);
  27457. }
  27458. }
  27459. removeLevel(levelIndex) {
  27460. this.levelController.removeLevel(levelIndex);
  27461. }
  27462. /**
  27463. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  27464. */
  27465. get levels() {
  27466. const levels = this.levelController.levels;
  27467. return levels ? levels : [];
  27468. }
  27469. /**
  27470. * Index of quality level (variant) currently played
  27471. */
  27472. get currentLevel() {
  27473. return this.streamController.currentLevel;
  27474. }
  27475. /**
  27476. * 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.
  27477. */
  27478. set currentLevel(newLevel) {
  27479. logger.log(`set currentLevel:${newLevel}`);
  27480. this.levelController.manualLevel = newLevel;
  27481. this.streamController.immediateLevelSwitch();
  27482. }
  27483. /**
  27484. * Index of next quality level loaded as scheduled by stream controller.
  27485. */
  27486. get nextLevel() {
  27487. return this.streamController.nextLevel;
  27488. }
  27489. /**
  27490. * Set quality level index for next loaded data.
  27491. * This will switch the video quality asap, without interrupting playback.
  27492. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  27493. * @param newLevel - Pass -1 for automatic level selection
  27494. */
  27495. set nextLevel(newLevel) {
  27496. logger.log(`set nextLevel:${newLevel}`);
  27497. this.levelController.manualLevel = newLevel;
  27498. this.streamController.nextLevelSwitch();
  27499. }
  27500. /**
  27501. * Return the quality level of the currently or last (of none is loaded currently) segment
  27502. */
  27503. get loadLevel() {
  27504. return this.levelController.level;
  27505. }
  27506. /**
  27507. * Set quality level index for next loaded data in a conservative way.
  27508. * This will switch the quality without flushing, but interrupt current loading.
  27509. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  27510. * @param newLevel - Pass -1 for automatic level selection
  27511. */
  27512. set loadLevel(newLevel) {
  27513. logger.log(`set loadLevel:${newLevel}`);
  27514. this.levelController.manualLevel = newLevel;
  27515. }
  27516. /**
  27517. * get next quality level loaded
  27518. */
  27519. get nextLoadLevel() {
  27520. return this.levelController.nextLoadLevel;
  27521. }
  27522. /**
  27523. * Set quality level of next loaded segment in a fully "non-destructive" way.
  27524. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  27525. */
  27526. set nextLoadLevel(level) {
  27527. this.levelController.nextLoadLevel = level;
  27528. }
  27529. /**
  27530. * Return "first level": like a default level, if not set,
  27531. * falls back to index of first level referenced in manifest
  27532. */
  27533. get firstLevel() {
  27534. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  27535. }
  27536. /**
  27537. * Sets "first-level", see getter.
  27538. */
  27539. set firstLevel(newLevel) {
  27540. logger.log(`set firstLevel:${newLevel}`);
  27541. this.levelController.firstLevel = newLevel;
  27542. }
  27543. /**
  27544. * Return the desired start level for the first fragment that will be loaded.
  27545. * The default value of -1 indicates automatic start level selection.
  27546. * Setting hls.nextAutoLevel without setting a startLevel will result in
  27547. * the nextAutoLevel value being used for one fragment load.
  27548. */
  27549. get startLevel() {
  27550. const startLevel = this.levelController.startLevel;
  27551. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  27552. return this.abrController.forcedAutoLevel;
  27553. }
  27554. return startLevel;
  27555. }
  27556. /**
  27557. * set start level (level of first fragment that will be played back)
  27558. * if not overrided by user, first level appearing in manifest will be used as start level
  27559. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  27560. * (determined from download of first segment)
  27561. */
  27562. set startLevel(newLevel) {
  27563. logger.log(`set startLevel:${newLevel}`);
  27564. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  27565. if (newLevel !== -1) {
  27566. newLevel = Math.max(newLevel, this.minAutoLevel);
  27567. }
  27568. this.levelController.startLevel = newLevel;
  27569. }
  27570. /**
  27571. * Whether level capping is enabled.
  27572. * Default value is set via `config.capLevelToPlayerSize`.
  27573. */
  27574. get capLevelToPlayerSize() {
  27575. return this.config.capLevelToPlayerSize;
  27576. }
  27577. /**
  27578. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  27579. */
  27580. set capLevelToPlayerSize(shouldStartCapping) {
  27581. const newCapLevelToPlayerSize = !!shouldStartCapping;
  27582. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  27583. if (newCapLevelToPlayerSize) {
  27584. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  27585. } else {
  27586. this.capLevelController.stopCapping();
  27587. this.autoLevelCapping = -1;
  27588. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  27589. }
  27590. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  27591. }
  27592. }
  27593. /**
  27594. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  27595. */
  27596. get autoLevelCapping() {
  27597. return this._autoLevelCapping;
  27598. }
  27599. /**
  27600. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  27601. */
  27602. get bandwidthEstimate() {
  27603. const {
  27604. bwEstimator
  27605. } = this.abrController;
  27606. if (!bwEstimator) {
  27607. return NaN;
  27608. }
  27609. return bwEstimator.getEstimate();
  27610. }
  27611. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  27612. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  27613. }
  27614. /**
  27615. * get time to first byte estimate
  27616. * @type {number}
  27617. */
  27618. get ttfbEstimate() {
  27619. const {
  27620. bwEstimator
  27621. } = this.abrController;
  27622. if (!bwEstimator) {
  27623. return NaN;
  27624. }
  27625. return bwEstimator.getEstimateTTFB();
  27626. }
  27627. /**
  27628. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  27629. */
  27630. set autoLevelCapping(newLevel) {
  27631. if (this._autoLevelCapping !== newLevel) {
  27632. logger.log(`set autoLevelCapping:${newLevel}`);
  27633. this._autoLevelCapping = newLevel;
  27634. this.levelController.checkMaxAutoUpdated();
  27635. }
  27636. }
  27637. get maxHdcpLevel() {
  27638. return this._maxHdcpLevel;
  27639. }
  27640. set maxHdcpLevel(value) {
  27641. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  27642. this._maxHdcpLevel = value;
  27643. this.levelController.checkMaxAutoUpdated();
  27644. }
  27645. }
  27646. /**
  27647. * True when automatic level selection enabled
  27648. */
  27649. get autoLevelEnabled() {
  27650. return this.levelController.manualLevel === -1;
  27651. }
  27652. /**
  27653. * Level set manually (if any)
  27654. */
  27655. get manualLevel() {
  27656. return this.levelController.manualLevel;
  27657. }
  27658. /**
  27659. * min level selectable in auto mode according to config.minAutoBitrate
  27660. */
  27661. get minAutoLevel() {
  27662. const {
  27663. levels,
  27664. config: {
  27665. minAutoBitrate
  27666. }
  27667. } = this;
  27668. if (!levels) return 0;
  27669. const len = levels.length;
  27670. for (let i = 0; i < len; i++) {
  27671. if (levels[i].maxBitrate >= minAutoBitrate) {
  27672. return i;
  27673. }
  27674. }
  27675. return 0;
  27676. }
  27677. /**
  27678. * max level selectable in auto mode according to autoLevelCapping
  27679. */
  27680. get maxAutoLevel() {
  27681. const {
  27682. levels,
  27683. autoLevelCapping,
  27684. maxHdcpLevel
  27685. } = this;
  27686. let maxAutoLevel;
  27687. if (autoLevelCapping === -1 && levels != null && levels.length) {
  27688. maxAutoLevel = levels.length - 1;
  27689. } else {
  27690. maxAutoLevel = autoLevelCapping;
  27691. }
  27692. if (maxHdcpLevel) {
  27693. for (let i = maxAutoLevel; i--;) {
  27694. const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  27695. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  27696. return i;
  27697. }
  27698. }
  27699. }
  27700. return maxAutoLevel;
  27701. }
  27702. get firstAutoLevel() {
  27703. return this.abrController.firstAutoLevel;
  27704. }
  27705. /**
  27706. * next automatically selected quality level
  27707. */
  27708. get nextAutoLevel() {
  27709. return this.abrController.nextAutoLevel;
  27710. }
  27711. /**
  27712. * this setter is used to force next auto level.
  27713. * this is useful to force a switch down in auto mode:
  27714. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  27715. * forced value is valid for one fragment. upon successful frag loading at forced level,
  27716. * this value will be resetted to -1 by ABR controller.
  27717. */
  27718. set nextAutoLevel(nextLevel) {
  27719. this.abrController.nextAutoLevel = nextLevel;
  27720. }
  27721. /**
  27722. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  27723. */
  27724. get playingDate() {
  27725. return this.streamController.currentProgramDateTime;
  27726. }
  27727. get mainForwardBufferInfo() {
  27728. return this.streamController.getMainFwdBufferInfo();
  27729. }
  27730. /**
  27731. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  27732. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  27733. */
  27734. setAudioOption(audioOption) {
  27735. var _this$audioTrackContr;
  27736. return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption);
  27737. }
  27738. /**
  27739. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  27740. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  27741. */
  27742. setSubtitleOption(subtitleOption) {
  27743. var _this$subtitleTrackCo;
  27744. (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption);
  27745. return null;
  27746. }
  27747. /**
  27748. * Get the complete list of audio tracks across all media groups
  27749. */
  27750. get allAudioTracks() {
  27751. const audioTrackController = this.audioTrackController;
  27752. return audioTrackController ? audioTrackController.allAudioTracks : [];
  27753. }
  27754. /**
  27755. * Get the list of selectable audio tracks
  27756. */
  27757. get audioTracks() {
  27758. const audioTrackController = this.audioTrackController;
  27759. return audioTrackController ? audioTrackController.audioTracks : [];
  27760. }
  27761. /**
  27762. * index of the selected audio track (index in audio track lists)
  27763. */
  27764. get audioTrack() {
  27765. const audioTrackController = this.audioTrackController;
  27766. return audioTrackController ? audioTrackController.audioTrack : -1;
  27767. }
  27768. /**
  27769. * selects an audio track, based on its index in audio track lists
  27770. */
  27771. set audioTrack(audioTrackId) {
  27772. const audioTrackController = this.audioTrackController;
  27773. if (audioTrackController) {
  27774. audioTrackController.audioTrack = audioTrackId;
  27775. }
  27776. }
  27777. /**
  27778. * get the complete list of subtitle tracks across all media groups
  27779. */
  27780. get allSubtitleTracks() {
  27781. const subtitleTrackController = this.subtitleTrackController;
  27782. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  27783. }
  27784. /**
  27785. * get alternate subtitle tracks list from playlist
  27786. */
  27787. get subtitleTracks() {
  27788. const subtitleTrackController = this.subtitleTrackController;
  27789. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  27790. }
  27791. /**
  27792. * index of the selected subtitle track (index in subtitle track lists)
  27793. */
  27794. get subtitleTrack() {
  27795. const subtitleTrackController = this.subtitleTrackController;
  27796. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  27797. }
  27798. get media() {
  27799. return this._media;
  27800. }
  27801. /**
  27802. * select an subtitle track, based on its index in subtitle track lists
  27803. */
  27804. set subtitleTrack(subtitleTrackId) {
  27805. const subtitleTrackController = this.subtitleTrackController;
  27806. if (subtitleTrackController) {
  27807. subtitleTrackController.subtitleTrack = subtitleTrackId;
  27808. }
  27809. }
  27810. /**
  27811. * Whether subtitle display is enabled or not
  27812. */
  27813. get subtitleDisplay() {
  27814. const subtitleTrackController = this.subtitleTrackController;
  27815. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  27816. }
  27817. /**
  27818. * Enable/disable subtitle display rendering
  27819. */
  27820. set subtitleDisplay(value) {
  27821. const subtitleTrackController = this.subtitleTrackController;
  27822. if (subtitleTrackController) {
  27823. subtitleTrackController.subtitleDisplay = value;
  27824. }
  27825. }
  27826. /**
  27827. * get mode for Low-Latency HLS loading
  27828. */
  27829. get lowLatencyMode() {
  27830. return this.config.lowLatencyMode;
  27831. }
  27832. /**
  27833. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  27834. */
  27835. set lowLatencyMode(mode) {
  27836. this.config.lowLatencyMode = mode;
  27837. }
  27838. /**
  27839. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  27840. * @returns null prior to loading live Playlist
  27841. */
  27842. get liveSyncPosition() {
  27843. return this.latencyController.liveSyncPosition;
  27844. }
  27845. /**
  27846. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  27847. * @returns 0 before first playlist is loaded
  27848. */
  27849. get latency() {
  27850. return this.latencyController.latency;
  27851. }
  27852. /**
  27853. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  27854. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  27855. * @returns 0 before first playlist is loaded
  27856. */
  27857. get maxLatency() {
  27858. return this.latencyController.maxLatency;
  27859. }
  27860. /**
  27861. * target distance from the edge as calculated by the latency controller
  27862. */
  27863. get targetLatency() {
  27864. return this.latencyController.targetLatency;
  27865. }
  27866. /**
  27867. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  27868. */
  27869. get drift() {
  27870. return this.latencyController.drift;
  27871. }
  27872. /**
  27873. * set to true when startLoad is called before MANIFEST_PARSED event
  27874. */
  27875. get forceStartLoad() {
  27876. return this.streamController.forceStartLoad;
  27877. }
  27878. }
  27879. Hls.defaultConfig = void 0;
  27880. export { AbrController, AttrList, AudioStreamController, AudioTrackController, BasePlaylistController, BaseSegment, BaseStreamController, BufferController, CMCDController, CapLevelController, ChunkMetadata, ContentSteeringController, DateRange, EMEController, ErrorActionFlags, ErrorController, ErrorDetails, ErrorTypes, Events, FPSController, Fragment, Hls, HlsSkip, HlsUrlParameters, KeySystemFormats, KeySystems, Level, LevelDetails, LevelKey, LoadStats, MetadataSchema, NetworkErrorAction, Part, PlaylistLevelType, SubtitleStreamController, SubtitleTrackController, TimelineController, Hls as default, getMediaSource, isMSESupported, isSupported };
  27881. //# sourceMappingURL=hls.mjs.map