hls.mjs 971 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544
  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.11"}`);
  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. WIDEVINE: "edef8ba979d64acea3c827dcd51d21ed"
  1043. };
  1044. function keySystemIdToKeySystemDomain(systemId) {
  1045. if (systemId === KeySystemIds.WIDEVINE) {
  1046. return KeySystems.WIDEVINE;
  1047. // } else if (systemId === KeySystemIds.PLAYREADY) {
  1048. // return KeySystems.PLAYREADY;
  1049. // } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {
  1050. // return KeySystems.CLEARKEY;
  1051. }
  1052. }
  1053. function keySystemDomainToKeySystemFormat(keySystem) {
  1054. switch (keySystem) {
  1055. case KeySystems.FAIRPLAY:
  1056. return KeySystemFormats.FAIRPLAY;
  1057. case KeySystems.PLAYREADY:
  1058. return KeySystemFormats.PLAYREADY;
  1059. case KeySystems.WIDEVINE:
  1060. return KeySystemFormats.WIDEVINE;
  1061. case KeySystems.CLEARKEY:
  1062. return KeySystemFormats.CLEARKEY;
  1063. }
  1064. }
  1065. function getKeySystemsForConfig(config) {
  1066. const {
  1067. drmSystems,
  1068. widevineLicenseUrl
  1069. } = config;
  1070. const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter(keySystem => !!drmSystems[keySystem]) : [];
  1071. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  1072. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  1073. }
  1074. return keySystemsToAttempt;
  1075. }
  1076. const requestMediaKeySystemAccess = function (_optionalSelf$navigat) {
  1077. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  1078. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  1079. } else {
  1080. return null;
  1081. }
  1082. }();
  1083. /**
  1084. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  1085. */
  1086. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  1087. let initDataTypes;
  1088. switch (keySystem) {
  1089. case KeySystems.FAIRPLAY:
  1090. initDataTypes = ['cenc', 'sinf'];
  1091. break;
  1092. case KeySystems.WIDEVINE:
  1093. case KeySystems.PLAYREADY:
  1094. initDataTypes = ['cenc'];
  1095. break;
  1096. case KeySystems.CLEARKEY:
  1097. initDataTypes = ['cenc', 'keyids'];
  1098. break;
  1099. default:
  1100. throw new Error(`Unknown key-system: ${keySystem}`);
  1101. }
  1102. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  1103. }
  1104. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  1105. const baseConfig = {
  1106. initDataTypes: initDataTypes,
  1107. persistentState: drmSystemOptions.persistentState || 'optional',
  1108. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',
  1109. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || 'temporary'],
  1110. audioCapabilities: audioCodecs.map(codec => ({
  1111. contentType: `audio/mp4; codecs="${codec}"`,
  1112. robustness: drmSystemOptions.audioRobustness || '',
  1113. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  1114. })),
  1115. videoCapabilities: videoCodecs.map(codec => ({
  1116. contentType: `video/mp4; codecs="${codec}"`,
  1117. robustness: drmSystemOptions.videoRobustness || '',
  1118. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  1119. }))
  1120. };
  1121. return [baseConfig];
  1122. }
  1123. function sliceUint8(array, start, end) {
  1124. // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
  1125. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
  1126. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
  1127. }
  1128. // breaking up those two types in order to clarify what is happening in the decoding path.
  1129. /**
  1130. * Returns true if an ID3 header can be found at offset in data
  1131. * @param data - The data to search
  1132. * @param offset - The offset at which to start searching
  1133. */
  1134. const isHeader$2 = (data, offset) => {
  1135. /*
  1136. * http://id3.org/id3v2.3.0
  1137. * [0] = 'I'
  1138. * [1] = 'D'
  1139. * [2] = '3'
  1140. * [3,4] = {Version}
  1141. * [5] = {Flags}
  1142. * [6-9] = {ID3 Size}
  1143. *
  1144. * An ID3v2 tag can be detected with the following pattern:
  1145. * $49 44 33 yy yy xx zz zz zz zz
  1146. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  1147. */
  1148. if (offset + 10 <= data.length) {
  1149. // look for 'ID3' identifier
  1150. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  1151. // check version is within range
  1152. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1153. // check size is within range
  1154. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1155. return true;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. return false;
  1161. };
  1162. /**
  1163. * Returns true if an ID3 footer can be found at offset in data
  1164. * @param data - The data to search
  1165. * @param offset - The offset at which to start searching
  1166. */
  1167. const isFooter = (data, offset) => {
  1168. /*
  1169. * The footer is a copy of the header, but with a different identifier
  1170. */
  1171. if (offset + 10 <= data.length) {
  1172. // look for '3DI' identifier
  1173. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  1174. // check version is within range
  1175. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1176. // check size is within range
  1177. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1178. return true;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return false;
  1184. };
  1185. /**
  1186. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  1187. * @param data - The data to search in
  1188. * @param offset - The offset at which to start searching
  1189. * @returns the block of data containing any ID3 tags found
  1190. * or *undefined* if no header is found at the starting offset
  1191. */
  1192. const getID3Data = (data, offset) => {
  1193. const front = offset;
  1194. let length = 0;
  1195. while (isHeader$2(data, offset)) {
  1196. // ID3 header is 10 bytes
  1197. length += 10;
  1198. const size = readSize(data, offset + 6);
  1199. length += size;
  1200. if (isFooter(data, offset + 10)) {
  1201. // ID3 footer is 10 bytes
  1202. length += 10;
  1203. }
  1204. offset += length;
  1205. }
  1206. if (length > 0) {
  1207. return data.subarray(front, front + length);
  1208. }
  1209. return undefined;
  1210. };
  1211. const readSize = (data, offset) => {
  1212. let size = 0;
  1213. size = (data[offset] & 0x7f) << 21;
  1214. size |= (data[offset + 1] & 0x7f) << 14;
  1215. size |= (data[offset + 2] & 0x7f) << 7;
  1216. size |= data[offset + 3] & 0x7f;
  1217. return size;
  1218. };
  1219. const canParse$2 = (data, offset) => {
  1220. return isHeader$2(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
  1221. };
  1222. /**
  1223. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  1224. * @param data - Block of data containing one or more ID3 tags
  1225. */
  1226. const getTimeStamp = data => {
  1227. const frames = getID3Frames(data);
  1228. for (let i = 0; i < frames.length; i++) {
  1229. const frame = frames[i];
  1230. if (isTimeStampFrame(frame)) {
  1231. return readTimeStamp(frame);
  1232. }
  1233. }
  1234. return undefined;
  1235. };
  1236. /**
  1237. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  1238. */
  1239. const isTimeStampFrame = frame => {
  1240. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  1241. };
  1242. const getFrameData = data => {
  1243. /*
  1244. Frame ID $xx xx xx xx (four characters)
  1245. Size $xx xx xx xx
  1246. Flags $xx xx
  1247. */
  1248. const type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  1249. const size = readSize(data, 4);
  1250. // skip frame id, size, and flags
  1251. const offset = 10;
  1252. return {
  1253. type,
  1254. size,
  1255. data: data.subarray(offset, offset + size)
  1256. };
  1257. };
  1258. /**
  1259. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  1260. * @param id3Data - The ID3 data containing one or more ID3 tags
  1261. */
  1262. const getID3Frames = id3Data => {
  1263. let offset = 0;
  1264. const frames = [];
  1265. while (isHeader$2(id3Data, offset)) {
  1266. const size = readSize(id3Data, offset + 6);
  1267. // skip past ID3 header
  1268. offset += 10;
  1269. const end = offset + size;
  1270. // loop through frames in the ID3 tag
  1271. while (offset + 8 < end) {
  1272. const frameData = getFrameData(id3Data.subarray(offset));
  1273. const frame = decodeFrame(frameData);
  1274. if (frame) {
  1275. frames.push(frame);
  1276. }
  1277. // skip frame header and frame data
  1278. offset += frameData.size + 10;
  1279. }
  1280. if (isFooter(id3Data, offset)) {
  1281. offset += 10;
  1282. }
  1283. }
  1284. return frames;
  1285. };
  1286. const decodeFrame = frame => {
  1287. if (frame.type === 'PRIV') {
  1288. return decodePrivFrame(frame);
  1289. } else if (frame.type[0] === 'W') {
  1290. return decodeURLFrame(frame);
  1291. }
  1292. return decodeTextFrame(frame);
  1293. };
  1294. const decodePrivFrame = frame => {
  1295. /*
  1296. Format: <text string>\0<binary data>
  1297. */
  1298. if (frame.size < 2) {
  1299. return undefined;
  1300. }
  1301. const owner = utf8ArrayToStr(frame.data, true);
  1302. const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  1303. return {
  1304. key: frame.type,
  1305. info: owner,
  1306. data: privateData.buffer
  1307. };
  1308. };
  1309. const decodeTextFrame = frame => {
  1310. if (frame.size < 2) {
  1311. return undefined;
  1312. }
  1313. if (frame.type === 'TXXX') {
  1314. /*
  1315. Format:
  1316. [0] = {Text Encoding}
  1317. [1-?] = {Description}\0{Value}
  1318. */
  1319. let index = 1;
  1320. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1321. index += description.length + 1;
  1322. const value = utf8ArrayToStr(frame.data.subarray(index));
  1323. return {
  1324. key: frame.type,
  1325. info: description,
  1326. data: value
  1327. };
  1328. }
  1329. /*
  1330. Format:
  1331. [0] = {Text Encoding}
  1332. [1-?] = {Value}
  1333. */
  1334. const text = utf8ArrayToStr(frame.data.subarray(1));
  1335. return {
  1336. key: frame.type,
  1337. data: text
  1338. };
  1339. };
  1340. const decodeURLFrame = frame => {
  1341. if (frame.type === 'WXXX') {
  1342. /*
  1343. Format:
  1344. [0] = {Text Encoding}
  1345. [1-?] = {Description}\0{URL}
  1346. */
  1347. if (frame.size < 2) {
  1348. return undefined;
  1349. }
  1350. let index = 1;
  1351. const description = utf8ArrayToStr(frame.data.subarray(index), true);
  1352. index += description.length + 1;
  1353. const value = utf8ArrayToStr(frame.data.subarray(index));
  1354. return {
  1355. key: frame.type,
  1356. info: description,
  1357. data: value
  1358. };
  1359. }
  1360. /*
  1361. Format:
  1362. [0-?] = {URL}
  1363. */
  1364. const url = utf8ArrayToStr(frame.data);
  1365. return {
  1366. key: frame.type,
  1367. data: url
  1368. };
  1369. };
  1370. const readTimeStamp = timeStampFrame => {
  1371. if (timeStampFrame.data.byteLength === 8) {
  1372. const data = new Uint8Array(timeStampFrame.data);
  1373. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  1374. // with the upper 31 bits set to zero.
  1375. const pts33Bit = data[3] & 0x1;
  1376. let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  1377. timestamp /= 45;
  1378. if (pts33Bit) {
  1379. timestamp += 47721858.84;
  1380. } // 2^32 / 90
  1381. return Math.round(timestamp);
  1382. }
  1383. return undefined;
  1384. };
  1385. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1386. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1387. /* utf.js - UTF-8 <=> UTF-16 convertion
  1388. *
  1389. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1390. * Version: 1.0
  1391. * LastModified: Dec 25 1999
  1392. * This library is free. You can redistribute it and/or modify it.
  1393. */
  1394. const utf8ArrayToStr = (array, exitOnNull = false) => {
  1395. const decoder = getTextDecoder();
  1396. if (decoder) {
  1397. const decoded = decoder.decode(array);
  1398. if (exitOnNull) {
  1399. // grab up to the first null
  1400. const idx = decoded.indexOf('\0');
  1401. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1402. }
  1403. // remove any null characters
  1404. return decoded.replace(/\0/g, '');
  1405. }
  1406. const len = array.length;
  1407. let c;
  1408. let char2;
  1409. let char3;
  1410. let out = '';
  1411. let i = 0;
  1412. while (i < len) {
  1413. c = array[i++];
  1414. if (c === 0x00 && exitOnNull) {
  1415. return out;
  1416. } else if (c === 0x00 || c === 0x03) {
  1417. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1418. continue;
  1419. }
  1420. switch (c >> 4) {
  1421. case 0:
  1422. case 1:
  1423. case 2:
  1424. case 3:
  1425. case 4:
  1426. case 5:
  1427. case 6:
  1428. case 7:
  1429. // 0xxxxxxx
  1430. out += String.fromCharCode(c);
  1431. break;
  1432. case 12:
  1433. case 13:
  1434. // 110x xxxx 10xx xxxx
  1435. char2 = array[i++];
  1436. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1437. break;
  1438. case 14:
  1439. // 1110 xxxx 10xx xxxx 10xx xxxx
  1440. char2 = array[i++];
  1441. char3 = array[i++];
  1442. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1443. break;
  1444. }
  1445. }
  1446. return out;
  1447. };
  1448. let decoder;
  1449. function getTextDecoder() {
  1450. // On Play Station 4, TextDecoder is defined but partially implemented.
  1451. // Manual decoding option is preferable
  1452. if (navigator.userAgent.includes('PlayStation 4')) {
  1453. return;
  1454. }
  1455. if (!decoder && typeof self.TextDecoder !== 'undefined') {
  1456. decoder = new self.TextDecoder('utf-8');
  1457. }
  1458. return decoder;
  1459. }
  1460. /**
  1461. * hex dump helper class
  1462. */
  1463. const Hex = {
  1464. hexDump: function (array) {
  1465. let str = '';
  1466. for (let i = 0; i < array.length; i++) {
  1467. let h = array[i].toString(16);
  1468. if (h.length < 2) {
  1469. h = '0' + h;
  1470. }
  1471. str += h;
  1472. }
  1473. return str;
  1474. }
  1475. };
  1476. const UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1477. const push = [].push;
  1478. // We are using fixed track IDs for driving the MP4 remuxer
  1479. // instead of following the TS PIDs.
  1480. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1481. // may not like if there are TrackID "switches"
  1482. // See https://github.com/video-dev/hls.js/issues/1331
  1483. // Here we are mapping our internal track types to constant MP4 track IDs
  1484. // With MSE currently one can only have one track of each, and we are muxing
  1485. // whatever video/audio rendition in them.
  1486. const RemuxerTrackIdConfig = {
  1487. video: 1,
  1488. audio: 2,
  1489. id3: 3,
  1490. text: 4
  1491. };
  1492. function bin2str(data) {
  1493. return String.fromCharCode.apply(null, data);
  1494. }
  1495. function readUint16(buffer, offset) {
  1496. const val = buffer[offset] << 8 | buffer[offset + 1];
  1497. return val < 0 ? 65536 + val : val;
  1498. }
  1499. function readUint32(buffer, offset) {
  1500. const val = readSint32(buffer, offset);
  1501. return val < 0 ? 4294967296 + val : val;
  1502. }
  1503. function readUint64(buffer, offset) {
  1504. let result = readUint32(buffer, offset);
  1505. result *= Math.pow(2, 32);
  1506. result += readUint32(buffer, offset + 4);
  1507. return result;
  1508. }
  1509. function readSint32(buffer, offset) {
  1510. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1511. }
  1512. function writeUint32(buffer, offset, value) {
  1513. buffer[offset] = value >> 24;
  1514. buffer[offset + 1] = value >> 16 & 0xff;
  1515. buffer[offset + 2] = value >> 8 & 0xff;
  1516. buffer[offset + 3] = value & 0xff;
  1517. }
  1518. // Find "moof" box
  1519. function hasMoofData(data) {
  1520. const end = data.byteLength;
  1521. for (let i = 0; i < end;) {
  1522. const size = readUint32(data, i);
  1523. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1524. return true;
  1525. }
  1526. i = size > 1 ? i + size : end;
  1527. }
  1528. return false;
  1529. }
  1530. // Find the data for a box specified by its path
  1531. function findBox(data, path) {
  1532. const results = [];
  1533. if (!path.length) {
  1534. // short-circuit the search for empty paths
  1535. return results;
  1536. }
  1537. const end = data.byteLength;
  1538. for (let i = 0; i < end;) {
  1539. const size = readUint32(data, i);
  1540. const type = bin2str(data.subarray(i + 4, i + 8));
  1541. const endbox = size > 1 ? i + size : end;
  1542. if (type === path[0]) {
  1543. if (path.length === 1) {
  1544. // this is the end of the path and we've found the box we were
  1545. // looking for
  1546. results.push(data.subarray(i + 8, endbox));
  1547. } else {
  1548. // recursively search for the next box along the path
  1549. const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1550. if (subresults.length) {
  1551. push.apply(results, subresults);
  1552. }
  1553. }
  1554. }
  1555. i = endbox;
  1556. }
  1557. // we've finished searching all of data
  1558. return results;
  1559. }
  1560. function parseSegmentIndex(sidx) {
  1561. const references = [];
  1562. const version = sidx[0];
  1563. // set initial offset, we skip the reference ID (not needed)
  1564. let index = 8;
  1565. const timescale = readUint32(sidx, index);
  1566. index += 4;
  1567. let earliestPresentationTime = 0;
  1568. let firstOffset = 0;
  1569. if (version === 0) {
  1570. earliestPresentationTime = readUint32(sidx, index);
  1571. firstOffset = readUint32(sidx, index + 4);
  1572. index += 8;
  1573. } else {
  1574. earliestPresentationTime = readUint64(sidx, index);
  1575. firstOffset = readUint64(sidx, index + 8);
  1576. index += 16;
  1577. }
  1578. // skip reserved
  1579. index += 2;
  1580. let startByte = sidx.length + firstOffset;
  1581. const referencesCount = readUint16(sidx, index);
  1582. index += 2;
  1583. for (let i = 0; i < referencesCount; i++) {
  1584. let referenceIndex = index;
  1585. const referenceInfo = readUint32(sidx, referenceIndex);
  1586. referenceIndex += 4;
  1587. const referenceSize = referenceInfo & 0x7fffffff;
  1588. const referenceType = (referenceInfo & 0x80000000) >>> 31;
  1589. if (referenceType === 1) {
  1590. logger.warn('SIDX has hierarchical references (not supported)');
  1591. return null;
  1592. }
  1593. const subsegmentDuration = readUint32(sidx, referenceIndex);
  1594. referenceIndex += 4;
  1595. references.push({
  1596. referenceSize,
  1597. subsegmentDuration,
  1598. // unscaled
  1599. info: {
  1600. duration: subsegmentDuration / timescale,
  1601. start: startByte,
  1602. end: startByte + referenceSize - 1
  1603. }
  1604. });
  1605. startByte += referenceSize;
  1606. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1607. // for |sapDelta|.
  1608. referenceIndex += 4;
  1609. // skip to next ref
  1610. index = referenceIndex;
  1611. }
  1612. return {
  1613. earliestPresentationTime,
  1614. timescale,
  1615. version,
  1616. referencesCount,
  1617. references
  1618. };
  1619. }
  1620. /**
  1621. * Parses an MP4 initialization segment and extracts stream type and
  1622. * timescale values for any declared tracks. Timescale values indicate the
  1623. * number of clock ticks per second to assume for time-based values
  1624. * elsewhere in the MP4.
  1625. *
  1626. * To determine the start time of an MP4, you need two pieces of
  1627. * information: the timescale unit and the earliest base media decode
  1628. * time. Multiple timescales can be specified within an MP4 but the
  1629. * base media decode time is always expressed in the timescale from
  1630. * the media header box for the track:
  1631. * ```
  1632. * moov > trak > mdia > mdhd.timescale
  1633. * moov > trak > mdia > hdlr
  1634. * ```
  1635. * @param initSegment the bytes of the init segment
  1636. * @returns a hash of track type to timescale values or null if
  1637. * the init segment is malformed.
  1638. */
  1639. function parseInitSegment(initSegment) {
  1640. const result = [];
  1641. const traks = findBox(initSegment, ['moov', 'trak']);
  1642. for (let i = 0; i < traks.length; i++) {
  1643. const trak = traks[i];
  1644. const tkhd = findBox(trak, ['tkhd'])[0];
  1645. if (tkhd) {
  1646. let version = tkhd[0];
  1647. const trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1648. const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1649. if (mdhd) {
  1650. version = mdhd[0];
  1651. const timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1652. const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1653. if (hdlr) {
  1654. const hdlrType = bin2str(hdlr.subarray(8, 12));
  1655. const type = {
  1656. soun: ElementaryStreamTypes.AUDIO,
  1657. vide: ElementaryStreamTypes.VIDEO
  1658. }[hdlrType];
  1659. if (type) {
  1660. // Parse codec details
  1661. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1662. const stsdData = parseStsd(stsd);
  1663. result[trackId] = {
  1664. timescale,
  1665. type
  1666. };
  1667. result[type] = _objectSpread2({
  1668. timescale,
  1669. id: trackId
  1670. }, stsdData);
  1671. }
  1672. }
  1673. }
  1674. }
  1675. }
  1676. const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1677. trex.forEach(trex => {
  1678. const trackId = readUint32(trex, 4);
  1679. const track = result[trackId];
  1680. if (track) {
  1681. track.default = {
  1682. duration: readUint32(trex, 12),
  1683. flags: readUint32(trex, 20)
  1684. };
  1685. }
  1686. });
  1687. return result;
  1688. }
  1689. function parseStsd(stsd) {
  1690. const sampleEntries = stsd.subarray(8);
  1691. const sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1692. const fourCC = bin2str(sampleEntries.subarray(4, 8));
  1693. let codec = fourCC;
  1694. const encrypted = fourCC === 'enca' || fourCC === 'encv';
  1695. if (encrypted) {
  1696. const encBox = findBox(sampleEntries, [fourCC])[0];
  1697. const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1698. const sinfs = findBox(encBoxChildren, ['sinf']);
  1699. sinfs.forEach(sinf => {
  1700. const schm = findBox(sinf, ['schm'])[0];
  1701. if (schm) {
  1702. const scheme = bin2str(schm.subarray(4, 8));
  1703. if (scheme === 'cbcs' || scheme === 'cenc') {
  1704. const frma = findBox(sinf, ['frma'])[0];
  1705. if (frma) {
  1706. // for encrypted content codec fourCC will be in frma
  1707. codec = bin2str(frma);
  1708. }
  1709. }
  1710. }
  1711. });
  1712. }
  1713. switch (codec) {
  1714. case 'avc1':
  1715. case 'avc2':
  1716. case 'avc3':
  1717. case 'avc4':
  1718. {
  1719. // extract profile + compatibility + level out of avcC box
  1720. const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1721. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1722. break;
  1723. }
  1724. case 'mp4a':
  1725. {
  1726. const codecBox = findBox(sampleEntries, [fourCC])[0];
  1727. const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1728. if (esdsBox && esdsBox.length > 12) {
  1729. let i = 4;
  1730. // ES Descriptor tag
  1731. if (esdsBox[i++] !== 0x03) {
  1732. break;
  1733. }
  1734. i = skipBERInteger(esdsBox, i);
  1735. i += 2; // skip es_id;
  1736. const flags = esdsBox[i++];
  1737. if (flags & 0x80) {
  1738. i += 2; // skip dependency es_id
  1739. }
  1740. if (flags & 0x40) {
  1741. i += esdsBox[i++]; // skip URL
  1742. }
  1743. // Decoder config descriptor
  1744. if (esdsBox[i++] !== 0x04) {
  1745. break;
  1746. }
  1747. i = skipBERInteger(esdsBox, i);
  1748. const objectType = esdsBox[i++];
  1749. if (objectType === 0x40) {
  1750. codec += '.' + toHex(objectType);
  1751. } else {
  1752. break;
  1753. }
  1754. i += 12;
  1755. // Decoder specific info
  1756. if (esdsBox[i++] !== 0x05) {
  1757. break;
  1758. }
  1759. i = skipBERInteger(esdsBox, i);
  1760. const firstByte = esdsBox[i++];
  1761. let audioObjectType = (firstByte & 0xf8) >> 3;
  1762. if (audioObjectType === 31) {
  1763. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1764. }
  1765. codec += '.' + audioObjectType;
  1766. }
  1767. break;
  1768. }
  1769. case 'hvc1':
  1770. case 'hev1':
  1771. {
  1772. const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1773. const profileByte = hvcCBox[1];
  1774. const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1775. const generalProfileIdc = profileByte & 0x1f;
  1776. const profileCompat = readUint32(hvcCBox, 2);
  1777. const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1778. const levelIDC = hvcCBox[12];
  1779. const constraintIndicator = hvcCBox.subarray(6, 12);
  1780. codec += '.' + profileSpace + generalProfileIdc;
  1781. codec += '.' + profileCompat.toString(16).toUpperCase();
  1782. codec += '.' + tierFlag + levelIDC;
  1783. let constraintString = '';
  1784. for (let i = constraintIndicator.length; i--;) {
  1785. const byte = constraintIndicator[i];
  1786. if (byte || constraintString) {
  1787. const encodedByte = byte.toString(16).toUpperCase();
  1788. constraintString = '.' + encodedByte + constraintString;
  1789. }
  1790. }
  1791. codec += constraintString;
  1792. break;
  1793. }
  1794. case 'dvh1':
  1795. case 'dvhe':
  1796. {
  1797. const dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];
  1798. const profile = dvcCBox[2] >> 1 & 0x7f;
  1799. const level = dvcCBox[2] << 5 & 0x20 | dvcCBox[3] >> 3 & 0x1f;
  1800. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);
  1801. break;
  1802. }
  1803. case 'vp09':
  1804. {
  1805. const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1806. const profile = vpcCBox[4];
  1807. const level = vpcCBox[5];
  1808. const bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1809. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  1810. break;
  1811. }
  1812. case 'av01':
  1813. {
  1814. const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1815. const profile = av1CBox[1] >>> 5;
  1816. const level = av1CBox[1] & 0x1f;
  1817. const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1818. const highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1819. const twelveBit = (av1CBox[2] & 0x20) >> 5;
  1820. const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1821. const monochrome = (av1CBox[2] & 0x10) >> 4;
  1822. const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1823. const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1824. const chromaSamplePosition = av1CBox[2] & 0x03;
  1825. // TODO: parse color_description_present_flag
  1826. // default it to BT.709/limited range for now
  1827. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1828. const colorPrimaries = 1;
  1829. const transferCharacteristics = 1;
  1830. const matrixCoefficients = 1;
  1831. const videoFullRangeFlag = 0;
  1832. codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1833. break;
  1834. }
  1835. }
  1836. return {
  1837. codec,
  1838. encrypted
  1839. };
  1840. }
  1841. function skipBERInteger(bytes, i) {
  1842. const limit = i + 5;
  1843. while (bytes[i++] & 0x80 && i < limit) {}
  1844. return i;
  1845. }
  1846. function toHex(x) {
  1847. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1848. }
  1849. function addLeadingZero(num) {
  1850. return (num < 10 ? '0' : '') + num;
  1851. }
  1852. function patchEncyptionData(initSegment, decryptdata) {
  1853. if (!initSegment || !decryptdata) {
  1854. return initSegment;
  1855. }
  1856. const keyId = decryptdata.keyId;
  1857. if (keyId && decryptdata.isCommonEncryption) {
  1858. const traks = findBox(initSegment, ['moov', 'trak']);
  1859. traks.forEach(trak => {
  1860. const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1861. // skip the sample entry count
  1862. const sampleEntries = stsd.subarray(8);
  1863. let encBoxes = findBox(sampleEntries, ['enca']);
  1864. const isAudio = encBoxes.length > 0;
  1865. if (!isAudio) {
  1866. encBoxes = findBox(sampleEntries, ['encv']);
  1867. }
  1868. encBoxes.forEach(enc => {
  1869. const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1870. const sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1871. sinfBoxes.forEach(sinf => {
  1872. const tenc = parseSinf(sinf);
  1873. if (tenc) {
  1874. // Look for default key id (keyID offset is always 8 within the tenc box):
  1875. const tencKeyId = tenc.subarray(8, 24);
  1876. if (!tencKeyId.some(b => b !== 0)) {
  1877. logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);
  1878. tenc.set(keyId, 8);
  1879. }
  1880. }
  1881. });
  1882. });
  1883. });
  1884. }
  1885. return initSegment;
  1886. }
  1887. function parseSinf(sinf) {
  1888. const schm = findBox(sinf, ['schm'])[0];
  1889. if (schm) {
  1890. const scheme = bin2str(schm.subarray(4, 8));
  1891. if (scheme === 'cbcs' || scheme === 'cenc') {
  1892. return findBox(sinf, ['schi', 'tenc'])[0];
  1893. }
  1894. }
  1895. logger.error(`[eme] missing 'schm' box`);
  1896. return null;
  1897. }
  1898. /**
  1899. * Determine the base media decode start time, in seconds, for an MP4
  1900. * fragment. If multiple fragments are specified, the earliest time is
  1901. * returned.
  1902. *
  1903. * The base media decode time can be parsed from track fragment
  1904. * metadata:
  1905. * ```
  1906. * moof > traf > tfdt.baseMediaDecodeTime
  1907. * ```
  1908. * It requires the timescale value from the mdhd to interpret.
  1909. *
  1910. * @param initData - a hash of track type to timescale values
  1911. * @param fmp4 - the bytes of the mp4 fragment
  1912. * @returns the earliest base media decode start time for the
  1913. * fragment, in seconds
  1914. */
  1915. function getStartDTS(initData, fmp4) {
  1916. // we need info from two children of each track fragment box
  1917. return findBox(fmp4, ['moof', 'traf']).reduce((result, traf) => {
  1918. const tfdt = findBox(traf, ['tfdt'])[0];
  1919. const version = tfdt[0];
  1920. const start = findBox(traf, ['tfhd']).reduce((result, tfhd) => {
  1921. // get the track id from the tfhd
  1922. const id = readUint32(tfhd, 4);
  1923. const track = initData[id];
  1924. if (track) {
  1925. let baseTime = readUint32(tfdt, 4);
  1926. if (version === 1) {
  1927. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1928. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1929. // https://github.com/video-dev/hls.js/issues/5303
  1930. if (baseTime === UINT32_MAX$1) {
  1931. logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);
  1932. return result;
  1933. }
  1934. baseTime *= UINT32_MAX$1 + 1;
  1935. baseTime += readUint32(tfdt, 8);
  1936. }
  1937. // assume a 90kHz clock if no timescale was specified
  1938. const scale = track.timescale || 90e3;
  1939. // convert base time to seconds
  1940. const startTime = baseTime / scale;
  1941. if (isFiniteNumber(startTime) && (result === null || startTime < result)) {
  1942. return startTime;
  1943. }
  1944. }
  1945. return result;
  1946. }, null);
  1947. if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {
  1948. return start;
  1949. }
  1950. return result;
  1951. }, null);
  1952. }
  1953. /*
  1954. For Reference:
  1955. aligned(8) class TrackFragmentHeaderBox
  1956. extends FullBox(‘tfhd’, 0, tf_flags){
  1957. unsigned int(32) track_ID;
  1958. // all the following are optional fields
  1959. unsigned int(64) base_data_offset;
  1960. unsigned int(32) sample_description_index;
  1961. unsigned int(32) default_sample_duration;
  1962. unsigned int(32) default_sample_size;
  1963. unsigned int(32) default_sample_flags
  1964. }
  1965. */
  1966. function getDuration(data, initData) {
  1967. let rawDuration = 0;
  1968. let videoDuration = 0;
  1969. let audioDuration = 0;
  1970. const trafs = findBox(data, ['moof', 'traf']);
  1971. for (let i = 0; i < trafs.length; i++) {
  1972. const traf = trafs[i];
  1973. // There is only one tfhd & trun per traf
  1974. // This is true for CMAF style content, and we should perhaps check the ftyp
  1975. // and only look for a single trun then, but for ISOBMFF we should check
  1976. // for multiple track runs.
  1977. const tfhd = findBox(traf, ['tfhd'])[0];
  1978. // get the track id from the tfhd
  1979. const id = readUint32(tfhd, 4);
  1980. const track = initData[id];
  1981. if (!track) {
  1982. continue;
  1983. }
  1984. const trackDefault = track.default;
  1985. const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  1986. let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
  1987. if (tfhdFlags & 0x000008) {
  1988. // 0x000008 indicates the presence of the default_sample_duration field
  1989. if (tfhdFlags & 0x000002) {
  1990. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  1991. // If present, the default_sample_duration exists at byte offset 12
  1992. sampleDuration = readUint32(tfhd, 12);
  1993. } else {
  1994. // Otherwise, the duration is at byte offset 8
  1995. sampleDuration = readUint32(tfhd, 8);
  1996. }
  1997. }
  1998. // assume a 90kHz clock if no timescale was specified
  1999. const timescale = track.timescale || 90e3;
  2000. const truns = findBox(traf, ['trun']);
  2001. for (let j = 0; j < truns.length; j++) {
  2002. rawDuration = computeRawDurationFromSamples(truns[j]);
  2003. if (!rawDuration && sampleDuration) {
  2004. const sampleCount = readUint32(truns[j], 4);
  2005. rawDuration = sampleDuration * sampleCount;
  2006. }
  2007. if (track.type === ElementaryStreamTypes.VIDEO) {
  2008. videoDuration += rawDuration / timescale;
  2009. } else if (track.type === ElementaryStreamTypes.AUDIO) {
  2010. audioDuration += rawDuration / timescale;
  2011. }
  2012. }
  2013. }
  2014. if (videoDuration === 0 && audioDuration === 0) {
  2015. // If duration samples are not available in the traf use sidx subsegment_duration
  2016. let sidxMinStart = Infinity;
  2017. let sidxMaxEnd = 0;
  2018. let sidxDuration = 0;
  2019. const sidxs = findBox(data, ['sidx']);
  2020. for (let i = 0; i < sidxs.length; i++) {
  2021. const sidx = parseSegmentIndex(sidxs[i]);
  2022. if (sidx != null && sidx.references) {
  2023. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2024. const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);
  2025. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2026. sidxDuration = sidxMaxEnd - sidxMinStart;
  2027. }
  2028. }
  2029. if (sidxDuration && isFiniteNumber(sidxDuration)) {
  2030. return sidxDuration;
  2031. }
  2032. }
  2033. if (videoDuration) {
  2034. return videoDuration;
  2035. }
  2036. return audioDuration;
  2037. }
  2038. /*
  2039. For Reference:
  2040. aligned(8) class TrackRunBox
  2041. extends FullBox(‘trun’, version, tr_flags) {
  2042. unsigned int(32) sample_count;
  2043. // the following are optional fields
  2044. signed int(32) data_offset;
  2045. unsigned int(32) first_sample_flags;
  2046. // all fields in the following array are optional
  2047. {
  2048. unsigned int(32) sample_duration;
  2049. unsigned int(32) sample_size;
  2050. unsigned int(32) sample_flags
  2051. if (version == 0)
  2052. { unsigned int(32)
  2053. else
  2054. { signed int(32)
  2055. }[ sample_count ]
  2056. }
  2057. */
  2058. function computeRawDurationFromSamples(trun) {
  2059. const flags = readUint32(trun, 0);
  2060. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  2061. // Each field is an int32, which is 4 bytes
  2062. let offset = 8;
  2063. // data-offset-present flag
  2064. if (flags & 0x000001) {
  2065. offset += 4;
  2066. }
  2067. // first-sample-flags-present flag
  2068. if (flags & 0x000004) {
  2069. offset += 4;
  2070. }
  2071. let duration = 0;
  2072. const sampleCount = readUint32(trun, 4);
  2073. for (let i = 0; i < sampleCount; i++) {
  2074. // sample-duration-present flag
  2075. if (flags & 0x000100) {
  2076. const sampleDuration = readUint32(trun, offset);
  2077. duration += sampleDuration;
  2078. offset += 4;
  2079. }
  2080. // sample-size-present flag
  2081. if (flags & 0x000200) {
  2082. offset += 4;
  2083. }
  2084. // sample-flags-present flag
  2085. if (flags & 0x000400) {
  2086. offset += 4;
  2087. }
  2088. // sample-composition-time-offsets-present flag
  2089. if (flags & 0x000800) {
  2090. offset += 4;
  2091. }
  2092. }
  2093. return duration;
  2094. }
  2095. function offsetStartDTS(initData, fmp4, timeOffset) {
  2096. findBox(fmp4, ['moof', 'traf']).forEach(traf => {
  2097. findBox(traf, ['tfhd']).forEach(tfhd => {
  2098. // get the track id from the tfhd
  2099. const id = readUint32(tfhd, 4);
  2100. const track = initData[id];
  2101. if (!track) {
  2102. return;
  2103. }
  2104. // assume a 90kHz clock if no timescale was specified
  2105. const timescale = track.timescale || 90e3;
  2106. // get the base media decode time from the tfdt
  2107. findBox(traf, ['tfdt']).forEach(tfdt => {
  2108. const version = tfdt[0];
  2109. const offset = timeOffset * timescale;
  2110. if (offset) {
  2111. let baseMediaDecodeTime = readUint32(tfdt, 4);
  2112. if (version === 0) {
  2113. baseMediaDecodeTime -= offset;
  2114. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2115. writeUint32(tfdt, 4, baseMediaDecodeTime);
  2116. } else {
  2117. baseMediaDecodeTime *= Math.pow(2, 32);
  2118. baseMediaDecodeTime += readUint32(tfdt, 8);
  2119. baseMediaDecodeTime -= offset;
  2120. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2121. const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
  2122. const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
  2123. writeUint32(tfdt, 4, upper);
  2124. writeUint32(tfdt, 8, lower);
  2125. }
  2126. }
  2127. });
  2128. });
  2129. });
  2130. }
  2131. // TODO: Check if the last moof+mdat pair is part of the valid range
  2132. function segmentValidRange(data) {
  2133. const segmentedRange = {
  2134. valid: null,
  2135. remainder: null
  2136. };
  2137. const moofs = findBox(data, ['moof']);
  2138. if (moofs.length < 2) {
  2139. segmentedRange.remainder = data;
  2140. return segmentedRange;
  2141. }
  2142. const last = moofs[moofs.length - 1];
  2143. // Offset by 8 bytes; findBox offsets the start by as much
  2144. segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);
  2145. segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);
  2146. return segmentedRange;
  2147. }
  2148. function appendUint8Array(data1, data2) {
  2149. const temp = new Uint8Array(data1.length + data2.length);
  2150. temp.set(data1);
  2151. temp.set(data2, data1.length);
  2152. return temp;
  2153. }
  2154. function parseSamples(timeOffset, track) {
  2155. const seiSamples = [];
  2156. const videoData = track.samples;
  2157. const timescale = track.timescale;
  2158. const trackId = track.id;
  2159. let isHEVCFlavor = false;
  2160. const moofs = findBox(videoData, ['moof']);
  2161. moofs.map(moof => {
  2162. const moofOffset = moof.byteOffset - 8;
  2163. const trafs = findBox(moof, ['traf']);
  2164. trafs.map(traf => {
  2165. // get the base media decode time from the tfdt
  2166. const baseTime = findBox(traf, ['tfdt']).map(tfdt => {
  2167. const version = tfdt[0];
  2168. let result = readUint32(tfdt, 4);
  2169. if (version === 1) {
  2170. result *= Math.pow(2, 32);
  2171. result += readUint32(tfdt, 8);
  2172. }
  2173. return result / timescale;
  2174. })[0];
  2175. if (baseTime !== undefined) {
  2176. timeOffset = baseTime;
  2177. }
  2178. return findBox(traf, ['tfhd']).map(tfhd => {
  2179. const id = readUint32(tfhd, 4);
  2180. const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2181. const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2182. const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2183. const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2184. let defaultSampleDuration = 0;
  2185. const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2186. let defaultSampleSize = 0;
  2187. const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2188. let tfhdOffset = 8;
  2189. if (id === trackId) {
  2190. if (baseDataOffsetPresent) {
  2191. tfhdOffset += 8;
  2192. }
  2193. if (sampleDescriptionIndexPresent) {
  2194. tfhdOffset += 4;
  2195. }
  2196. if (defaultSampleDurationPresent) {
  2197. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2198. tfhdOffset += 4;
  2199. }
  2200. if (defaultSampleSizePresent) {
  2201. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2202. tfhdOffset += 4;
  2203. }
  2204. if (defaultSampleFlagsPresent) {
  2205. tfhdOffset += 4;
  2206. }
  2207. if (track.type === 'video') {
  2208. isHEVCFlavor = isHEVC(track.codec);
  2209. }
  2210. findBox(traf, ['trun']).map(trun => {
  2211. const version = trun[0];
  2212. const flags = readUint32(trun, 0) & 0xffffff;
  2213. const dataOffsetPresent = (flags & 0x000001) !== 0;
  2214. let dataOffset = 0;
  2215. const firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2216. const sampleDurationPresent = (flags & 0x000100) !== 0;
  2217. let sampleDuration = 0;
  2218. const sampleSizePresent = (flags & 0x000200) !== 0;
  2219. let sampleSize = 0;
  2220. const sampleFlagsPresent = (flags & 0x000400) !== 0;
  2221. const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2222. let compositionOffset = 0;
  2223. const sampleCount = readUint32(trun, 4);
  2224. let trunOffset = 8; // past version, flags, and sample count
  2225. if (dataOffsetPresent) {
  2226. dataOffset = readUint32(trun, trunOffset);
  2227. trunOffset += 4;
  2228. }
  2229. if (firstSampleFlagsPresent) {
  2230. trunOffset += 4;
  2231. }
  2232. let sampleOffset = dataOffset + moofOffset;
  2233. for (let ix = 0; ix < sampleCount; ix++) {
  2234. if (sampleDurationPresent) {
  2235. sampleDuration = readUint32(trun, trunOffset);
  2236. trunOffset += 4;
  2237. } else {
  2238. sampleDuration = defaultSampleDuration;
  2239. }
  2240. if (sampleSizePresent) {
  2241. sampleSize = readUint32(trun, trunOffset);
  2242. trunOffset += 4;
  2243. } else {
  2244. sampleSize = defaultSampleSize;
  2245. }
  2246. if (sampleFlagsPresent) {
  2247. trunOffset += 4;
  2248. }
  2249. if (sampleCompositionOffsetsPresent) {
  2250. if (version === 0) {
  2251. compositionOffset = readUint32(trun, trunOffset);
  2252. } else {
  2253. compositionOffset = readSint32(trun, trunOffset);
  2254. }
  2255. trunOffset += 4;
  2256. }
  2257. if (track.type === ElementaryStreamTypes.VIDEO) {
  2258. let naluTotalSize = 0;
  2259. while (naluTotalSize < sampleSize) {
  2260. const naluSize = readUint32(videoData, sampleOffset);
  2261. sampleOffset += 4;
  2262. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2263. const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2264. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2265. }
  2266. sampleOffset += naluSize;
  2267. naluTotalSize += naluSize + 4;
  2268. }
  2269. }
  2270. timeOffset += sampleDuration / timescale;
  2271. }
  2272. });
  2273. }
  2274. });
  2275. });
  2276. });
  2277. return seiSamples;
  2278. }
  2279. function isHEVC(codec) {
  2280. if (!codec) {
  2281. return false;
  2282. }
  2283. const delimit = codec.indexOf('.');
  2284. const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  2285. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2286. // Dolby Vision
  2287. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2288. }
  2289. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2290. if (isHEVCFlavor) {
  2291. const naluType = naluHeader >> 1 & 0x3f;
  2292. return naluType === 39 || naluType === 40;
  2293. } else {
  2294. const naluType = naluHeader & 0x1f;
  2295. return naluType === 6;
  2296. }
  2297. }
  2298. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2299. const data = discardEPB(unescapedData);
  2300. let seiPtr = 0;
  2301. // skip nal header
  2302. seiPtr += headerSize;
  2303. let payloadType = 0;
  2304. let payloadSize = 0;
  2305. let b = 0;
  2306. while (seiPtr < data.length) {
  2307. payloadType = 0;
  2308. do {
  2309. if (seiPtr >= data.length) {
  2310. break;
  2311. }
  2312. b = data[seiPtr++];
  2313. payloadType += b;
  2314. } while (b === 0xff);
  2315. // Parse payload size.
  2316. payloadSize = 0;
  2317. do {
  2318. if (seiPtr >= data.length) {
  2319. break;
  2320. }
  2321. b = data[seiPtr++];
  2322. payloadSize += b;
  2323. } while (b === 0xff);
  2324. const leftOver = data.length - seiPtr;
  2325. // Create a variable to process the payload
  2326. let payPtr = seiPtr;
  2327. // Increment the seiPtr to the end of the payload
  2328. if (payloadSize < leftOver) {
  2329. seiPtr += payloadSize;
  2330. } else if (payloadSize > leftOver) {
  2331. // Some type of corruption has happened?
  2332. logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);
  2333. // We might be able to parse some data, but let's be safe and ignore it.
  2334. break;
  2335. }
  2336. if (payloadType === 4) {
  2337. const countryCode = data[payPtr++];
  2338. if (countryCode === 181) {
  2339. const providerCode = readUint16(data, payPtr);
  2340. payPtr += 2;
  2341. if (providerCode === 49) {
  2342. const userStructure = readUint32(data, payPtr);
  2343. payPtr += 4;
  2344. if (userStructure === 0x47413934) {
  2345. const userDataType = data[payPtr++];
  2346. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2347. if (userDataType === 3) {
  2348. const firstByte = data[payPtr++];
  2349. const totalCCs = 0x1f & firstByte;
  2350. const enabled = 0x40 & firstByte;
  2351. const totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2352. const byteArray = new Uint8Array(totalBytes);
  2353. if (enabled) {
  2354. byteArray[0] = firstByte;
  2355. for (let i = 1; i < totalBytes; i++) {
  2356. byteArray[i] = data[payPtr++];
  2357. }
  2358. }
  2359. samples.push({
  2360. type: userDataType,
  2361. payloadType,
  2362. pts,
  2363. bytes: byteArray
  2364. });
  2365. }
  2366. }
  2367. }
  2368. }
  2369. } else if (payloadType === 5) {
  2370. if (payloadSize > 16) {
  2371. const uuidStrArray = [];
  2372. for (let i = 0; i < 16; i++) {
  2373. const _b = data[payPtr++].toString(16);
  2374. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2375. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2376. uuidStrArray.push('-');
  2377. }
  2378. }
  2379. const length = payloadSize - 16;
  2380. const userDataBytes = new Uint8Array(length);
  2381. for (let i = 0; i < length; i++) {
  2382. userDataBytes[i] = data[payPtr++];
  2383. }
  2384. samples.push({
  2385. payloadType,
  2386. pts,
  2387. uuid: uuidStrArray.join(''),
  2388. userData: utf8ArrayToStr(userDataBytes),
  2389. userDataBytes
  2390. });
  2391. }
  2392. }
  2393. }
  2394. }
  2395. /**
  2396. * remove Emulation Prevention bytes from a RBSP
  2397. */
  2398. function discardEPB(data) {
  2399. const length = data.byteLength;
  2400. const EPBPositions = [];
  2401. let i = 1;
  2402. // Find all `Emulation Prevention Bytes`
  2403. while (i < length - 2) {
  2404. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2405. EPBPositions.push(i + 2);
  2406. i += 2;
  2407. } else {
  2408. i++;
  2409. }
  2410. }
  2411. // If no Emulation Prevention Bytes were found just return the original
  2412. // array
  2413. if (EPBPositions.length === 0) {
  2414. return data;
  2415. }
  2416. // Create a new array to hold the NAL unit data
  2417. const newLength = length - EPBPositions.length;
  2418. const newData = new Uint8Array(newLength);
  2419. let sourceIndex = 0;
  2420. for (i = 0; i < newLength; sourceIndex++, i++) {
  2421. if (sourceIndex === EPBPositions[0]) {
  2422. // Skip this byte
  2423. sourceIndex++;
  2424. // Remove this position index
  2425. EPBPositions.shift();
  2426. }
  2427. newData[i] = data[sourceIndex];
  2428. }
  2429. return newData;
  2430. }
  2431. function parseEmsg(data) {
  2432. const version = data[0];
  2433. let schemeIdUri = '';
  2434. let value = '';
  2435. let timeScale = 0;
  2436. let presentationTimeDelta = 0;
  2437. let presentationTime = 0;
  2438. let eventDuration = 0;
  2439. let id = 0;
  2440. let offset = 0;
  2441. if (version === 0) {
  2442. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2443. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2444. offset += 1;
  2445. }
  2446. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2447. offset += 1;
  2448. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2449. value += bin2str(data.subarray(offset, offset + 1));
  2450. offset += 1;
  2451. }
  2452. value += bin2str(data.subarray(offset, offset + 1));
  2453. offset += 1;
  2454. timeScale = readUint32(data, 12);
  2455. presentationTimeDelta = readUint32(data, 16);
  2456. eventDuration = readUint32(data, 20);
  2457. id = readUint32(data, 24);
  2458. offset = 28;
  2459. } else if (version === 1) {
  2460. offset += 4;
  2461. timeScale = readUint32(data, offset);
  2462. offset += 4;
  2463. const leftPresentationTime = readUint32(data, offset);
  2464. offset += 4;
  2465. const rightPresentationTime = readUint32(data, offset);
  2466. offset += 4;
  2467. presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;
  2468. if (!isSafeInteger(presentationTime)) {
  2469. presentationTime = Number.MAX_SAFE_INTEGER;
  2470. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2471. }
  2472. eventDuration = readUint32(data, offset);
  2473. offset += 4;
  2474. id = readUint32(data, offset);
  2475. offset += 4;
  2476. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2477. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2478. offset += 1;
  2479. }
  2480. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2481. offset += 1;
  2482. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2483. value += bin2str(data.subarray(offset, offset + 1));
  2484. offset += 1;
  2485. }
  2486. value += bin2str(data.subarray(offset, offset + 1));
  2487. offset += 1;
  2488. }
  2489. const payload = data.subarray(offset, data.byteLength);
  2490. return {
  2491. schemeIdUri,
  2492. value,
  2493. timeScale,
  2494. presentationTime,
  2495. presentationTimeDelta,
  2496. eventDuration,
  2497. id,
  2498. payload
  2499. };
  2500. }
  2501. function mp4Box(type, ...payload) {
  2502. const len = payload.length;
  2503. let size = 8;
  2504. let i = len;
  2505. while (i--) {
  2506. size += payload[i].byteLength;
  2507. }
  2508. const result = new Uint8Array(size);
  2509. result[0] = size >> 24 & 0xff;
  2510. result[1] = size >> 16 & 0xff;
  2511. result[2] = size >> 8 & 0xff;
  2512. result[3] = size & 0xff;
  2513. result.set(type, 4);
  2514. for (i = 0, size = 8; i < len; i++) {
  2515. result.set(payload[i], size);
  2516. size += payload[i].byteLength;
  2517. }
  2518. return result;
  2519. }
  2520. function mp4pssh(systemId, keyids, data) {
  2521. if (systemId.byteLength !== 16) {
  2522. throw new RangeError('Invalid system id');
  2523. }
  2524. let version;
  2525. let kids;
  2526. if (keyids) {
  2527. version = 1;
  2528. kids = new Uint8Array(keyids.length * 16);
  2529. for (let ix = 0; ix < keyids.length; ix++) {
  2530. const k = keyids[ix]; // uint8array
  2531. if (k.byteLength !== 16) {
  2532. throw new RangeError('Invalid key');
  2533. }
  2534. kids.set(k, ix * 16);
  2535. }
  2536. } else {
  2537. version = 0;
  2538. kids = new Uint8Array();
  2539. }
  2540. let kidCount;
  2541. if (version > 0) {
  2542. kidCount = new Uint8Array(4);
  2543. if (keyids.length > 0) {
  2544. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  2545. }
  2546. } else {
  2547. kidCount = new Uint8Array();
  2548. }
  2549. const dataSize = new Uint8Array(4);
  2550. if (data && data.byteLength > 0) {
  2551. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  2552. }
  2553. return mp4Box([112, 115, 115, 104], new Uint8Array([version, 0x00, 0x00, 0x00 // Flags
  2554. ]), systemId,
  2555. // 16 bytes
  2556. kidCount, kids, dataSize, data || new Uint8Array());
  2557. }
  2558. function parsePssh(initData) {
  2559. if (!(initData instanceof ArrayBuffer) || initData.byteLength < 32) {
  2560. return null;
  2561. }
  2562. const result = {
  2563. version: 0,
  2564. systemId: '',
  2565. kids: null,
  2566. data: null
  2567. };
  2568. const view = new DataView(initData);
  2569. const boxSize = view.getUint32(0);
  2570. if (initData.byteLength !== boxSize && boxSize > 44) {
  2571. return null;
  2572. }
  2573. const type = view.getUint32(4);
  2574. if (type !== 0x70737368) {
  2575. return null;
  2576. }
  2577. result.version = view.getUint32(8) >>> 24;
  2578. if (result.version > 1) {
  2579. return null;
  2580. }
  2581. result.systemId = Hex.hexDump(new Uint8Array(initData, 12, 16));
  2582. const dataSizeOrKidCount = view.getUint32(28);
  2583. if (result.version === 0) {
  2584. if (boxSize - 32 < dataSizeOrKidCount) {
  2585. return null;
  2586. }
  2587. result.data = new Uint8Array(initData, 32, dataSizeOrKidCount);
  2588. } else if (result.version === 1) {
  2589. result.kids = [];
  2590. for (let i = 0; i < dataSizeOrKidCount; i++) {
  2591. result.kids.push(new Uint8Array(initData, 32 + i * 16, 16));
  2592. }
  2593. }
  2594. return result;
  2595. }
  2596. let keyUriToKeyIdMap = {};
  2597. class LevelKey {
  2598. static clearKeyUriToKeyIdMap() {
  2599. keyUriToKeyIdMap = {};
  2600. }
  2601. constructor(method, uri, format, formatversions = [1], iv = null) {
  2602. this.uri = void 0;
  2603. this.method = void 0;
  2604. this.keyFormat = void 0;
  2605. this.keyFormatVersions = void 0;
  2606. this.encrypted = void 0;
  2607. this.isCommonEncryption = void 0;
  2608. this.iv = null;
  2609. this.key = null;
  2610. this.keyId = null;
  2611. this.pssh = null;
  2612. this.method = method;
  2613. this.uri = uri;
  2614. this.keyFormat = format;
  2615. this.keyFormatVersions = formatversions;
  2616. this.iv = iv;
  2617. this.encrypted = method ? method !== 'NONE' : false;
  2618. this.isCommonEncryption = this.encrypted && method !== 'AES-128';
  2619. }
  2620. isSupported() {
  2621. // If it's Segment encryption or No encryption, just select that key system
  2622. if (this.method) {
  2623. if (this.method === 'AES-128' || this.method === 'NONE') {
  2624. return true;
  2625. }
  2626. if (this.keyFormat === 'identity') {
  2627. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  2628. return this.method === 'SAMPLE-AES';
  2629. } else {
  2630. switch (this.keyFormat) {
  2631. case KeySystemFormats.FAIRPLAY:
  2632. case KeySystemFormats.WIDEVINE:
  2633. case KeySystemFormats.PLAYREADY:
  2634. case KeySystemFormats.CLEARKEY:
  2635. return ['ISO-23001-7', 'SAMPLE-AES', 'SAMPLE-AES-CENC', 'SAMPLE-AES-CTR'].indexOf(this.method) !== -1;
  2636. }
  2637. }
  2638. }
  2639. return false;
  2640. }
  2641. getDecryptData(sn) {
  2642. if (!this.encrypted || !this.uri) {
  2643. return null;
  2644. }
  2645. if (this.method === 'AES-128' && this.uri && !this.iv) {
  2646. if (typeof sn !== 'number') {
  2647. // We are fetching decryption data for a initialization segment
  2648. // If the segment was encrypted with AES-128
  2649. // It must have an IV defined. We cannot substitute the Segment Number in.
  2650. if (this.method === 'AES-128' && !this.iv) {
  2651. logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`);
  2652. }
  2653. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  2654. sn = 0;
  2655. }
  2656. const iv = createInitializationVector(sn);
  2657. const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  2658. return decryptdata;
  2659. }
  2660. // Initialize keyId if possible
  2661. const keyBytes = convertDataUriToArrayBytes(this.uri);
  2662. if (keyBytes) {
  2663. switch (this.keyFormat) {
  2664. case KeySystemFormats.WIDEVINE:
  2665. this.pssh = keyBytes;
  2666. // In case of widevine keyID is embedded in PSSH box. Read Key ID.
  2667. if (keyBytes.length >= 22) {
  2668. this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6);
  2669. }
  2670. break;
  2671. case KeySystemFormats.PLAYREADY:
  2672. {
  2673. const PlayReadyKeySystemUUID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);
  2674. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  2675. const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  2676. const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  2677. // Parse Playready WRMHeader XML
  2678. const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);
  2679. const parser = new DOMParser();
  2680. const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');
  2681. const keyData = xmlDoc.getElementsByTagName('KID')[0];
  2682. if (keyData) {
  2683. const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute('VALUE');
  2684. if (keyId) {
  2685. const keyIdArray = base64Decode(keyId).subarray(0, 16);
  2686. // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID
  2687. // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID
  2688. changeEndianness(keyIdArray);
  2689. this.keyId = keyIdArray;
  2690. }
  2691. }
  2692. break;
  2693. }
  2694. default:
  2695. {
  2696. let keydata = keyBytes.subarray(0, 16);
  2697. if (keydata.length !== 16) {
  2698. const padded = new Uint8Array(16);
  2699. padded.set(keydata, 16 - keydata.length);
  2700. keydata = padded;
  2701. }
  2702. this.keyId = keydata;
  2703. break;
  2704. }
  2705. }
  2706. }
  2707. // Default behavior: assign a new keyId for each uri
  2708. if (!this.keyId || this.keyId.byteLength !== 16) {
  2709. let keyId = keyUriToKeyIdMap[this.uri];
  2710. if (!keyId) {
  2711. const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  2712. keyId = new Uint8Array(16);
  2713. const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes
  2714. dv.setUint32(0, val);
  2715. keyUriToKeyIdMap[this.uri] = keyId;
  2716. }
  2717. this.keyId = keyId;
  2718. }
  2719. return this;
  2720. }
  2721. }
  2722. function createInitializationVector(segmentNumber) {
  2723. const uint8View = new Uint8Array(16);
  2724. for (let i = 12; i < 16; i++) {
  2725. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2726. }
  2727. return uint8View;
  2728. }
  2729. const VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  2730. function hasVariableReferences(str) {
  2731. return VARIABLE_REPLACEMENT_REGEX.test(str);
  2732. }
  2733. function substituteVariablesInAttributes(parsed, attr, attributeNames) {
  2734. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  2735. for (let i = attributeNames.length; i--;) {
  2736. const name = attributeNames[i];
  2737. const value = attr[name];
  2738. if (value) {
  2739. attr[name] = substituteVariables(parsed, value);
  2740. }
  2741. }
  2742. }
  2743. }
  2744. function substituteVariables(parsed, value) {
  2745. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  2746. const variableList = parsed.variableList;
  2747. return value.replace(VARIABLE_REPLACEMENT_REGEX, variableReference => {
  2748. const variableName = variableReference.substring(2, variableReference.length - 1);
  2749. const variableValue = variableList == null ? void 0 : variableList[variableName];
  2750. if (variableValue === undefined) {
  2751. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${variableName}"`));
  2752. return variableReference;
  2753. }
  2754. return variableValue;
  2755. });
  2756. }
  2757. return value;
  2758. }
  2759. function addVariableDefinition(parsed, attr, parentUrl) {
  2760. let variableList = parsed.variableList;
  2761. if (!variableList) {
  2762. parsed.variableList = variableList = {};
  2763. }
  2764. let NAME;
  2765. let VALUE;
  2766. if ('QUERYPARAM' in attr) {
  2767. NAME = attr.QUERYPARAM;
  2768. try {
  2769. const searchParams = new self.URL(parentUrl).searchParams;
  2770. if (searchParams.has(NAME)) {
  2771. VALUE = searchParams.get(NAME);
  2772. } else {
  2773. throw new Error(`"${NAME}" does not match any query parameter in URI: "${parentUrl}"`);
  2774. }
  2775. } catch (error) {
  2776. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));
  2777. }
  2778. } else {
  2779. NAME = attr.NAME;
  2780. VALUE = attr.VALUE;
  2781. }
  2782. if (NAME in variableList) {
  2783. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${NAME}"`));
  2784. } else {
  2785. variableList[NAME] = VALUE || '';
  2786. }
  2787. }
  2788. function importVariableDefinition(parsed, attr, sourceVariableList) {
  2789. const IMPORT = attr.IMPORT;
  2790. if (sourceVariableList && IMPORT in sourceVariableList) {
  2791. let variableList = parsed.variableList;
  2792. if (!variableList) {
  2793. parsed.variableList = variableList = {};
  2794. }
  2795. variableList[IMPORT] = sourceVariableList[IMPORT];
  2796. } else {
  2797. parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${IMPORT}"`));
  2798. }
  2799. }
  2800. /**
  2801. * MediaSource helper
  2802. */
  2803. function getMediaSource(preferManagedMediaSource = true) {
  2804. if (typeof self === 'undefined') return undefined;
  2805. const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  2806. return mms || self.MediaSource || self.WebKitMediaSource;
  2807. }
  2808. function isManagedMediaSource(source) {
  2809. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  2810. }
  2811. // from http://mp4ra.org/codecs.html
  2812. // values indicate codec selection preference (lower is higher priority)
  2813. const sampleEntryCodesISO = {
  2814. audio: {
  2815. a3ds: 1,
  2816. 'ac-3': 0.95,
  2817. 'ac-4': 1,
  2818. alac: 0.9,
  2819. alaw: 1,
  2820. dra1: 1,
  2821. 'dts+': 1,
  2822. 'dts-': 1,
  2823. dtsc: 1,
  2824. dtse: 1,
  2825. dtsh: 1,
  2826. 'ec-3': 0.9,
  2827. enca: 1,
  2828. fLaC: 0.9,
  2829. // MP4-RA listed codec entry for FLAC
  2830. flac: 0.9,
  2831. // legacy browser codec name for FLAC
  2832. FLAC: 0.9,
  2833. // some manifests may list "FLAC" with Apple's tools
  2834. g719: 1,
  2835. g726: 1,
  2836. m4ae: 1,
  2837. mha1: 1,
  2838. mha2: 1,
  2839. mhm1: 1,
  2840. mhm2: 1,
  2841. mlpa: 1,
  2842. mp4a: 1,
  2843. 'raw ': 1,
  2844. Opus: 1,
  2845. opus: 1,
  2846. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2847. samr: 1,
  2848. sawb: 1,
  2849. sawp: 1,
  2850. sevc: 1,
  2851. sqcp: 1,
  2852. ssmv: 1,
  2853. twos: 1,
  2854. ulaw: 1
  2855. },
  2856. video: {
  2857. avc1: 1,
  2858. avc2: 1,
  2859. avc3: 1,
  2860. avc4: 1,
  2861. avcp: 1,
  2862. av01: 0.8,
  2863. drac: 1,
  2864. dva1: 1,
  2865. dvav: 1,
  2866. dvh1: 0.7,
  2867. dvhe: 0.7,
  2868. encv: 1,
  2869. hev1: 0.75,
  2870. hvc1: 0.75,
  2871. mjp2: 1,
  2872. mp4v: 1,
  2873. mvc1: 1,
  2874. mvc2: 1,
  2875. mvc3: 1,
  2876. mvc4: 1,
  2877. resv: 1,
  2878. rv60: 1,
  2879. s263: 1,
  2880. svc1: 1,
  2881. svc2: 1,
  2882. 'vc-1': 1,
  2883. vp08: 1,
  2884. vp09: 0.9
  2885. },
  2886. text: {
  2887. stpp: 1,
  2888. wvtt: 1
  2889. }
  2890. };
  2891. function isCodecType(codec, type) {
  2892. const typeCodes = sampleEntryCodesISO[type];
  2893. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2894. }
  2895. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {
  2896. return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));
  2897. }
  2898. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {
  2899. var _MediaSource$isTypeSu;
  2900. const MediaSource = getMediaSource(preferManagedMediaSource);
  2901. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2902. }
  2903. function mimeTypeForCodec(codec, type) {
  2904. return `${type}/mp4;codecs="${codec}"`;
  2905. }
  2906. function videoCodecPreferenceValue(videoCodec) {
  2907. if (videoCodec) {
  2908. const fourCC = videoCodec.substring(0, 4);
  2909. return sampleEntryCodesISO.video[fourCC];
  2910. }
  2911. return 2;
  2912. }
  2913. function codecsSetSelectionPreferenceValue(codecSet) {
  2914. return codecSet.split(',').reduce((num, fourCC) => {
  2915. const preferenceValue = sampleEntryCodesISO.video[fourCC];
  2916. if (preferenceValue) {
  2917. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2918. }
  2919. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2920. }, 0);
  2921. }
  2922. const CODEC_COMPATIBLE_NAMES = {};
  2923. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {
  2924. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2925. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2926. }
  2927. // Idealy fLaC and Opus would be first (spec-compliant) but
  2928. // some browsers will report that fLaC is supported then fail.
  2929. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2930. const codecsToCheck = {
  2931. flac: ['flac', 'fLaC', 'FLAC'],
  2932. opus: ['opus', 'Opus']
  2933. }[lowerCaseCodec];
  2934. for (let i = 0; i < codecsToCheck.length; i++) {
  2935. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2936. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2937. return codecsToCheck[i];
  2938. }
  2939. }
  2940. return lowerCaseCodec;
  2941. }
  2942. const AUDIO_CODEC_REGEXP = /flac|opus/i;
  2943. function getCodecCompatibleName(codec, preferManagedMediaSource = true) {
  2944. return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));
  2945. }
  2946. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2947. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2948. // so use level codec is parsed codec is unavailable or incomplete
  2949. if (parsedCodec && parsedCodec !== 'mp4a') {
  2950. return parsedCodec;
  2951. }
  2952. return levelCodec ? levelCodec.split(',')[0] : levelCodec;
  2953. }
  2954. function convertAVC1ToAVCOTI(codec) {
  2955. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2956. const avcdata = codec.split('.');
  2957. if (avcdata.length > 2) {
  2958. let result = avcdata.shift() + '.';
  2959. result += parseInt(avcdata.shift()).toString(16);
  2960. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  2961. return result;
  2962. }
  2963. return codec;
  2964. }
  2965. 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;
  2966. const MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  2967. const IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  2968. const LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  2969. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  2970. /(?!#) *(\S[^\r\n]*)/.source,
  2971. // segment URI, group 3 => the URI (note newline is not eaten)
  2972. /#EXT-X-BYTERANGE:*(.+)/.source,
  2973. // next segment's byterange, group 4 => range spec (x@y)
  2974. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  2975. // next segment's program date/time group 5 => the datetime spec
  2976. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  2977. ].join('|'), 'g');
  2978. 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('|'));
  2979. class M3U8Parser {
  2980. static findGroup(groups, mediaGroupId) {
  2981. for (let i = 0; i < groups.length; i++) {
  2982. const group = groups[i];
  2983. if (group.id === mediaGroupId) {
  2984. return group;
  2985. }
  2986. }
  2987. }
  2988. static resolve(url, baseUrl) {
  2989. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  2990. alwaysNormalize: true
  2991. });
  2992. }
  2993. static isMediaPlaylist(str) {
  2994. return IS_MEDIA_PLAYLIST.test(str);
  2995. }
  2996. static parseMasterPlaylist(string, baseurl) {
  2997. const hasVariableRefs = hasVariableReferences(string) ;
  2998. const parsed = {
  2999. contentSteering: null,
  3000. levels: [],
  3001. playlistParsingError: null,
  3002. sessionData: null,
  3003. sessionKeys: null,
  3004. startTimeOffset: null,
  3005. variableList: null,
  3006. hasVariableRefs
  3007. };
  3008. const levelsWithKnownCodecs = [];
  3009. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  3010. let result;
  3011. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  3012. if (result[1]) {
  3013. var _level$unknownCodecs;
  3014. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  3015. const attrs = new AttrList(result[1]);
  3016. {
  3017. substituteVariablesInAttributes(parsed, attrs, ['CODECS', 'SUPPLEMENTAL-CODECS', 'ALLOWED-CPC', 'PATHWAY-ID', 'STABLE-VARIANT-ID', 'AUDIO', 'VIDEO', 'SUBTITLES', 'CLOSED-CAPTIONS', 'NAME']);
  3018. }
  3019. const uri = substituteVariables(parsed, result[2]) ;
  3020. const level = {
  3021. attrs,
  3022. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  3023. name: attrs.NAME,
  3024. url: M3U8Parser.resolve(uri, baseurl)
  3025. };
  3026. const resolution = attrs.decimalResolution('RESOLUTION');
  3027. if (resolution) {
  3028. level.width = resolution.width;
  3029. level.height = resolution.height;
  3030. }
  3031. setCodecs(attrs.CODECS, level);
  3032. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  3033. levelsWithKnownCodecs.push(level);
  3034. }
  3035. parsed.levels.push(level);
  3036. } else if (result[3]) {
  3037. const tag = result[3];
  3038. const attributes = result[4];
  3039. switch (tag) {
  3040. case 'SESSION-DATA':
  3041. {
  3042. // #EXT-X-SESSION-DATA
  3043. const sessionAttrs = new AttrList(attributes);
  3044. {
  3045. substituteVariablesInAttributes(parsed, sessionAttrs, ['DATA-ID', 'LANGUAGE', 'VALUE', 'URI']);
  3046. }
  3047. const dataId = sessionAttrs['DATA-ID'];
  3048. if (dataId) {
  3049. if (parsed.sessionData === null) {
  3050. parsed.sessionData = {};
  3051. }
  3052. parsed.sessionData[dataId] = sessionAttrs;
  3053. }
  3054. break;
  3055. }
  3056. case 'SESSION-KEY':
  3057. {
  3058. // #EXT-X-SESSION-KEY
  3059. const sessionKey = parseKey(attributes, baseurl, parsed);
  3060. if (sessionKey.encrypted && sessionKey.isSupported()) {
  3061. if (parsed.sessionKeys === null) {
  3062. parsed.sessionKeys = [];
  3063. }
  3064. parsed.sessionKeys.push(sessionKey);
  3065. } else {
  3066. logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${attributes}"`);
  3067. }
  3068. break;
  3069. }
  3070. case 'DEFINE':
  3071. {
  3072. // #EXT-X-DEFINE
  3073. {
  3074. const variableAttributes = new AttrList(attributes);
  3075. substituteVariablesInAttributes(parsed, variableAttributes, ['NAME', 'VALUE', 'QUERYPARAM']);
  3076. addVariableDefinition(parsed, variableAttributes, baseurl);
  3077. }
  3078. break;
  3079. }
  3080. case 'CONTENT-STEERING':
  3081. {
  3082. // #EXT-X-CONTENT-STEERING
  3083. const contentSteeringAttributes = new AttrList(attributes);
  3084. {
  3085. substituteVariablesInAttributes(parsed, contentSteeringAttributes, ['SERVER-URI', 'PATHWAY-ID']);
  3086. }
  3087. parsed.contentSteering = {
  3088. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  3089. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  3090. };
  3091. break;
  3092. }
  3093. case 'START':
  3094. {
  3095. // #EXT-X-START
  3096. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  3097. break;
  3098. }
  3099. }
  3100. }
  3101. }
  3102. // Filter out levels with unknown codecs if it does not remove all levels
  3103. const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  3104. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  3105. if (parsed.levels.length === 0) {
  3106. parsed.playlistParsingError = new Error('no levels found in manifest');
  3107. }
  3108. return parsed;
  3109. }
  3110. static parseMasterPlaylistMedia(string, baseurl, parsed) {
  3111. let result;
  3112. const results = {};
  3113. const levels = parsed.levels;
  3114. const groupsByType = {
  3115. AUDIO: levels.map(level => ({
  3116. id: level.attrs.AUDIO,
  3117. audioCodec: level.audioCodec
  3118. })),
  3119. SUBTITLES: levels.map(level => ({
  3120. id: level.attrs.SUBTITLES,
  3121. textCodec: level.textCodec
  3122. })),
  3123. 'CLOSED-CAPTIONS': []
  3124. };
  3125. let id = 0;
  3126. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  3127. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  3128. const attrs = new AttrList(result[1]);
  3129. const type = attrs.TYPE;
  3130. if (type) {
  3131. const groups = groupsByType[type];
  3132. const medias = results[type] || [];
  3133. results[type] = medias;
  3134. {
  3135. substituteVariablesInAttributes(parsed, attrs, ['URI', 'GROUP-ID', 'LANGUAGE', 'ASSOC-LANGUAGE', 'STABLE-RENDITION-ID', 'NAME', 'INSTREAM-ID', 'CHARACTERISTICS', 'CHANNELS']);
  3136. }
  3137. const lang = attrs.LANGUAGE;
  3138. const assocLang = attrs['ASSOC-LANGUAGE'];
  3139. const channels = attrs.CHANNELS;
  3140. const characteristics = attrs.CHARACTERISTICS;
  3141. const instreamId = attrs['INSTREAM-ID'];
  3142. const media = {
  3143. attrs,
  3144. bitrate: 0,
  3145. id: id++,
  3146. groupId: attrs['GROUP-ID'] || '',
  3147. name: attrs.NAME || lang || '',
  3148. type,
  3149. default: attrs.bool('DEFAULT'),
  3150. autoselect: attrs.bool('AUTOSELECT'),
  3151. forced: attrs.bool('FORCED'),
  3152. lang,
  3153. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  3154. };
  3155. if (assocLang) {
  3156. media.assocLang = assocLang;
  3157. }
  3158. if (channels) {
  3159. media.channels = channels;
  3160. }
  3161. if (characteristics) {
  3162. media.characteristics = characteristics;
  3163. }
  3164. if (instreamId) {
  3165. media.instreamId = instreamId;
  3166. }
  3167. if (groups != null && groups.length) {
  3168. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  3169. // If we don't find the track signalled, lets use the first audio groups codec we have
  3170. // Acting as a best guess
  3171. const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  3172. assignCodec(media, groupCodec, 'audioCodec');
  3173. assignCodec(media, groupCodec, 'textCodec');
  3174. }
  3175. medias.push(media);
  3176. }
  3177. }
  3178. return results;
  3179. }
  3180. static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  3181. const level = new LevelDetails(baseurl);
  3182. const fragments = level.fragments;
  3183. // The most recent init segment seen (applies to all subsequent segments)
  3184. let currentInitSegment = null;
  3185. let currentSN = 0;
  3186. let currentPart = 0;
  3187. let totalduration = 0;
  3188. let discontinuityCounter = 0;
  3189. let prevFrag = null;
  3190. let frag = new Fragment(type, baseurl);
  3191. let result;
  3192. let i;
  3193. let levelkeys;
  3194. let firstPdtIndex = -1;
  3195. let createNextFrag = false;
  3196. let nextByteRange = null;
  3197. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  3198. level.m3u8 = string;
  3199. level.hasVariableRefs = hasVariableReferences(string) ;
  3200. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  3201. if (createNextFrag) {
  3202. createNextFrag = false;
  3203. frag = new Fragment(type, baseurl);
  3204. // setup the next fragment for part loading
  3205. frag.start = totalduration;
  3206. frag.sn = currentSN;
  3207. frag.cc = discontinuityCounter;
  3208. frag.level = id;
  3209. if (currentInitSegment) {
  3210. frag.initSegment = currentInitSegment;
  3211. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3212. currentInitSegment.rawProgramDateTime = null;
  3213. if (nextByteRange) {
  3214. frag.setByteRange(nextByteRange);
  3215. nextByteRange = null;
  3216. }
  3217. }
  3218. }
  3219. const duration = result[1];
  3220. if (duration) {
  3221. // INF
  3222. frag.duration = parseFloat(duration);
  3223. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3224. const title = (' ' + result[2]).slice(1);
  3225. frag.title = title || null;
  3226. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  3227. } else if (result[3]) {
  3228. // url
  3229. if (isFiniteNumber(frag.duration)) {
  3230. frag.start = totalduration;
  3231. if (levelkeys) {
  3232. setFragLevelKeys(frag, levelkeys, level);
  3233. }
  3234. frag.sn = currentSN;
  3235. frag.level = id;
  3236. frag.cc = discontinuityCounter;
  3237. fragments.push(frag);
  3238. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3239. const uri = (' ' + result[3]).slice(1);
  3240. frag.relurl = substituteVariables(level, uri) ;
  3241. assignProgramDateTime(frag, prevFrag);
  3242. prevFrag = frag;
  3243. totalduration += frag.duration;
  3244. currentSN++;
  3245. currentPart = 0;
  3246. createNextFrag = true;
  3247. }
  3248. } else if (result[4]) {
  3249. // X-BYTERANGE
  3250. const data = (' ' + result[4]).slice(1);
  3251. if (prevFrag) {
  3252. frag.setByteRange(data, prevFrag);
  3253. } else {
  3254. frag.setByteRange(data);
  3255. }
  3256. } else if (result[5]) {
  3257. // PROGRAM-DATE-TIME
  3258. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3259. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  3260. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  3261. if (firstPdtIndex === -1) {
  3262. firstPdtIndex = fragments.length;
  3263. }
  3264. } else {
  3265. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  3266. if (!result) {
  3267. logger.warn('No matches on slow regex match for level playlist!');
  3268. continue;
  3269. }
  3270. for (i = 1; i < result.length; i++) {
  3271. if (typeof result[i] !== 'undefined') {
  3272. break;
  3273. }
  3274. }
  3275. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3276. const tag = (' ' + result[i]).slice(1);
  3277. const value1 = (' ' + result[i + 1]).slice(1);
  3278. const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  3279. switch (tag) {
  3280. case 'PLAYLIST-TYPE':
  3281. level.type = value1.toUpperCase();
  3282. break;
  3283. case 'MEDIA-SEQUENCE':
  3284. currentSN = level.startSN = parseInt(value1);
  3285. break;
  3286. case 'SKIP':
  3287. {
  3288. const skipAttrs = new AttrList(value1);
  3289. {
  3290. substituteVariablesInAttributes(level, skipAttrs, ['RECENTLY-REMOVED-DATERANGES']);
  3291. }
  3292. const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  3293. if (isFiniteNumber(skippedSegments)) {
  3294. level.skippedSegments = skippedSegments;
  3295. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  3296. for (let _i = skippedSegments; _i--;) {
  3297. fragments.unshift(null);
  3298. }
  3299. currentSN += skippedSegments;
  3300. }
  3301. const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  3302. if (recentlyRemovedDateranges) {
  3303. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  3304. }
  3305. break;
  3306. }
  3307. case 'TARGETDURATION':
  3308. level.targetduration = Math.max(parseInt(value1), 1);
  3309. break;
  3310. case 'VERSION':
  3311. level.version = parseInt(value1);
  3312. break;
  3313. case 'INDEPENDENT-SEGMENTS':
  3314. case 'EXTM3U':
  3315. break;
  3316. case 'ENDLIST':
  3317. level.live = false;
  3318. break;
  3319. case '#':
  3320. if (value1 || value2) {
  3321. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  3322. }
  3323. break;
  3324. case 'DISCONTINUITY':
  3325. discontinuityCounter++;
  3326. frag.tagList.push(['DIS']);
  3327. break;
  3328. case 'GAP':
  3329. frag.gap = true;
  3330. frag.tagList.push([tag]);
  3331. break;
  3332. case 'BITRATE':
  3333. frag.tagList.push([tag, value1]);
  3334. break;
  3335. case 'DATERANGE':
  3336. {
  3337. const dateRangeAttr = new AttrList(value1);
  3338. {
  3339. substituteVariablesInAttributes(level, dateRangeAttr, ['ID', 'CLASS', 'START-DATE', 'END-DATE', 'SCTE35-CMD', 'SCTE35-OUT', 'SCTE35-IN']);
  3340. substituteVariablesInAttributes(level, dateRangeAttr, dateRangeAttr.clientAttrs);
  3341. }
  3342. const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  3343. if (dateRange.isValid || level.skippedSegments) {
  3344. level.dateRanges[dateRange.id] = dateRange;
  3345. } else {
  3346. logger.warn(`Ignoring invalid DATERANGE tag: "${value1}"`);
  3347. }
  3348. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  3349. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  3350. break;
  3351. }
  3352. case 'DEFINE':
  3353. {
  3354. {
  3355. const variableAttributes = new AttrList(value1);
  3356. substituteVariablesInAttributes(level, variableAttributes, ['NAME', 'VALUE', 'IMPORT', 'QUERYPARAM']);
  3357. if ('IMPORT' in variableAttributes) {
  3358. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  3359. } else {
  3360. addVariableDefinition(level, variableAttributes, baseurl);
  3361. }
  3362. }
  3363. break;
  3364. }
  3365. case 'DISCONTINUITY-SEQUENCE':
  3366. discontinuityCounter = parseInt(value1);
  3367. break;
  3368. case 'KEY':
  3369. {
  3370. const levelKey = parseKey(value1, baseurl, level);
  3371. if (levelKey.isSupported()) {
  3372. if (levelKey.method === 'NONE') {
  3373. levelkeys = undefined;
  3374. break;
  3375. }
  3376. if (!levelkeys) {
  3377. levelkeys = {};
  3378. }
  3379. if (levelkeys[levelKey.keyFormat]) {
  3380. levelkeys = _extends({}, levelkeys);
  3381. }
  3382. levelkeys[levelKey.keyFormat] = levelKey;
  3383. } else {
  3384. logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${value1}"`);
  3385. }
  3386. break;
  3387. }
  3388. case 'START':
  3389. level.startTimeOffset = parseStartTimeOffset(value1);
  3390. break;
  3391. case 'MAP':
  3392. {
  3393. const mapAttrs = new AttrList(value1);
  3394. {
  3395. substituteVariablesInAttributes(level, mapAttrs, ['BYTERANGE', 'URI']);
  3396. }
  3397. if (frag.duration) {
  3398. // Initial segment tag is after segment duration tag.
  3399. // #EXTINF: 6.0
  3400. // #EXT-X-MAP:URI="init.mp4
  3401. const init = new Fragment(type, baseurl);
  3402. setInitSegment(init, mapAttrs, id, levelkeys);
  3403. currentInitSegment = init;
  3404. frag.initSegment = currentInitSegment;
  3405. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  3406. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3407. }
  3408. } else {
  3409. // Initial segment tag is before segment duration tag
  3410. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  3411. const end = frag.byteRangeEndOffset;
  3412. if (end) {
  3413. const start = frag.byteRangeStartOffset;
  3414. nextByteRange = `${end - start}@${start}`;
  3415. } else {
  3416. nextByteRange = null;
  3417. }
  3418. setInitSegment(frag, mapAttrs, id, levelkeys);
  3419. currentInitSegment = frag;
  3420. createNextFrag = true;
  3421. }
  3422. break;
  3423. }
  3424. case 'SERVER-CONTROL':
  3425. {
  3426. const serverControlAttrs = new AttrList(value1);
  3427. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  3428. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  3429. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  3430. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  3431. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  3432. break;
  3433. }
  3434. case 'PART-INF':
  3435. {
  3436. const partInfAttrs = new AttrList(value1);
  3437. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  3438. break;
  3439. }
  3440. case 'PART':
  3441. {
  3442. let partList = level.partList;
  3443. if (!partList) {
  3444. partList = level.partList = [];
  3445. }
  3446. const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  3447. const index = currentPart++;
  3448. const partAttrs = new AttrList(value1);
  3449. {
  3450. substituteVariablesInAttributes(level, partAttrs, ['BYTERANGE', 'URI']);
  3451. }
  3452. const part = new Part(partAttrs, frag, baseurl, index, previousFragmentPart);
  3453. partList.push(part);
  3454. frag.duration += part.duration;
  3455. break;
  3456. }
  3457. case 'PRELOAD-HINT':
  3458. {
  3459. const preloadHintAttrs = new AttrList(value1);
  3460. {
  3461. substituteVariablesInAttributes(level, preloadHintAttrs, ['URI']);
  3462. }
  3463. level.preloadHint = preloadHintAttrs;
  3464. break;
  3465. }
  3466. case 'RENDITION-REPORT':
  3467. {
  3468. const renditionReportAttrs = new AttrList(value1);
  3469. {
  3470. substituteVariablesInAttributes(level, renditionReportAttrs, ['URI']);
  3471. }
  3472. level.renditionReports = level.renditionReports || [];
  3473. level.renditionReports.push(renditionReportAttrs);
  3474. break;
  3475. }
  3476. default:
  3477. logger.warn(`line parsed but not handled: ${result}`);
  3478. break;
  3479. }
  3480. }
  3481. }
  3482. if (prevFrag && !prevFrag.relurl) {
  3483. fragments.pop();
  3484. totalduration -= prevFrag.duration;
  3485. if (level.partList) {
  3486. level.fragmentHint = prevFrag;
  3487. }
  3488. } else if (level.partList) {
  3489. assignProgramDateTime(frag, prevFrag);
  3490. frag.cc = discontinuityCounter;
  3491. level.fragmentHint = frag;
  3492. if (levelkeys) {
  3493. setFragLevelKeys(frag, levelkeys, level);
  3494. }
  3495. }
  3496. const fragmentLength = fragments.length;
  3497. const firstFragment = fragments[0];
  3498. const lastFragment = fragments[fragmentLength - 1];
  3499. totalduration += level.skippedSegments * level.targetduration;
  3500. if (totalduration > 0 && fragmentLength && lastFragment) {
  3501. level.averagetargetduration = totalduration / fragmentLength;
  3502. const lastSn = lastFragment.sn;
  3503. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  3504. if (!level.live) {
  3505. lastFragment.endList = true;
  3506. }
  3507. if (firstFragment) {
  3508. level.startCC = firstFragment.cc;
  3509. }
  3510. } else {
  3511. level.endSN = 0;
  3512. level.startCC = 0;
  3513. }
  3514. if (level.fragmentHint) {
  3515. totalduration += level.fragmentHint.duration;
  3516. }
  3517. level.totalduration = totalduration;
  3518. level.endCC = discontinuityCounter;
  3519. /**
  3520. * Backfill any missing PDT values
  3521. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  3522. * one or more Media Segment URIs, the client SHOULD extrapolate
  3523. * backward from that tag (using EXTINF durations and/or media
  3524. * timestamps) to associate dates with those segments."
  3525. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  3526. * computed.
  3527. */
  3528. if (firstPdtIndex > 0) {
  3529. backfillProgramDateTimes(fragments, firstPdtIndex);
  3530. }
  3531. return level;
  3532. }
  3533. }
  3534. function parseKey(keyTagAttributes, baseurl, parsed) {
  3535. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  3536. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  3537. const keyAttrs = new AttrList(keyTagAttributes);
  3538. {
  3539. substituteVariablesInAttributes(parsed, keyAttrs, ['KEYFORMAT', 'KEYFORMATVERSIONS', 'URI', 'IV', 'URI']);
  3540. }
  3541. const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  3542. const decrypturi = keyAttrs.URI;
  3543. const decryptiv = keyAttrs.hexadecimalInteger('IV');
  3544. const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  3545. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  3546. const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  3547. if (decrypturi && keyAttrs.IV && !decryptiv) {
  3548. logger.error(`Invalid IV: ${keyAttrs.IV}`);
  3549. }
  3550. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  3551. // No uri is allowed when METHOD is NONE
  3552. const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  3553. const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  3554. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
  3555. }
  3556. function parseStartTimeOffset(startAttributes) {
  3557. const startAttrs = new AttrList(startAttributes);
  3558. const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  3559. if (isFiniteNumber(startTimeOffset)) {
  3560. return startTimeOffset;
  3561. }
  3562. return null;
  3563. }
  3564. function setCodecs(codecsAttributeValue, level) {
  3565. let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);
  3566. ['video', 'audio', 'text'].forEach(type => {
  3567. const filtered = codecs.filter(codec => isCodecType(codec, type));
  3568. if (filtered.length) {
  3569. // Comma separated list of all codecs for type
  3570. level[`${type}Codec`] = filtered.join(',');
  3571. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  3572. codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);
  3573. }
  3574. });
  3575. level.unknownCodecs = codecs;
  3576. }
  3577. function assignCodec(media, groupItem, codecProperty) {
  3578. const codecValue = groupItem[codecProperty];
  3579. if (codecValue) {
  3580. media[codecProperty] = codecValue;
  3581. }
  3582. }
  3583. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  3584. let fragPrev = fragments[firstPdtIndex];
  3585. for (let i = firstPdtIndex; i--;) {
  3586. const frag = fragments[i];
  3587. // Exit on delta-playlist skipped segments
  3588. if (!frag) {
  3589. return;
  3590. }
  3591. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  3592. fragPrev = frag;
  3593. }
  3594. }
  3595. function assignProgramDateTime(frag, prevFrag) {
  3596. if (frag.rawProgramDateTime) {
  3597. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  3598. } else if (prevFrag != null && prevFrag.programDateTime) {
  3599. frag.programDateTime = prevFrag.endProgramDateTime;
  3600. }
  3601. if (!isFiniteNumber(frag.programDateTime)) {
  3602. frag.programDateTime = null;
  3603. frag.rawProgramDateTime = null;
  3604. }
  3605. }
  3606. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  3607. frag.relurl = mapAttrs.URI;
  3608. if (mapAttrs.BYTERANGE) {
  3609. frag.setByteRange(mapAttrs.BYTERANGE);
  3610. }
  3611. frag.level = id;
  3612. frag.sn = 'initSegment';
  3613. if (levelkeys) {
  3614. frag.levelkeys = levelkeys;
  3615. }
  3616. frag.initSegment = null;
  3617. }
  3618. function setFragLevelKeys(frag, levelkeys, level) {
  3619. frag.levelkeys = levelkeys;
  3620. const {
  3621. encryptedFragments
  3622. } = level;
  3623. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {
  3624. encryptedFragments.push(frag);
  3625. }
  3626. }
  3627. var PlaylistContextType = {
  3628. MANIFEST: "manifest",
  3629. LEVEL: "level",
  3630. AUDIO_TRACK: "audioTrack",
  3631. SUBTITLE_TRACK: "subtitleTrack"
  3632. };
  3633. var PlaylistLevelType = {
  3634. MAIN: "main",
  3635. AUDIO: "audio",
  3636. SUBTITLE: "subtitle"
  3637. };
  3638. function mapContextToLevelType(context) {
  3639. const {
  3640. type
  3641. } = context;
  3642. switch (type) {
  3643. case PlaylistContextType.AUDIO_TRACK:
  3644. return PlaylistLevelType.AUDIO;
  3645. case PlaylistContextType.SUBTITLE_TRACK:
  3646. return PlaylistLevelType.SUBTITLE;
  3647. default:
  3648. return PlaylistLevelType.MAIN;
  3649. }
  3650. }
  3651. function getResponseUrl(response, context) {
  3652. let url = response.url;
  3653. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3654. // data-uri mode also not supported (but no need to detect redirection)
  3655. if (url === undefined || url.indexOf('data:') === 0) {
  3656. // fallback to initial URL
  3657. url = context.url;
  3658. }
  3659. return url;
  3660. }
  3661. class PlaylistLoader {
  3662. constructor(hls) {
  3663. this.hls = void 0;
  3664. this.loaders = Object.create(null);
  3665. this.variableList = null;
  3666. this.hls = hls;
  3667. this.registerListeners();
  3668. }
  3669. startLoad(startPosition) {}
  3670. stopLoad() {
  3671. this.destroyInternalLoaders();
  3672. }
  3673. registerListeners() {
  3674. const {
  3675. hls
  3676. } = this;
  3677. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3678. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3679. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3680. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3681. }
  3682. unregisterListeners() {
  3683. const {
  3684. hls
  3685. } = this;
  3686. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3687. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3688. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3689. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3690. }
  3691. /**
  3692. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  3693. */
  3694. createInternalLoader(context) {
  3695. const config = this.hls.config;
  3696. const PLoader = config.pLoader;
  3697. const Loader = config.loader;
  3698. const InternalLoader = PLoader || Loader;
  3699. const loader = new InternalLoader(config);
  3700. this.loaders[context.type] = loader;
  3701. return loader;
  3702. }
  3703. getInternalLoader(context) {
  3704. return this.loaders[context.type];
  3705. }
  3706. resetInternalLoader(contextType) {
  3707. if (this.loaders[contextType]) {
  3708. delete this.loaders[contextType];
  3709. }
  3710. }
  3711. /**
  3712. * Call `destroy` on all internal loader instances mapped (one per context type)
  3713. */
  3714. destroyInternalLoaders() {
  3715. for (const contextType in this.loaders) {
  3716. const loader = this.loaders[contextType];
  3717. if (loader) {
  3718. loader.destroy();
  3719. }
  3720. this.resetInternalLoader(contextType);
  3721. }
  3722. }
  3723. destroy() {
  3724. this.variableList = null;
  3725. this.unregisterListeners();
  3726. this.destroyInternalLoaders();
  3727. }
  3728. onManifestLoading(event, data) {
  3729. const {
  3730. url
  3731. } = data;
  3732. this.variableList = null;
  3733. this.load({
  3734. id: null,
  3735. level: 0,
  3736. responseType: 'text',
  3737. type: PlaylistContextType.MANIFEST,
  3738. url,
  3739. deliveryDirectives: null
  3740. });
  3741. }
  3742. onLevelLoading(event, data) {
  3743. const {
  3744. id,
  3745. level,
  3746. pathwayId,
  3747. url,
  3748. deliveryDirectives
  3749. } = data;
  3750. this.load({
  3751. id,
  3752. level,
  3753. pathwayId,
  3754. responseType: 'text',
  3755. type: PlaylistContextType.LEVEL,
  3756. url,
  3757. deliveryDirectives
  3758. });
  3759. }
  3760. onAudioTrackLoading(event, data) {
  3761. const {
  3762. id,
  3763. groupId,
  3764. url,
  3765. deliveryDirectives
  3766. } = data;
  3767. this.load({
  3768. id,
  3769. groupId,
  3770. level: null,
  3771. responseType: 'text',
  3772. type: PlaylistContextType.AUDIO_TRACK,
  3773. url,
  3774. deliveryDirectives
  3775. });
  3776. }
  3777. onSubtitleTrackLoading(event, data) {
  3778. const {
  3779. id,
  3780. groupId,
  3781. url,
  3782. deliveryDirectives
  3783. } = data;
  3784. this.load({
  3785. id,
  3786. groupId,
  3787. level: null,
  3788. responseType: 'text',
  3789. type: PlaylistContextType.SUBTITLE_TRACK,
  3790. url,
  3791. deliveryDirectives
  3792. });
  3793. }
  3794. load(context) {
  3795. var _context$deliveryDire;
  3796. const config = this.hls.config;
  3797. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  3798. // Check if a loader for this context already exists
  3799. let loader = this.getInternalLoader(context);
  3800. if (loader) {
  3801. const loaderContext = loader.context;
  3802. if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) {
  3803. // same URL can't overlap
  3804. logger.trace('[playlist-loader]: playlist request ongoing');
  3805. return;
  3806. }
  3807. logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);
  3808. loader.abort();
  3809. }
  3810. // apply different configs for retries depending on
  3811. // context (manifest, level, audio/subs playlist)
  3812. let loadPolicy;
  3813. if (context.type === PlaylistContextType.MANIFEST) {
  3814. loadPolicy = config.manifestLoadPolicy.default;
  3815. } else {
  3816. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  3817. timeoutRetry: null,
  3818. errorRetry: null
  3819. });
  3820. }
  3821. loader = this.createInternalLoader(context);
  3822. // Override level/track timeout for LL-HLS requests
  3823. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  3824. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  3825. let levelDetails;
  3826. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  3827. levelDetails = this.hls.levels[context.level].details;
  3828. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  3829. levelDetails = this.hls.audioTracks[context.id].details;
  3830. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  3831. levelDetails = this.hls.subtitleTracks[context.id].details;
  3832. }
  3833. if (levelDetails) {
  3834. const partTarget = levelDetails.partTarget;
  3835. const targetDuration = levelDetails.targetduration;
  3836. if (partTarget && targetDuration) {
  3837. const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  3838. loadPolicy = _extends({}, loadPolicy, {
  3839. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  3840. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  3841. });
  3842. }
  3843. }
  3844. }
  3845. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  3846. const loaderConfig = {
  3847. loadPolicy,
  3848. timeout: loadPolicy.maxLoadTimeMs,
  3849. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  3850. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  3851. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  3852. };
  3853. const loaderCallbacks = {
  3854. onSuccess: (response, stats, context, networkDetails) => {
  3855. const loader = this.getInternalLoader(context);
  3856. this.resetInternalLoader(context.type);
  3857. const string = response.data;
  3858. // Validate if it is an M3U8 at all
  3859. if (string.indexOf('#EXTM3U') !== 0) {
  3860. this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  3861. return;
  3862. }
  3863. stats.parsing.start = performance.now();
  3864. if (M3U8Parser.isMediaPlaylist(string)) {
  3865. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  3866. } else {
  3867. this.handleMasterPlaylist(response, stats, context, networkDetails);
  3868. }
  3869. },
  3870. onError: (response, context, networkDetails, stats) => {
  3871. this.handleNetworkError(context, networkDetails, false, response, stats);
  3872. },
  3873. onTimeout: (stats, context, networkDetails) => {
  3874. this.handleNetworkError(context, networkDetails, true, undefined, stats);
  3875. }
  3876. };
  3877. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  3878. loader.load(context, loaderConfig, loaderCallbacks);
  3879. }
  3880. handleMasterPlaylist(response, stats, context, networkDetails) {
  3881. const hls = this.hls;
  3882. const string = response.data;
  3883. const url = getResponseUrl(response, context);
  3884. const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  3885. if (parsedResult.playlistParsingError) {
  3886. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  3887. return;
  3888. }
  3889. const {
  3890. contentSteering,
  3891. levels,
  3892. sessionData,
  3893. sessionKeys,
  3894. startTimeOffset,
  3895. variableList
  3896. } = parsedResult;
  3897. this.variableList = variableList;
  3898. const {
  3899. AUDIO: audioTracks = [],
  3900. SUBTITLES: subtitles,
  3901. 'CLOSED-CAPTIONS': captions
  3902. } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);
  3903. if (audioTracks.length) {
  3904. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3905. const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);
  3906. // if no embedded audio track defined, but audio codec signaled in quality level,
  3907. // we need to signal this main audio track this could happen with playlists with
  3908. // alt audio rendition in which quality levels (main)
  3909. // contains both audio+video. but with mixed audio track not signaled
  3910. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3911. logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3912. audioTracks.unshift({
  3913. type: 'main',
  3914. name: 'main',
  3915. groupId: 'main',
  3916. default: false,
  3917. autoselect: false,
  3918. forced: false,
  3919. id: -1,
  3920. attrs: new AttrList({}),
  3921. bitrate: 0,
  3922. url: ''
  3923. });
  3924. }
  3925. }
  3926. hls.trigger(Events.MANIFEST_LOADED, {
  3927. levels,
  3928. audioTracks,
  3929. subtitles,
  3930. captions,
  3931. contentSteering,
  3932. url,
  3933. stats,
  3934. networkDetails,
  3935. sessionData,
  3936. sessionKeys,
  3937. startTimeOffset,
  3938. variableList
  3939. });
  3940. }
  3941. handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  3942. const hls = this.hls;
  3943. const {
  3944. id,
  3945. level,
  3946. type
  3947. } = context;
  3948. const url = getResponseUrl(response, context);
  3949. const levelUrlId = 0;
  3950. const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  3951. const levelType = mapContextToLevelType(context);
  3952. const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList);
  3953. // We have done our first request (Manifest-type) and receive
  3954. // not a master playlist but a chunk-list (track/level)
  3955. // We fire the manifest-loaded event anyway with the parsed level-details
  3956. // by creating a single-level structure for it.
  3957. if (type === PlaylistContextType.MANIFEST) {
  3958. const singleLevel = {
  3959. attrs: new AttrList({}),
  3960. bitrate: 0,
  3961. details: levelDetails,
  3962. name: '',
  3963. url
  3964. };
  3965. hls.trigger(Events.MANIFEST_LOADED, {
  3966. levels: [singleLevel],
  3967. audioTracks: [],
  3968. url,
  3969. stats,
  3970. networkDetails,
  3971. sessionData: null,
  3972. sessionKeys: null,
  3973. contentSteering: null,
  3974. startTimeOffset: null,
  3975. variableList: null
  3976. });
  3977. }
  3978. // save parsing time
  3979. stats.parsing.end = performance.now();
  3980. // extend the context with the new levelDetails property
  3981. context.levelDetails = levelDetails;
  3982. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  3983. }
  3984. handleManifestParsingError(response, context, error, networkDetails, stats) {
  3985. this.hls.trigger(Events.ERROR, {
  3986. type: ErrorTypes.NETWORK_ERROR,
  3987. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  3988. fatal: context.type === PlaylistContextType.MANIFEST,
  3989. url: response.url,
  3990. err: error,
  3991. error,
  3992. reason: error.message,
  3993. response,
  3994. context,
  3995. networkDetails,
  3996. stats
  3997. });
  3998. }
  3999. handleNetworkError(context, networkDetails, timeout = false, response, stats) {
  4000. let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;
  4001. if (context.type === PlaylistContextType.LEVEL) {
  4002. message += `: ${context.level} id: ${context.id}`;
  4003. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  4004. message += ` id: ${context.id} group-id: "${context.groupId}"`;
  4005. }
  4006. const error = new Error(message);
  4007. logger.warn(`[playlist-loader]: ${message}`);
  4008. let details = ErrorDetails.UNKNOWN;
  4009. let fatal = false;
  4010. const loader = this.getInternalLoader(context);
  4011. switch (context.type) {
  4012. case PlaylistContextType.MANIFEST:
  4013. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  4014. fatal = true;
  4015. break;
  4016. case PlaylistContextType.LEVEL:
  4017. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  4018. fatal = false;
  4019. break;
  4020. case PlaylistContextType.AUDIO_TRACK:
  4021. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  4022. fatal = false;
  4023. break;
  4024. case PlaylistContextType.SUBTITLE_TRACK:
  4025. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  4026. fatal = false;
  4027. break;
  4028. }
  4029. if (loader) {
  4030. this.resetInternalLoader(context.type);
  4031. }
  4032. const errorData = {
  4033. type: ErrorTypes.NETWORK_ERROR,
  4034. details,
  4035. fatal,
  4036. url: context.url,
  4037. loader,
  4038. context,
  4039. error,
  4040. networkDetails,
  4041. stats
  4042. };
  4043. if (response) {
  4044. const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  4045. errorData.response = _objectSpread2({
  4046. url,
  4047. data: undefined
  4048. }, response);
  4049. }
  4050. this.hls.trigger(Events.ERROR, errorData);
  4051. }
  4052. handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  4053. const hls = this.hls;
  4054. const {
  4055. type,
  4056. level,
  4057. id,
  4058. groupId,
  4059. deliveryDirectives
  4060. } = context;
  4061. const url = getResponseUrl(response, context);
  4062. const parent = mapContextToLevelType(context);
  4063. const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  4064. if (!levelDetails.fragments.length) {
  4065. const _error = new Error('No Segments found in Playlist');
  4066. hls.trigger(Events.ERROR, {
  4067. type: ErrorTypes.NETWORK_ERROR,
  4068. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  4069. fatal: false,
  4070. url,
  4071. error: _error,
  4072. reason: _error.message,
  4073. response,
  4074. context,
  4075. level: levelIndex,
  4076. parent,
  4077. networkDetails,
  4078. stats
  4079. });
  4080. return;
  4081. }
  4082. if (!levelDetails.targetduration) {
  4083. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  4084. }
  4085. const error = levelDetails.playlistParsingError;
  4086. if (error) {
  4087. hls.trigger(Events.ERROR, {
  4088. type: ErrorTypes.NETWORK_ERROR,
  4089. details: ErrorDetails.LEVEL_PARSING_ERROR,
  4090. fatal: false,
  4091. url,
  4092. error,
  4093. reason: error.message,
  4094. response,
  4095. context,
  4096. level: levelIndex,
  4097. parent,
  4098. networkDetails,
  4099. stats
  4100. });
  4101. return;
  4102. }
  4103. if (levelDetails.live && loader) {
  4104. if (loader.getCacheAge) {
  4105. levelDetails.ageHeader = loader.getCacheAge() || 0;
  4106. }
  4107. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  4108. levelDetails.ageHeader = 0;
  4109. }
  4110. }
  4111. switch (type) {
  4112. case PlaylistContextType.MANIFEST:
  4113. case PlaylistContextType.LEVEL:
  4114. hls.trigger(Events.LEVEL_LOADED, {
  4115. details: levelDetails,
  4116. level: levelIndex || 0,
  4117. id: id || 0,
  4118. stats,
  4119. networkDetails,
  4120. deliveryDirectives
  4121. });
  4122. break;
  4123. case PlaylistContextType.AUDIO_TRACK:
  4124. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  4125. details: levelDetails,
  4126. id: id || 0,
  4127. groupId: groupId || '',
  4128. stats,
  4129. networkDetails,
  4130. deliveryDirectives
  4131. });
  4132. break;
  4133. case PlaylistContextType.SUBTITLE_TRACK:
  4134. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  4135. details: levelDetails,
  4136. id: id || 0,
  4137. groupId: groupId || '',
  4138. stats,
  4139. networkDetails,
  4140. deliveryDirectives
  4141. });
  4142. break;
  4143. }
  4144. }
  4145. }
  4146. function sendAddTrackEvent(track, videoEl) {
  4147. let event;
  4148. try {
  4149. event = new Event('addtrack');
  4150. } catch (err) {
  4151. // for IE11
  4152. event = document.createEvent('Event');
  4153. event.initEvent('addtrack', false, false);
  4154. }
  4155. event.track = track;
  4156. videoEl.dispatchEvent(event);
  4157. }
  4158. function addCueToTrack(track, cue) {
  4159. // Sometimes there are cue overlaps on segmented vtts so the same
  4160. // cue can appear more than once in different vtt files.
  4161. // This avoid showing duplicated cues with same timecode and text.
  4162. const mode = track.mode;
  4163. if (mode === 'disabled') {
  4164. track.mode = 'hidden';
  4165. }
  4166. if (track.cues && !track.cues.getCueById(cue.id)) {
  4167. try {
  4168. track.addCue(cue);
  4169. if (!track.cues.getCueById(cue.id)) {
  4170. throw new Error(`addCue is failed for: ${cue}`);
  4171. }
  4172. } catch (err) {
  4173. logger.debug(`[texttrack-utils]: ${err}`);
  4174. try {
  4175. const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  4176. textTrackCue.id = cue.id;
  4177. track.addCue(textTrackCue);
  4178. } catch (err2) {
  4179. logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);
  4180. }
  4181. }
  4182. }
  4183. if (mode === 'disabled') {
  4184. track.mode = mode;
  4185. }
  4186. }
  4187. function clearCurrentCues(track) {
  4188. // When track.mode is disabled, track.cues will be null.
  4189. // To guarantee the removal of cues, we need to temporarily
  4190. // change the mode to hidden
  4191. const mode = track.mode;
  4192. if (mode === 'disabled') {
  4193. track.mode = 'hidden';
  4194. }
  4195. if (track.cues) {
  4196. for (let i = track.cues.length; i--;) {
  4197. track.removeCue(track.cues[i]);
  4198. }
  4199. }
  4200. if (mode === 'disabled') {
  4201. track.mode = mode;
  4202. }
  4203. }
  4204. function removeCuesInRange(track, start, end, predicate) {
  4205. const mode = track.mode;
  4206. if (mode === 'disabled') {
  4207. track.mode = 'hidden';
  4208. }
  4209. if (track.cues && track.cues.length > 0) {
  4210. const cues = getCuesInRange(track.cues, start, end);
  4211. for (let i = 0; i < cues.length; i++) {
  4212. if (!predicate || predicate(cues[i])) {
  4213. track.removeCue(cues[i]);
  4214. }
  4215. }
  4216. }
  4217. if (mode === 'disabled') {
  4218. track.mode = mode;
  4219. }
  4220. }
  4221. // Find first cue starting after given time.
  4222. // Modified version of binary search O(log(n)).
  4223. function getFirstCueIndexAfterTime(cues, time) {
  4224. // If first cue starts after time, start there
  4225. if (time < cues[0].startTime) {
  4226. return 0;
  4227. }
  4228. // If the last cue ends before time there is no overlap
  4229. const len = cues.length - 1;
  4230. if (time > cues[len].endTime) {
  4231. return -1;
  4232. }
  4233. let left = 0;
  4234. let right = len;
  4235. while (left <= right) {
  4236. const mid = Math.floor((right + left) / 2);
  4237. if (time < cues[mid].startTime) {
  4238. right = mid - 1;
  4239. } else if (time > cues[mid].startTime && left < len) {
  4240. left = mid + 1;
  4241. } else {
  4242. // If it's not lower or higher, it must be equal.
  4243. return mid;
  4244. }
  4245. }
  4246. // At this point, left and right have swapped.
  4247. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  4248. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  4249. }
  4250. function getCuesInRange(cues, start, end) {
  4251. const cuesFound = [];
  4252. const firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  4253. if (firstCueInRange > -1) {
  4254. for (let i = firstCueInRange, len = cues.length; i < len; i++) {
  4255. const cue = cues[i];
  4256. if (cue.startTime >= start && cue.endTime <= end) {
  4257. cuesFound.push(cue);
  4258. } else if (cue.startTime > end) {
  4259. return cuesFound;
  4260. }
  4261. }
  4262. }
  4263. return cuesFound;
  4264. }
  4265. function filterSubtitleTracks(textTrackList) {
  4266. const tracks = [];
  4267. for (let i = 0; i < textTrackList.length; i++) {
  4268. const track = textTrackList[i];
  4269. // Edge adds a track without a label; we don't want to use it
  4270. if ((track.kind === 'subtitles' || track.kind === 'captions') && track.label) {
  4271. tracks.push(textTrackList[i]);
  4272. }
  4273. }
  4274. return tracks;
  4275. }
  4276. var MetadataSchema = {
  4277. audioId3: "org.id3",
  4278. dateRange: "com.apple.quicktime.HLS",
  4279. emsg: "https://aomedia.org/emsg/ID3"
  4280. };
  4281. const MIN_CUE_DURATION = 0.25;
  4282. function getCueClass() {
  4283. if (typeof self === 'undefined') return undefined;
  4284. return self.VTTCue || self.TextTrackCue;
  4285. }
  4286. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  4287. let cue = new Cue(startTime, endTime, '');
  4288. try {
  4289. cue.value = data;
  4290. if (type) {
  4291. cue.type = type;
  4292. }
  4293. } catch (e) {
  4294. cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread2({
  4295. type
  4296. }, data) : data));
  4297. }
  4298. return cue;
  4299. }
  4300. // VTTCue latest draft allows an infinite duration, fallback
  4301. // to MAX_VALUE if necessary
  4302. const MAX_CUE_ENDTIME = (() => {
  4303. const Cue = getCueClass();
  4304. try {
  4305. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  4306. } catch (e) {
  4307. return Number.MAX_VALUE;
  4308. }
  4309. return Number.POSITIVE_INFINITY;
  4310. })();
  4311. function dateRangeDateToTimelineSeconds(date, offset) {
  4312. return date.getTime() / 1000 - offset;
  4313. }
  4314. function hexToArrayBuffer(str) {
  4315. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  4316. }
  4317. class ID3TrackController {
  4318. constructor(hls) {
  4319. this.hls = void 0;
  4320. this.id3Track = null;
  4321. this.media = null;
  4322. this.dateRangeCuesAppended = {};
  4323. this.hls = hls;
  4324. this._registerListeners();
  4325. }
  4326. destroy() {
  4327. this._unregisterListeners();
  4328. this.id3Track = null;
  4329. this.media = null;
  4330. this.dateRangeCuesAppended = {};
  4331. // @ts-ignore
  4332. this.hls = null;
  4333. }
  4334. _registerListeners() {
  4335. const {
  4336. hls
  4337. } = this;
  4338. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4339. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4340. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4341. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4342. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4343. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4344. }
  4345. _unregisterListeners() {
  4346. const {
  4347. hls
  4348. } = this;
  4349. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4350. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4351. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4352. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4353. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4354. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4355. }
  4356. // Add ID3 metatadata text track.
  4357. onMediaAttached(event, data) {
  4358. this.media = data.media;
  4359. }
  4360. onMediaDetaching() {
  4361. if (!this.id3Track) {
  4362. return;
  4363. }
  4364. clearCurrentCues(this.id3Track);
  4365. this.id3Track = null;
  4366. this.media = null;
  4367. this.dateRangeCuesAppended = {};
  4368. }
  4369. onManifestLoading() {
  4370. this.dateRangeCuesAppended = {};
  4371. }
  4372. createTrack(media) {
  4373. const track = this.getID3Track(media.textTracks);
  4374. track.mode = 'hidden';
  4375. return track;
  4376. }
  4377. getID3Track(textTracks) {
  4378. if (!this.media) {
  4379. return;
  4380. }
  4381. for (let i = 0; i < textTracks.length; i++) {
  4382. const textTrack = textTracks[i];
  4383. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  4384. // send 'addtrack' when reusing the textTrack for metadata,
  4385. // same as what we do for captions
  4386. sendAddTrackEvent(textTrack, this.media);
  4387. return textTrack;
  4388. }
  4389. }
  4390. return this.media.addTextTrack('metadata', 'id3');
  4391. }
  4392. onFragParsingMetadata(event, data) {
  4393. if (!this.media) {
  4394. return;
  4395. }
  4396. const {
  4397. hls: {
  4398. config: {
  4399. enableEmsgMetadataCues,
  4400. enableID3MetadataCues
  4401. }
  4402. }
  4403. } = this;
  4404. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  4405. return;
  4406. }
  4407. const {
  4408. samples
  4409. } = data;
  4410. // create track dynamically
  4411. if (!this.id3Track) {
  4412. this.id3Track = this.createTrack(this.media);
  4413. }
  4414. const Cue = getCueClass();
  4415. if (!Cue) {
  4416. return;
  4417. }
  4418. for (let i = 0; i < samples.length; i++) {
  4419. const type = samples[i].type;
  4420. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  4421. continue;
  4422. }
  4423. const frames = getID3Frames(samples[i].data);
  4424. if (frames) {
  4425. const startTime = samples[i].pts;
  4426. let endTime = startTime + samples[i].duration;
  4427. if (endTime > MAX_CUE_ENDTIME) {
  4428. endTime = MAX_CUE_ENDTIME;
  4429. }
  4430. const timeDiff = endTime - startTime;
  4431. if (timeDiff <= 0) {
  4432. endTime = startTime + MIN_CUE_DURATION;
  4433. }
  4434. for (let j = 0; j < frames.length; j++) {
  4435. const frame = frames[j];
  4436. // Safari doesn't put the timestamp frame in the TextTrack
  4437. if (!isTimeStampFrame(frame)) {
  4438. // add a bounds to any unbounded cues
  4439. this.updateId3CueEnds(startTime, type);
  4440. const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  4441. if (cue) {
  4442. this.id3Track.addCue(cue);
  4443. }
  4444. }
  4445. }
  4446. }
  4447. }
  4448. }
  4449. updateId3CueEnds(startTime, type) {
  4450. var _this$id3Track;
  4451. const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  4452. if (cues) {
  4453. for (let i = cues.length; i--;) {
  4454. const cue = cues[i];
  4455. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  4456. cue.endTime = startTime;
  4457. }
  4458. }
  4459. }
  4460. }
  4461. onBufferFlushing(event, {
  4462. startOffset,
  4463. endOffset,
  4464. type
  4465. }) {
  4466. const {
  4467. id3Track,
  4468. hls
  4469. } = this;
  4470. if (!hls) {
  4471. return;
  4472. }
  4473. const {
  4474. config: {
  4475. enableEmsgMetadataCues,
  4476. enableID3MetadataCues
  4477. }
  4478. } = hls;
  4479. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4480. let predicate;
  4481. if (type === 'audio') {
  4482. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  4483. } else if (type === 'video') {
  4484. predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4485. } else {
  4486. predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4487. }
  4488. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  4489. }
  4490. }
  4491. onLevelUpdated(event, {
  4492. details
  4493. }) {
  4494. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4495. return;
  4496. }
  4497. const {
  4498. dateRangeCuesAppended,
  4499. id3Track
  4500. } = this;
  4501. const {
  4502. dateRanges
  4503. } = details;
  4504. const ids = Object.keys(dateRanges);
  4505. // Remove cues from track not found in details.dateRanges
  4506. if (id3Track) {
  4507. const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));
  4508. for (let i = idsToRemove.length; i--;) {
  4509. const id = idsToRemove[i];
  4510. Object.keys(dateRangeCuesAppended[id].cues).forEach(key => {
  4511. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4512. });
  4513. delete dateRangeCuesAppended[id];
  4514. }
  4515. }
  4516. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4517. const lastFragment = details.fragments[details.fragments.length - 1];
  4518. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  4519. return;
  4520. }
  4521. if (!this.id3Track) {
  4522. this.id3Track = this.createTrack(this.media);
  4523. }
  4524. const dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4525. const Cue = getCueClass();
  4526. for (let i = 0; i < ids.length; i++) {
  4527. const id = ids[i];
  4528. const dateRange = dateRanges[id];
  4529. const startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4530. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  4531. const appendedDateRangeCues = dateRangeCuesAppended[id];
  4532. const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  4533. let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4534. let endTime = MAX_CUE_ENDTIME;
  4535. const endDate = dateRange.endDate;
  4536. if (endDate) {
  4537. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4538. durationKnown = true;
  4539. } else if (dateRange.endOnNext && !durationKnown) {
  4540. const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {
  4541. if (id !== dateRange.id) {
  4542. const otherDateRange = dateRanges[id];
  4543. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  4544. return otherDateRange;
  4545. }
  4546. }
  4547. return candidateDateRange;
  4548. }, null);
  4549. if (nextDateRangeWithSameClass) {
  4550. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4551. durationKnown = true;
  4552. }
  4553. }
  4554. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  4555. // This is to emulate Safari HLS playback handling of DateRange tags
  4556. const attributes = Object.keys(dateRange.attr);
  4557. for (let j = 0; j < attributes.length; j++) {
  4558. const key = attributes[j];
  4559. if (!isDateRangeCueAttribute(key)) {
  4560. continue;
  4561. }
  4562. const cue = cues[key];
  4563. if (cue) {
  4564. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4565. cue.endTime = endTime;
  4566. }
  4567. } else if (Cue) {
  4568. let data = dateRange.attr[key];
  4569. if (isSCTE35Attribute(key)) {
  4570. data = hexToArrayBuffer(data);
  4571. }
  4572. const _cue = createCueWithDataFields(Cue, startTime, endTime, {
  4573. key,
  4574. data
  4575. }, MetadataSchema.dateRange);
  4576. if (_cue) {
  4577. _cue.id = id;
  4578. this.id3Track.addCue(_cue);
  4579. cues[key] = _cue;
  4580. }
  4581. }
  4582. }
  4583. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  4584. dateRangeCuesAppended[id] = {
  4585. cues,
  4586. dateRange,
  4587. durationKnown
  4588. };
  4589. }
  4590. }
  4591. }
  4592. class LatencyController {
  4593. constructor(hls) {
  4594. this.hls = void 0;
  4595. this.config = void 0;
  4596. this.media = null;
  4597. this.levelDetails = null;
  4598. this.currentTime = 0;
  4599. this.stallCount = 0;
  4600. this._latency = null;
  4601. this.timeupdateHandler = () => this.timeupdate();
  4602. this.hls = hls;
  4603. this.config = hls.config;
  4604. this.registerListeners();
  4605. }
  4606. get latency() {
  4607. return this._latency || 0;
  4608. }
  4609. get maxLatency() {
  4610. const {
  4611. config,
  4612. levelDetails
  4613. } = this;
  4614. if (config.liveMaxLatencyDuration !== undefined) {
  4615. return config.liveMaxLatencyDuration;
  4616. }
  4617. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4618. }
  4619. get targetLatency() {
  4620. const {
  4621. levelDetails
  4622. } = this;
  4623. if (levelDetails === null) {
  4624. return null;
  4625. }
  4626. const {
  4627. holdBack,
  4628. partHoldBack,
  4629. targetduration
  4630. } = levelDetails;
  4631. const {
  4632. liveSyncDuration,
  4633. liveSyncDurationCount,
  4634. lowLatencyMode
  4635. } = this.config;
  4636. const userConfig = this.hls.userConfig;
  4637. let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4638. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4639. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4640. }
  4641. const maxLiveSyncOnStallIncrease = targetduration;
  4642. const liveSyncOnStallIncrease = 1.0;
  4643. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4644. }
  4645. get liveSyncPosition() {
  4646. const liveEdge = this.estimateLiveEdge();
  4647. const targetLatency = this.targetLatency;
  4648. const levelDetails = this.levelDetails;
  4649. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4650. return null;
  4651. }
  4652. const edge = levelDetails.edge;
  4653. const syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4654. const min = edge - levelDetails.totalduration;
  4655. const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4656. return Math.min(Math.max(min, syncPosition), max);
  4657. }
  4658. get drift() {
  4659. const {
  4660. levelDetails
  4661. } = this;
  4662. if (levelDetails === null) {
  4663. return 1;
  4664. }
  4665. return levelDetails.drift;
  4666. }
  4667. get edgeStalled() {
  4668. const {
  4669. levelDetails
  4670. } = this;
  4671. if (levelDetails === null) {
  4672. return 0;
  4673. }
  4674. const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4675. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4676. }
  4677. get forwardBufferLength() {
  4678. const {
  4679. media,
  4680. levelDetails
  4681. } = this;
  4682. if (!media || !levelDetails) {
  4683. return 0;
  4684. }
  4685. const bufferedRanges = media.buffered.length;
  4686. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4687. }
  4688. destroy() {
  4689. this.unregisterListeners();
  4690. this.onMediaDetaching();
  4691. this.levelDetails = null;
  4692. // @ts-ignore
  4693. this.hls = this.timeupdateHandler = null;
  4694. }
  4695. registerListeners() {
  4696. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4697. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4698. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4699. this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4700. this.hls.on(Events.ERROR, this.onError, this);
  4701. }
  4702. unregisterListeners() {
  4703. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4704. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4705. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4706. this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4707. this.hls.off(Events.ERROR, this.onError, this);
  4708. }
  4709. onMediaAttached(event, data) {
  4710. this.media = data.media;
  4711. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4712. }
  4713. onMediaDetaching() {
  4714. if (this.media) {
  4715. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4716. this.media = null;
  4717. }
  4718. }
  4719. onManifestLoading() {
  4720. this.levelDetails = null;
  4721. this._latency = null;
  4722. this.stallCount = 0;
  4723. }
  4724. onLevelUpdated(event, {
  4725. details
  4726. }) {
  4727. this.levelDetails = details;
  4728. if (details.advanced) {
  4729. this.timeupdate();
  4730. }
  4731. if (!details.live && this.media) {
  4732. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4733. }
  4734. }
  4735. onError(event, data) {
  4736. var _this$levelDetails;
  4737. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  4738. return;
  4739. }
  4740. this.stallCount++;
  4741. if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  4742. logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4743. }
  4744. }
  4745. timeupdate() {
  4746. const {
  4747. media,
  4748. levelDetails
  4749. } = this;
  4750. if (!media || !levelDetails) {
  4751. return;
  4752. }
  4753. this.currentTime = media.currentTime;
  4754. const latency = this.computeLatency();
  4755. if (latency === null) {
  4756. return;
  4757. }
  4758. this._latency = latency;
  4759. // Adapt playbackRate to meet target latency in low-latency mode
  4760. const {
  4761. lowLatencyMode,
  4762. maxLiveSyncPlaybackRate
  4763. } = this.config;
  4764. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  4765. return;
  4766. }
  4767. const targetLatency = this.targetLatency;
  4768. if (targetLatency === null) {
  4769. return;
  4770. }
  4771. const distanceFromTarget = latency - targetLatency;
  4772. // Only adjust playbackRate when within one target duration of targetLatency
  4773. // and more than one second from under-buffering.
  4774. // Playback further than one target duration from target can be considered DVR playback.
  4775. const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4776. const inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4777. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4778. const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4779. const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4780. media.playbackRate = Math.min(max, Math.max(1, rate));
  4781. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4782. media.playbackRate = 1;
  4783. }
  4784. }
  4785. estimateLiveEdge() {
  4786. const {
  4787. levelDetails
  4788. } = this;
  4789. if (levelDetails === null) {
  4790. return null;
  4791. }
  4792. return levelDetails.edge + levelDetails.age;
  4793. }
  4794. computeLatency() {
  4795. const liveEdge = this.estimateLiveEdge();
  4796. if (liveEdge === null) {
  4797. return null;
  4798. }
  4799. return liveEdge - this.currentTime;
  4800. }
  4801. }
  4802. const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  4803. function isHdcpLevel(value) {
  4804. return HdcpLevels.indexOf(value) > -1;
  4805. }
  4806. const VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  4807. function isVideoRange(value) {
  4808. return !!value && VideoRangeValues.indexOf(value) > -1;
  4809. }
  4810. var HlsSkip = {
  4811. No: "",
  4812. Yes: "YES",
  4813. v2: "v2"
  4814. };
  4815. function getSkipValue(details) {
  4816. const {
  4817. canSkipUntil,
  4818. canSkipDateRanges,
  4819. age
  4820. } = details;
  4821. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  4822. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  4823. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  4824. const playlistRecentEnough = age < canSkipUntil / 2;
  4825. if (canSkipUntil && playlistRecentEnough) {
  4826. if (canSkipDateRanges) {
  4827. return HlsSkip.v2;
  4828. }
  4829. return HlsSkip.Yes;
  4830. }
  4831. return HlsSkip.No;
  4832. }
  4833. class HlsUrlParameters {
  4834. constructor(msn, part, skip) {
  4835. this.msn = void 0;
  4836. this.part = void 0;
  4837. this.skip = void 0;
  4838. this.msn = msn;
  4839. this.part = part;
  4840. this.skip = skip;
  4841. }
  4842. addDirectives(uri) {
  4843. const url = new self.URL(uri);
  4844. if (this.msn !== undefined) {
  4845. url.searchParams.set('_HLS_msn', this.msn.toString());
  4846. }
  4847. if (this.part !== undefined) {
  4848. url.searchParams.set('_HLS_part', this.part.toString());
  4849. }
  4850. if (this.skip) {
  4851. url.searchParams.set('_HLS_skip', this.skip);
  4852. }
  4853. return url.href;
  4854. }
  4855. }
  4856. class Level {
  4857. constructor(data) {
  4858. this._attrs = void 0;
  4859. this.audioCodec = void 0;
  4860. this.bitrate = void 0;
  4861. this.codecSet = void 0;
  4862. this.url = void 0;
  4863. this.frameRate = void 0;
  4864. this.height = void 0;
  4865. this.id = void 0;
  4866. this.name = void 0;
  4867. this.videoCodec = void 0;
  4868. this.width = void 0;
  4869. this.details = void 0;
  4870. this.fragmentError = 0;
  4871. this.loadError = 0;
  4872. this.loaded = void 0;
  4873. this.realBitrate = 0;
  4874. this.supportedPromise = void 0;
  4875. this.supportedResult = void 0;
  4876. this._avgBitrate = 0;
  4877. this._audioGroups = void 0;
  4878. this._subtitleGroups = void 0;
  4879. // Deprecated (retained for backwards compatibility)
  4880. this._urlId = 0;
  4881. this.url = [data.url];
  4882. this._attrs = [data.attrs];
  4883. this.bitrate = data.bitrate;
  4884. if (data.details) {
  4885. this.details = data.details;
  4886. }
  4887. this.id = data.id || 0;
  4888. this.name = data.name;
  4889. this.width = data.width || 0;
  4890. this.height = data.height || 0;
  4891. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  4892. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  4893. this.audioCodec = data.audioCodec;
  4894. this.videoCodec = data.videoCodec;
  4895. this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');
  4896. this.addGroupId('audio', data.attrs.AUDIO);
  4897. this.addGroupId('text', data.attrs.SUBTITLES);
  4898. }
  4899. get maxBitrate() {
  4900. return Math.max(this.realBitrate, this.bitrate);
  4901. }
  4902. get averageBitrate() {
  4903. return this._avgBitrate || this.realBitrate || this.bitrate;
  4904. }
  4905. get attrs() {
  4906. return this._attrs[0];
  4907. }
  4908. get codecs() {
  4909. return this.attrs.CODECS || '';
  4910. }
  4911. get pathwayId() {
  4912. return this.attrs['PATHWAY-ID'] || '.';
  4913. }
  4914. get videoRange() {
  4915. return this.attrs['VIDEO-RANGE'] || 'SDR';
  4916. }
  4917. get score() {
  4918. return this.attrs.optionalFloat('SCORE', 0);
  4919. }
  4920. get uri() {
  4921. return this.url[0] || '';
  4922. }
  4923. hasAudioGroup(groupId) {
  4924. return hasGroup(this._audioGroups, groupId);
  4925. }
  4926. hasSubtitleGroup(groupId) {
  4927. return hasGroup(this._subtitleGroups, groupId);
  4928. }
  4929. get audioGroups() {
  4930. return this._audioGroups;
  4931. }
  4932. get subtitleGroups() {
  4933. return this._subtitleGroups;
  4934. }
  4935. addGroupId(type, groupId) {
  4936. if (!groupId) {
  4937. return;
  4938. }
  4939. if (type === 'audio') {
  4940. let audioGroups = this._audioGroups;
  4941. if (!audioGroups) {
  4942. audioGroups = this._audioGroups = [];
  4943. }
  4944. if (audioGroups.indexOf(groupId) === -1) {
  4945. audioGroups.push(groupId);
  4946. }
  4947. } else if (type === 'text') {
  4948. let subtitleGroups = this._subtitleGroups;
  4949. if (!subtitleGroups) {
  4950. subtitleGroups = this._subtitleGroups = [];
  4951. }
  4952. if (subtitleGroups.indexOf(groupId) === -1) {
  4953. subtitleGroups.push(groupId);
  4954. }
  4955. }
  4956. }
  4957. // Deprecated methods (retained for backwards compatibility)
  4958. get urlId() {
  4959. return 0;
  4960. }
  4961. set urlId(value) {}
  4962. get audioGroupIds() {
  4963. return this.audioGroups ? [this.audioGroupId] : undefined;
  4964. }
  4965. get textGroupIds() {
  4966. return this.subtitleGroups ? [this.textGroupId] : undefined;
  4967. }
  4968. get audioGroupId() {
  4969. var _this$audioGroups;
  4970. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  4971. }
  4972. get textGroupId() {
  4973. var _this$subtitleGroups;
  4974. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  4975. }
  4976. addFallback() {}
  4977. }
  4978. function hasGroup(groups, groupId) {
  4979. if (!groupId || !groups) {
  4980. return false;
  4981. }
  4982. return groups.indexOf(groupId) !== -1;
  4983. }
  4984. function updateFromToPTS(fragFrom, fragTo) {
  4985. const fragToPTS = fragTo.startPTS;
  4986. // if we know startPTS[toIdx]
  4987. if (isFiniteNumber(fragToPTS)) {
  4988. // update fragment duration.
  4989. // it helps to fix drifts between playlist reported duration and fragment real duration
  4990. let duration = 0;
  4991. let frag;
  4992. if (fragTo.sn > fragFrom.sn) {
  4993. duration = fragToPTS - fragFrom.start;
  4994. frag = fragFrom;
  4995. } else {
  4996. duration = fragFrom.start - fragToPTS;
  4997. frag = fragTo;
  4998. }
  4999. if (frag.duration !== duration) {
  5000. frag.duration = duration;
  5001. }
  5002. // we dont know startPTS[toIdx]
  5003. } else if (fragTo.sn > fragFrom.sn) {
  5004. const contiguous = fragFrom.cc === fragTo.cc;
  5005. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  5006. if (contiguous && fragFrom.minEndPTS) {
  5007. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  5008. } else {
  5009. fragTo.start = fragFrom.start + fragFrom.duration;
  5010. }
  5011. } else {
  5012. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  5013. }
  5014. }
  5015. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  5016. const parsedMediaDuration = endPTS - startPTS;
  5017. if (parsedMediaDuration <= 0) {
  5018. logger.warn('Fragment should have a positive duration', frag);
  5019. endPTS = startPTS + frag.duration;
  5020. endDTS = startDTS + frag.duration;
  5021. }
  5022. let maxStartPTS = startPTS;
  5023. let minEndPTS = endPTS;
  5024. const fragStartPts = frag.startPTS;
  5025. const fragEndPts = frag.endPTS;
  5026. if (isFiniteNumber(fragStartPts)) {
  5027. // delta PTS between audio and video
  5028. const deltaPTS = Math.abs(fragStartPts - startPTS);
  5029. if (!isFiniteNumber(frag.deltaPTS)) {
  5030. frag.deltaPTS = deltaPTS;
  5031. } else {
  5032. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  5033. }
  5034. maxStartPTS = Math.max(startPTS, fragStartPts);
  5035. startPTS = Math.min(startPTS, fragStartPts);
  5036. startDTS = Math.min(startDTS, frag.startDTS);
  5037. minEndPTS = Math.min(endPTS, fragEndPts);
  5038. endPTS = Math.max(endPTS, fragEndPts);
  5039. endDTS = Math.max(endDTS, frag.endDTS);
  5040. }
  5041. const drift = startPTS - frag.start;
  5042. if (frag.start !== 0) {
  5043. frag.start = startPTS;
  5044. }
  5045. frag.duration = endPTS - frag.start;
  5046. frag.startPTS = startPTS;
  5047. frag.maxStartPTS = maxStartPTS;
  5048. frag.startDTS = startDTS;
  5049. frag.endPTS = endPTS;
  5050. frag.minEndPTS = minEndPTS;
  5051. frag.endDTS = endDTS;
  5052. const sn = frag.sn; // 'initSegment'
  5053. // exit if sn out of range
  5054. if (!details || sn < details.startSN || sn > details.endSN) {
  5055. return 0;
  5056. }
  5057. let i;
  5058. const fragIdx = sn - details.startSN;
  5059. const fragments = details.fragments;
  5060. // update frag reference in fragments array
  5061. // rationale is that fragments array might not contain this frag object.
  5062. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  5063. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  5064. // resulting in invalid sliding computation
  5065. fragments[fragIdx] = frag;
  5066. // adjust fragment PTS/duration from seqnum-1 to frag 0
  5067. for (i = fragIdx; i > 0; i--) {
  5068. updateFromToPTS(fragments[i], fragments[i - 1]);
  5069. }
  5070. // adjust fragment PTS/duration from seqnum to last frag
  5071. for (i = fragIdx; i < fragments.length - 1; i++) {
  5072. updateFromToPTS(fragments[i], fragments[i + 1]);
  5073. }
  5074. if (details.fragmentHint) {
  5075. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  5076. }
  5077. details.PTSKnown = details.alignedSliding = true;
  5078. return drift;
  5079. }
  5080. function mergeDetails(oldDetails, newDetails) {
  5081. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  5082. let currentInitSegment = null;
  5083. const oldFragments = oldDetails.fragments;
  5084. for (let i = oldFragments.length - 1; i >= 0; i--) {
  5085. const oldInit = oldFragments[i].initSegment;
  5086. if (oldInit) {
  5087. currentInitSegment = oldInit;
  5088. break;
  5089. }
  5090. }
  5091. if (oldDetails.fragmentHint) {
  5092. // prevent PTS and duration from being adjusted on the next hint
  5093. delete oldDetails.fragmentHint.endPTS;
  5094. }
  5095. // check if old/new playlists have fragments in common
  5096. // loop through overlapping SN and update startPTS , cc, and duration if any found
  5097. let ccOffset = 0;
  5098. let PTSFrag;
  5099. mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {
  5100. if (oldFrag.relurl) {
  5101. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  5102. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  5103. // of the playlist.
  5104. ccOffset = oldFrag.cc - newFrag.cc;
  5105. }
  5106. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  5107. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  5108. newFrag.startDTS = oldFrag.startDTS;
  5109. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  5110. newFrag.endPTS = oldFrag.endPTS;
  5111. newFrag.endDTS = oldFrag.endDTS;
  5112. newFrag.minEndPTS = oldFrag.minEndPTS;
  5113. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  5114. if (newFrag.duration) {
  5115. PTSFrag = newFrag;
  5116. }
  5117. // PTS is known when any segment has startPTS and endPTS
  5118. newDetails.PTSKnown = newDetails.alignedSliding = true;
  5119. }
  5120. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  5121. newFrag.loader = oldFrag.loader;
  5122. newFrag.stats = oldFrag.stats;
  5123. if (oldFrag.initSegment) {
  5124. newFrag.initSegment = oldFrag.initSegment;
  5125. currentInitSegment = oldFrag.initSegment;
  5126. }
  5127. });
  5128. if (currentInitSegment) {
  5129. const fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5130. fragmentsToCheck.forEach(frag => {
  5131. var _currentInitSegment;
  5132. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  5133. frag.initSegment = currentInitSegment;
  5134. }
  5135. });
  5136. }
  5137. if (newDetails.skippedSegments) {
  5138. newDetails.deltaUpdateFailed = newDetails.fragments.some(frag => !frag);
  5139. if (newDetails.deltaUpdateFailed) {
  5140. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  5141. for (let i = newDetails.skippedSegments; i--;) {
  5142. newDetails.fragments.shift();
  5143. }
  5144. newDetails.startSN = newDetails.fragments[0].sn;
  5145. newDetails.startCC = newDetails.fragments[0].cc;
  5146. } else if (newDetails.canSkipDateRanges) {
  5147. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  5148. }
  5149. }
  5150. const newFragments = newDetails.fragments;
  5151. if (ccOffset) {
  5152. logger.warn('discontinuity sliding from playlist, take drift into account');
  5153. for (let i = 0; i < newFragments.length; i++) {
  5154. newFragments[i].cc += ccOffset;
  5155. }
  5156. }
  5157. if (newDetails.skippedSegments) {
  5158. newDetails.startCC = newDetails.fragments[0].cc;
  5159. }
  5160. // Merge parts
  5161. mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {
  5162. newPart.elementaryStreams = oldPart.elementaryStreams;
  5163. newPart.stats = oldPart.stats;
  5164. });
  5165. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  5166. if (PTSFrag) {
  5167. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  5168. } else {
  5169. // ensure that delta is within oldFragments range
  5170. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  5171. // in that case we also need to adjust start offset of all fragments
  5172. adjustSliding(oldDetails, newDetails);
  5173. }
  5174. if (newFragments.length) {
  5175. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  5176. }
  5177. newDetails.driftStartTime = oldDetails.driftStartTime;
  5178. newDetails.driftStart = oldDetails.driftStart;
  5179. const advancedDateTime = newDetails.advancedDateTime;
  5180. if (newDetails.advanced && advancedDateTime) {
  5181. const edge = newDetails.edge;
  5182. if (!newDetails.driftStart) {
  5183. newDetails.driftStartTime = advancedDateTime;
  5184. newDetails.driftStart = edge;
  5185. }
  5186. newDetails.driftEndTime = advancedDateTime;
  5187. newDetails.driftEnd = edge;
  5188. } else {
  5189. newDetails.driftEndTime = oldDetails.driftEndTime;
  5190. newDetails.driftEnd = oldDetails.driftEnd;
  5191. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  5192. }
  5193. }
  5194. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  5195. const dateRanges = _extends({}, oldDateRanges);
  5196. if (recentlyRemovedDateranges) {
  5197. recentlyRemovedDateranges.forEach(id => {
  5198. delete dateRanges[id];
  5199. });
  5200. }
  5201. Object.keys(deltaDateRanges).forEach(id => {
  5202. const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  5203. if (dateRange.isValid) {
  5204. dateRanges[id] = dateRange;
  5205. } else {
  5206. logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(deltaDateRanges[id].attr)}"`);
  5207. }
  5208. });
  5209. return dateRanges;
  5210. }
  5211. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  5212. if (oldParts && newParts) {
  5213. let delta = 0;
  5214. for (let i = 0, len = oldParts.length; i <= len; i++) {
  5215. const oldPart = oldParts[i];
  5216. const newPart = newParts[i + delta];
  5217. if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {
  5218. intersectionFn(oldPart, newPart);
  5219. } else {
  5220. delta--;
  5221. }
  5222. }
  5223. }
  5224. }
  5225. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5226. const skippedSegments = newDetails.skippedSegments;
  5227. const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5228. const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5229. const delta = newDetails.startSN - oldDetails.startSN;
  5230. const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5231. const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5232. for (let i = start; i <= end; i++) {
  5233. const oldFrag = oldFrags[delta + i];
  5234. let newFrag = newFrags[i];
  5235. if (skippedSegments && !newFrag && i < skippedSegments) {
  5236. // Fill in skipped segments in delta playlist
  5237. newFrag = newDetails.fragments[i] = oldFrag;
  5238. }
  5239. if (oldFrag && newFrag) {
  5240. intersectionFn(oldFrag, newFrag);
  5241. }
  5242. }
  5243. }
  5244. function adjustSliding(oldDetails, newDetails) {
  5245. const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5246. const oldFragments = oldDetails.fragments;
  5247. if (delta < 0 || delta >= oldFragments.length) {
  5248. return;
  5249. }
  5250. addSliding(newDetails, oldFragments[delta].start);
  5251. }
  5252. function addSliding(details, start) {
  5253. if (start) {
  5254. const fragments = details.fragments;
  5255. for (let i = details.skippedSegments; i < fragments.length; i++) {
  5256. fragments[i].start += start;
  5257. }
  5258. if (details.fragmentHint) {
  5259. details.fragmentHint.start += start;
  5260. }
  5261. }
  5262. }
  5263. function computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {
  5264. let reloadInterval = 1000 * newDetails.targetduration;
  5265. if (newDetails.updated) {
  5266. // Use last segment duration when shorter than target duration and near live edge
  5267. const fragments = newDetails.fragments;
  5268. const liveEdgeMaxTargetDurations = 4;
  5269. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5270. const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5271. if (lastSegmentDuration < reloadInterval) {
  5272. reloadInterval = lastSegmentDuration;
  5273. }
  5274. }
  5275. } else {
  5276. // estimate = 'miss half average';
  5277. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5278. // changed then it MUST wait for a period of one-half the target
  5279. // duration before retrying.
  5280. reloadInterval /= 2;
  5281. }
  5282. return Math.round(reloadInterval);
  5283. }
  5284. function getFragmentWithSN(level, sn, fragCurrent) {
  5285. if (!(level != null && level.details)) {
  5286. return null;
  5287. }
  5288. const levelDetails = level.details;
  5289. let fragment = levelDetails.fragments[sn - levelDetails.startSN];
  5290. if (fragment) {
  5291. return fragment;
  5292. }
  5293. fragment = levelDetails.fragmentHint;
  5294. if (fragment && fragment.sn === sn) {
  5295. return fragment;
  5296. }
  5297. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  5298. return fragCurrent;
  5299. }
  5300. return null;
  5301. }
  5302. function getPartWith(level, sn, partIndex) {
  5303. var _level$details;
  5304. if (!(level != null && level.details)) {
  5305. return null;
  5306. }
  5307. return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex);
  5308. }
  5309. function findPart(partList, sn, partIndex) {
  5310. if (partList) {
  5311. for (let i = partList.length; i--;) {
  5312. const part = partList[i];
  5313. if (part.index === partIndex && part.fragment.sn === sn) {
  5314. return part;
  5315. }
  5316. }
  5317. }
  5318. return null;
  5319. }
  5320. function reassignFragmentLevelIndexes(levels) {
  5321. levels.forEach((level, index) => {
  5322. const {
  5323. details
  5324. } = level;
  5325. if (details != null && details.fragments) {
  5326. details.fragments.forEach(fragment => {
  5327. fragment.level = index;
  5328. });
  5329. }
  5330. });
  5331. }
  5332. function isTimeoutError(error) {
  5333. switch (error.details) {
  5334. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5335. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5336. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5337. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  5338. return true;
  5339. }
  5340. return false;
  5341. }
  5342. function getRetryConfig(loadPolicy, error) {
  5343. const isTimeout = isTimeoutError(error);
  5344. return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];
  5345. }
  5346. function getRetryDelay(retryConfig, retryCount) {
  5347. // exponential backoff capped to max retry delay
  5348. const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  5349. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  5350. }
  5351. function getLoaderConfigWithoutReties(loderConfig) {
  5352. return _objectSpread2(_objectSpread2({}, loderConfig), {
  5353. errorRetry: null,
  5354. timeoutRetry: null
  5355. });
  5356. }
  5357. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  5358. if (!retryConfig) {
  5359. return false;
  5360. }
  5361. const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  5362. const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  5363. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  5364. }
  5365. function retryForHttpStatus(httpStatus) {
  5366. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  5367. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  5368. }
  5369. const BinarySearch = {
  5370. /**
  5371. * Searches for an item in an array which matches a certain condition.
  5372. * This requires the condition to only match one item in the array,
  5373. * and for the array to be ordered.
  5374. *
  5375. * @param list The array to search.
  5376. * @param comparisonFn
  5377. * Called and provided a candidate item as the first argument.
  5378. * Should return:
  5379. * > -1 if the item should be located at a lower index than the provided item.
  5380. * > 1 if the item should be located at a higher index than the provided item.
  5381. * > 0 if the item is the item you're looking for.
  5382. *
  5383. * @returns the object if found, otherwise returns null
  5384. */
  5385. search: function (list, comparisonFn) {
  5386. let minIndex = 0;
  5387. let maxIndex = list.length - 1;
  5388. let currentIndex = null;
  5389. let currentElement = null;
  5390. while (minIndex <= maxIndex) {
  5391. currentIndex = (minIndex + maxIndex) / 2 | 0;
  5392. currentElement = list[currentIndex];
  5393. const comparisonResult = comparisonFn(currentElement);
  5394. if (comparisonResult > 0) {
  5395. minIndex = currentIndex + 1;
  5396. } else if (comparisonResult < 0) {
  5397. maxIndex = currentIndex - 1;
  5398. } else {
  5399. return currentElement;
  5400. }
  5401. }
  5402. return null;
  5403. }
  5404. };
  5405. /**
  5406. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  5407. * @param fragments - The array of candidate fragments
  5408. * @param PDTValue - The PDT value which must be exceeded
  5409. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5410. */
  5411. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5412. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  5413. return null;
  5414. }
  5415. // if less than start
  5416. const startPDT = fragments[0].programDateTime;
  5417. if (PDTValue < (startPDT || 0)) {
  5418. return null;
  5419. }
  5420. const endPDT = fragments[fragments.length - 1].endProgramDateTime;
  5421. if (PDTValue >= (endPDT || 0)) {
  5422. return null;
  5423. }
  5424. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5425. for (let seg = 0; seg < fragments.length; ++seg) {
  5426. const frag = fragments[seg];
  5427. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5428. return frag;
  5429. }
  5430. }
  5431. return null;
  5432. }
  5433. /**
  5434. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5435. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5436. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5437. * @param fragPrevious - The last frag successfully appended
  5438. * @param fragments - The array of candidate fragments
  5439. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  5440. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5441. * @returns a matching fragment or null
  5442. */
  5443. function findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {
  5444. let fragNext = null;
  5445. if (fragPrevious) {
  5446. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  5447. // check for buffer-end rounding error
  5448. const bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  5449. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  5450. bufferEnd += 0.0000015;
  5451. }
  5452. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  5453. fragNext = fragments[0];
  5454. }
  5455. // Prefer the next fragment if it's within tolerance
  5456. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  5457. return fragNext;
  5458. }
  5459. // We might be seeking past the tolerance so find the best match
  5460. const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5461. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  5462. return foundFragment;
  5463. }
  5464. // If no match was found return the next fragment after fragPrevious, or null
  5465. return fragNext;
  5466. }
  5467. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  5468. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  5469. const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {
  5470. if (tag[0] === 'INF') {
  5471. duration += parseFloat(tag[1]);
  5472. }
  5473. return duration;
  5474. }, nextFragLookupTolerance);
  5475. return fragNext.start <= firstDuration;
  5476. }
  5477. return false;
  5478. }
  5479. /**
  5480. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5481. * @param candidate - The fragment to test
  5482. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  5483. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5484. * @returns 0 if it matches, 1 if too low, -1 if too high
  5485. */
  5486. function fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {
  5487. // eagerly accept an accurate match (no tolerance)
  5488. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  5489. return 0;
  5490. }
  5491. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5492. // this is to cope with situations like
  5493. // bufferEnd = 9.991
  5494. // frag[Ø] : [0,10]
  5495. // frag[1] : [10,20]
  5496. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5497. // frag start frag start+duration
  5498. // |-----------------------------|
  5499. // <---> <--->
  5500. // ...--------><-----------------------------><---------....
  5501. // previous frag matching fragment next frag
  5502. // return -1 return 0 return 1
  5503. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5504. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5505. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5506. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5507. return 1;
  5508. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5509. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5510. return -1;
  5511. }
  5512. return 0;
  5513. }
  5514. /**
  5515. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5516. * This function tests the candidate's program date time values, as represented in Unix time
  5517. * @param candidate - The fragment to test
  5518. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  5519. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5520. * @returns true if contiguous, false otherwise
  5521. */
  5522. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5523. const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5524. // endProgramDateTime can be null, default to zero
  5525. const endProgramDateTime = candidate.endProgramDateTime || 0;
  5526. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5527. }
  5528. function findFragWithCC(fragments, cc) {
  5529. return BinarySearch.search(fragments, candidate => {
  5530. if (candidate.cc < cc) {
  5531. return 1;
  5532. } else if (candidate.cc > cc) {
  5533. return -1;
  5534. } else {
  5535. return 0;
  5536. }
  5537. });
  5538. }
  5539. var NetworkErrorAction = {
  5540. DoNothing: 0,
  5541. SendEndCallback: 1,
  5542. SendAlternateToPenaltyBox: 2,
  5543. RemoveAlternatePermanently: 3,
  5544. InsertDiscontinuity: 4,
  5545. RetryRequest: 5
  5546. };
  5547. var ErrorActionFlags = {
  5548. None: 0,
  5549. MoveAllAlternatesMatchingHost: 1,
  5550. MoveAllAlternatesMatchingHDCP: 2,
  5551. SwitchToSDR: 4
  5552. }; // Reserved for future use
  5553. class ErrorController {
  5554. constructor(hls) {
  5555. this.hls = void 0;
  5556. this.playlistError = 0;
  5557. this.penalizedRenditions = {};
  5558. this.log = void 0;
  5559. this.warn = void 0;
  5560. this.error = void 0;
  5561. this.hls = hls;
  5562. this.log = logger.log.bind(logger, `[info]:`);
  5563. this.warn = logger.warn.bind(logger, `[warning]:`);
  5564. this.error = logger.error.bind(logger, `[error]:`);
  5565. this.registerListeners();
  5566. }
  5567. registerListeners() {
  5568. const hls = this.hls;
  5569. hls.on(Events.ERROR, this.onError, this);
  5570. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5571. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5572. }
  5573. unregisterListeners() {
  5574. const hls = this.hls;
  5575. if (!hls) {
  5576. return;
  5577. }
  5578. hls.off(Events.ERROR, this.onError, this);
  5579. hls.off(Events.ERROR, this.onErrorOut, this);
  5580. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5581. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5582. }
  5583. destroy() {
  5584. this.unregisterListeners();
  5585. // @ts-ignore
  5586. this.hls = null;
  5587. this.penalizedRenditions = {};
  5588. }
  5589. startLoad(startPosition) {}
  5590. stopLoad() {
  5591. this.playlistError = 0;
  5592. }
  5593. getVariantLevelIndex(frag) {
  5594. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  5595. }
  5596. onManifestLoading() {
  5597. this.playlistError = 0;
  5598. this.penalizedRenditions = {};
  5599. }
  5600. onLevelUpdated() {
  5601. this.playlistError = 0;
  5602. }
  5603. onError(event, data) {
  5604. var _data$frag, _data$level;
  5605. if (data.fatal) {
  5606. return;
  5607. }
  5608. const hls = this.hls;
  5609. const context = data.context;
  5610. switch (data.details) {
  5611. case ErrorDetails.FRAG_LOAD_ERROR:
  5612. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5613. case ErrorDetails.KEY_LOAD_ERROR:
  5614. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5615. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5616. return;
  5617. case ErrorDetails.FRAG_PARSING_ERROR:
  5618. // ignore empty segment errors marked as gap
  5619. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  5620. data.errorAction = {
  5621. action: NetworkErrorAction.DoNothing,
  5622. flags: ErrorActionFlags.None
  5623. };
  5624. return;
  5625. }
  5626. // falls through
  5627. case ErrorDetails.FRAG_GAP:
  5628. case ErrorDetails.FRAG_DECRYPT_ERROR:
  5629. {
  5630. // Switch level if possible, otherwise allow retry count to reach max error retries
  5631. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5632. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5633. return;
  5634. }
  5635. case ErrorDetails.LEVEL_EMPTY_ERROR:
  5636. case ErrorDetails.LEVEL_PARSING_ERROR:
  5637. {
  5638. var _data$context, _data$context$levelDe;
  5639. // Only retry when empty and live
  5640. const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  5641. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  5642. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  5643. } else {
  5644. // Escalate to fatal if not retrying or switching
  5645. data.levelRetry = false;
  5646. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5647. }
  5648. }
  5649. return;
  5650. case ErrorDetails.LEVEL_LOAD_ERROR:
  5651. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5652. if (typeof (context == null ? void 0 : context.level) === 'number') {
  5653. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  5654. }
  5655. return;
  5656. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  5657. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  5658. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  5659. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  5660. if (context) {
  5661. const level = hls.levels[hls.loadLevel];
  5662. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  5663. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  5664. // otherwise allow playlist retry count to reach max error retries
  5665. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  5666. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5667. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  5668. return;
  5669. }
  5670. }
  5671. return;
  5672. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  5673. {
  5674. const level = hls.levels[hls.loadLevel];
  5675. const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];
  5676. if (restrictedHdcpLevel) {
  5677. data.errorAction = {
  5678. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5679. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  5680. hdcpLevel: restrictedHdcpLevel
  5681. };
  5682. } else {
  5683. this.keySystemError(data);
  5684. }
  5685. }
  5686. return;
  5687. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  5688. case ErrorDetails.REMUX_ALLOC_ERROR:
  5689. case ErrorDetails.BUFFER_APPEND_ERROR:
  5690. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  5691. return;
  5692. case ErrorDetails.INTERNAL_EXCEPTION:
  5693. case ErrorDetails.BUFFER_APPENDING_ERROR:
  5694. case ErrorDetails.BUFFER_FULL_ERROR:
  5695. case ErrorDetails.LEVEL_SWITCH_ERROR:
  5696. case ErrorDetails.BUFFER_STALLED_ERROR:
  5697. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  5698. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  5699. data.errorAction = {
  5700. action: NetworkErrorAction.DoNothing,
  5701. flags: ErrorActionFlags.None
  5702. };
  5703. return;
  5704. }
  5705. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  5706. this.keySystemError(data);
  5707. }
  5708. }
  5709. keySystemError(data) {
  5710. const levelIndex = this.getVariantLevelIndex(data.frag);
  5711. // Do not retry level. Escalate to fatal if switching levels fails.
  5712. data.levelRetry = false;
  5713. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5714. }
  5715. getPlaylistRetryOrSwitchAction(data, levelIndex) {
  5716. const hls = this.hls;
  5717. const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  5718. const retryCount = this.playlistError++;
  5719. const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  5720. if (retry) {
  5721. return {
  5722. action: NetworkErrorAction.RetryRequest,
  5723. flags: ErrorActionFlags.None,
  5724. retryConfig,
  5725. retryCount
  5726. };
  5727. }
  5728. const errorAction = this.getLevelSwitchAction(data, levelIndex);
  5729. if (retryConfig) {
  5730. errorAction.retryConfig = retryConfig;
  5731. errorAction.retryCount = retryCount;
  5732. }
  5733. return errorAction;
  5734. }
  5735. getFragRetryOrSwitchAction(data) {
  5736. const hls = this.hls;
  5737. // Share fragment error count accross media options (main, audio, subs)
  5738. // This allows for level based rendition switching when media option assets fail
  5739. const variantLevelIndex = this.getVariantLevelIndex(data.frag);
  5740. const level = hls.levels[variantLevelIndex];
  5741. const {
  5742. fragLoadPolicy,
  5743. keyLoadPolicy
  5744. } = hls.config;
  5745. const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  5746. const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);
  5747. // Switch levels when out of retried or level index out of bounds
  5748. if (level) {
  5749. if (data.details !== ErrorDetails.FRAG_GAP) {
  5750. level.fragmentError++;
  5751. }
  5752. const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  5753. if (retry) {
  5754. return {
  5755. action: NetworkErrorAction.RetryRequest,
  5756. flags: ErrorActionFlags.None,
  5757. retryConfig,
  5758. retryCount: fragmentErrors
  5759. };
  5760. }
  5761. }
  5762. // Reach max retry count, or Missing level reference
  5763. // Switch to valid index
  5764. const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  5765. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  5766. if (retryConfig) {
  5767. errorAction.retryConfig = retryConfig;
  5768. errorAction.retryCount = fragmentErrors;
  5769. }
  5770. return errorAction;
  5771. }
  5772. getLevelSwitchAction(data, levelIndex) {
  5773. const hls = this.hls;
  5774. if (levelIndex === null || levelIndex === undefined) {
  5775. levelIndex = hls.loadLevel;
  5776. }
  5777. const level = this.hls.levels[levelIndex];
  5778. if (level) {
  5779. var _data$frag2, _data$context2;
  5780. const errorDetails = data.details;
  5781. level.loadError++;
  5782. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  5783. level.fragmentError++;
  5784. }
  5785. // Search for next level to retry
  5786. let nextLevel = -1;
  5787. const {
  5788. levels,
  5789. loadLevel,
  5790. minAutoLevel,
  5791. maxAutoLevel
  5792. } = hls;
  5793. if (!hls.autoLevelEnabled) {
  5794. hls.loadLevel = -1;
  5795. }
  5796. const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  5797. // Find alternate audio codec if available on audio codec error
  5798. const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5799. const findAudioCodecAlternate = isAudioCodecError && levels.some(({
  5800. audioCodec
  5801. }) => level.audioCodec !== audioCodec);
  5802. // Find alternate video codec if available on video codec error
  5803. const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5804. const findVideoCodecAlternate = isVideoCodecError && levels.some(({
  5805. codecSet,
  5806. audioCodec
  5807. }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);
  5808. const {
  5809. type: playlistErrorType,
  5810. groupId: playlistErrorGroupId
  5811. } = (_data$context2 = data.context) != null ? _data$context2 : {};
  5812. for (let i = levels.length; i--;) {
  5813. const candidate = (i + loadLevel) % levels.length;
  5814. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  5815. var _level$audioGroups, _level$subtitleGroups;
  5816. const levelCandidate = levels[candidate];
  5817. // Skip level switch if GAP tag is found in next level at same position
  5818. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  5819. const levelDetails = levels[candidate].details;
  5820. if (levelDetails) {
  5821. const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  5822. if (fragCandidate != null && fragCandidate.gap) {
  5823. continue;
  5824. }
  5825. }
  5826. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  5827. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  5828. continue;
  5829. } 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) {
  5830. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  5831. continue;
  5832. }
  5833. nextLevel = candidate;
  5834. break;
  5835. }
  5836. }
  5837. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5838. data.levelRetry = true;
  5839. this.playlistError = 0;
  5840. return {
  5841. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5842. flags: ErrorActionFlags.None,
  5843. nextAutoLevel: nextLevel
  5844. };
  5845. }
  5846. }
  5847. // No levels to switch / Manual level selection / Level not found
  5848. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5849. return {
  5850. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5851. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5852. };
  5853. }
  5854. onErrorOut(event, data) {
  5855. var _data$errorAction;
  5856. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5857. case NetworkErrorAction.DoNothing:
  5858. break;
  5859. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5860. this.sendAlternateToPenaltyBox(data);
  5861. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5862. data.fatal = true;
  5863. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5864. this.warn(`MediaSource ended after "${data.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`);
  5865. this.hls.recoverMediaError();
  5866. }
  5867. break;
  5868. case NetworkErrorAction.RetryRequest:
  5869. // handled by stream and playlist/level controllers
  5870. break;
  5871. }
  5872. if (data.fatal) {
  5873. this.hls.stopLoad();
  5874. return;
  5875. }
  5876. }
  5877. sendAlternateToPenaltyBox(data) {
  5878. const hls = this.hls;
  5879. const errorAction = data.errorAction;
  5880. if (!errorAction) {
  5881. return;
  5882. }
  5883. const {
  5884. flags,
  5885. hdcpLevel,
  5886. nextAutoLevel
  5887. } = errorAction;
  5888. switch (flags) {
  5889. case ErrorActionFlags.None:
  5890. this.switchLevel(data, nextAutoLevel);
  5891. break;
  5892. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5893. if (hdcpLevel) {
  5894. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5895. errorAction.resolved = true;
  5896. }
  5897. this.warn(`Restricting playback to HDCP-LEVEL of "${hls.maxHdcpLevel}" or lower`);
  5898. break;
  5899. }
  5900. // If not resolved by previous actions try to switch to next level
  5901. if (!errorAction.resolved) {
  5902. this.switchLevel(data, nextAutoLevel);
  5903. }
  5904. }
  5905. switchLevel(data, levelIndex) {
  5906. if (levelIndex !== undefined && data.errorAction) {
  5907. this.warn(`switching to level ${levelIndex} after ${data.details}`);
  5908. this.hls.nextAutoLevel = levelIndex;
  5909. data.errorAction.resolved = true;
  5910. // Stream controller is responsible for this but won't switch on false start
  5911. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5912. }
  5913. }
  5914. }
  5915. class BasePlaylistController {
  5916. constructor(hls, logPrefix) {
  5917. this.hls = void 0;
  5918. this.timer = -1;
  5919. this.requestScheduled = -1;
  5920. this.canLoad = false;
  5921. this.log = void 0;
  5922. this.warn = void 0;
  5923. this.log = logger.log.bind(logger, `${logPrefix}:`);
  5924. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  5925. this.hls = hls;
  5926. }
  5927. destroy() {
  5928. this.clearTimer();
  5929. // @ts-ignore
  5930. this.hls = this.log = this.warn = null;
  5931. }
  5932. clearTimer() {
  5933. if (this.timer !== -1) {
  5934. self.clearTimeout(this.timer);
  5935. this.timer = -1;
  5936. }
  5937. }
  5938. startLoad() {
  5939. this.canLoad = true;
  5940. this.requestScheduled = -1;
  5941. this.loadPlaylist();
  5942. }
  5943. stopLoad() {
  5944. this.canLoad = false;
  5945. this.clearTimer();
  5946. }
  5947. switchParams(playlistUri, previous, current) {
  5948. const renditionReports = previous == null ? void 0 : previous.renditionReports;
  5949. if (renditionReports) {
  5950. let foundIndex = -1;
  5951. for (let i = 0; i < renditionReports.length; i++) {
  5952. const attr = renditionReports[i];
  5953. let uri;
  5954. try {
  5955. uri = new self.URL(attr.URI, previous.url).href;
  5956. } catch (error) {
  5957. logger.warn(`Could not construct new URL for Rendition Report: ${error}`);
  5958. uri = attr.URI || '';
  5959. }
  5960. // Use exact match. Otherwise, the last partial match, if any, will be used
  5961. // (Playlist URI includes a query string that the Rendition Report does not)
  5962. if (uri === playlistUri) {
  5963. foundIndex = i;
  5964. break;
  5965. } else if (uri === playlistUri.substring(0, uri.length)) {
  5966. foundIndex = i;
  5967. }
  5968. }
  5969. if (foundIndex !== -1) {
  5970. const attr = renditionReports[foundIndex];
  5971. const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  5972. let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  5973. if (this.hls.config.lowLatencyMode) {
  5974. const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  5975. if (part >= 0 && currentGoal > previous.partTarget) {
  5976. part += 1;
  5977. }
  5978. }
  5979. const skip = current && getSkipValue(current);
  5980. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  5981. }
  5982. }
  5983. }
  5984. loadPlaylist(hlsUrlParameters) {
  5985. if (this.requestScheduled === -1) {
  5986. this.requestScheduled = self.performance.now();
  5987. }
  5988. // Loading is handled by the subclasses
  5989. }
  5990. shouldLoadPlaylist(playlist) {
  5991. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  5992. }
  5993. shouldReloadPlaylist(playlist) {
  5994. return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist);
  5995. }
  5996. playlistLoaded(index, data, previousDetails) {
  5997. const {
  5998. details,
  5999. stats
  6000. } = data;
  6001. // Set last updated date-time
  6002. const now = self.performance.now();
  6003. const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  6004. details.advancedDateTime = Date.now() - elapsed;
  6005. // if current playlist is a live playlist, arm a timer to reload it
  6006. if (details.live || previousDetails != null && previousDetails.live) {
  6007. details.reloaded(previousDetails);
  6008. if (previousDetails) {
  6009. this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);
  6010. }
  6011. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  6012. if (previousDetails && details.fragments.length > 0) {
  6013. mergeDetails(previousDetails, details);
  6014. }
  6015. if (!this.canLoad || !details.live) {
  6016. return;
  6017. }
  6018. let deliveryDirectives;
  6019. let msn = undefined;
  6020. let part = undefined;
  6021. if (details.canBlockReload && details.endSN && details.advanced) {
  6022. // Load level with LL-HLS delivery directives
  6023. const lowLatencyMode = this.hls.config.lowLatencyMode;
  6024. const lastPartSn = details.lastPartSn;
  6025. const endSn = details.endSN;
  6026. const lastPartIndex = details.lastPartIndex;
  6027. const hasParts = lastPartIndex !== -1;
  6028. const lastPart = lastPartSn === endSn;
  6029. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  6030. const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  6031. if (hasParts) {
  6032. msn = lastPart ? endSn + 1 : lastPartSn;
  6033. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  6034. } else {
  6035. msn = endSn + 1;
  6036. }
  6037. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  6038. // Update directives to obtain the Playlist that has the estimated additional duration of media
  6039. const lastAdvanced = details.age;
  6040. const cdnAge = lastAdvanced + details.ageHeader;
  6041. let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  6042. if (currentGoal > 0) {
  6043. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  6044. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  6045. // then we either can't catchup, or the "age" header cannot be trusted.
  6046. this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);
  6047. currentGoal = 0;
  6048. } else {
  6049. const segments = Math.floor(currentGoal / details.targetduration);
  6050. msn += segments;
  6051. if (part !== undefined) {
  6052. const parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  6053. part += parts;
  6054. }
  6055. this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);
  6056. }
  6057. details.tuneInGoal = currentGoal;
  6058. }
  6059. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6060. if (lowLatencyMode || !lastPart) {
  6061. this.loadPlaylist(deliveryDirectives);
  6062. return;
  6063. }
  6064. } else if (details.canBlockReload || details.canSkipUntil) {
  6065. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  6066. }
  6067. const bufferInfo = this.hls.mainForwardBufferInfo;
  6068. const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  6069. const distanceToLiveEdgeMs = (details.edge - position) * 1000;
  6070. const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  6071. if (details.updated && now > this.requestScheduled + reloadInterval) {
  6072. this.requestScheduled = stats.loading.start;
  6073. }
  6074. if (msn !== undefined && details.canBlockReload) {
  6075. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  6076. } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now) {
  6077. this.requestScheduled = now;
  6078. } else if (this.requestScheduled - now <= 0) {
  6079. this.requestScheduled += reloadInterval;
  6080. }
  6081. let estimatedTimeUntilUpdate = this.requestScheduled - now;
  6082. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  6083. this.log(`reload live playlist ${index} in ${Math.round(estimatedTimeUntilUpdate)} ms`);
  6084. // this.log(
  6085. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  6086. // reload in ${estimatedTimeUntilUpdate / 1000}
  6087. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  6088. // diff ${
  6089. // (reloadInterval -
  6090. // (estimatedTimeUntilUpdate +
  6091. // stats.loading.end -
  6092. // stats.loading.start)) /
  6093. // 1000
  6094. // }
  6095. // reload interval ${reloadInterval / 1000}
  6096. // target duration ${details.targetduration}
  6097. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  6098. // );
  6099. this.timer = self.setTimeout(() => this.loadPlaylist(deliveryDirectives), estimatedTimeUntilUpdate);
  6100. } else {
  6101. this.clearTimer();
  6102. }
  6103. }
  6104. getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  6105. let skip = getSkipValue(details);
  6106. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  6107. msn = previousDeliveryDirectives.msn;
  6108. part = previousDeliveryDirectives.part;
  6109. skip = HlsSkip.No;
  6110. }
  6111. return new HlsUrlParameters(msn, part, skip);
  6112. }
  6113. checkRetry(errorEvent) {
  6114. const errorDetails = errorEvent.details;
  6115. const isTimeout = isTimeoutError(errorEvent);
  6116. const errorAction = errorEvent.errorAction;
  6117. const {
  6118. action,
  6119. retryCount = 0,
  6120. retryConfig
  6121. } = errorAction || {};
  6122. const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  6123. if (retry) {
  6124. var _errorEvent$context;
  6125. this.requestScheduled = -1;
  6126. if (retryCount >= retryConfig.maxNumRetry) {
  6127. return false;
  6128. }
  6129. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  6130. // The LL-HLS request already timed out so retry immediately
  6131. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" without delivery-directives`);
  6132. this.loadPlaylist();
  6133. } else {
  6134. const delay = getRetryDelay(retryConfig, retryCount);
  6135. // Schedule level/track reload
  6136. this.timer = self.setTimeout(() => this.loadPlaylist(), delay);
  6137. this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after "${errorDetails}" in ${delay}ms`);
  6138. }
  6139. // `levelRetry = true` used to inform other controllers that a retry is happening
  6140. errorEvent.levelRetry = true;
  6141. errorAction.resolved = true;
  6142. }
  6143. return retry;
  6144. }
  6145. }
  6146. /*
  6147. * compute an Exponential Weighted moving average
  6148. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  6149. * - heavily inspired from shaka-player
  6150. */
  6151. class EWMA {
  6152. // About half of the estimated value will be from the last |halfLife| samples by weight.
  6153. constructor(halfLife, estimate = 0, weight = 0) {
  6154. this.halfLife = void 0;
  6155. this.alpha_ = void 0;
  6156. this.estimate_ = void 0;
  6157. this.totalWeight_ = void 0;
  6158. this.halfLife = halfLife;
  6159. // Larger values of alpha expire historical data more slowly.
  6160. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  6161. this.estimate_ = estimate;
  6162. this.totalWeight_ = weight;
  6163. }
  6164. sample(weight, value) {
  6165. const adjAlpha = Math.pow(this.alpha_, weight);
  6166. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  6167. this.totalWeight_ += weight;
  6168. }
  6169. getTotalWeight() {
  6170. return this.totalWeight_;
  6171. }
  6172. getEstimate() {
  6173. if (this.alpha_) {
  6174. const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  6175. if (zeroFactor) {
  6176. return this.estimate_ / zeroFactor;
  6177. }
  6178. }
  6179. return this.estimate_;
  6180. }
  6181. }
  6182. /*
  6183. * EWMA Bandwidth Estimator
  6184. * - heavily inspired from shaka-player
  6185. * Tracks bandwidth samples and estimates available bandwidth.
  6186. * Based on the minimum of two exponentially-weighted moving averages with
  6187. * different half-lives.
  6188. */
  6189. class EwmaBandWidthEstimator {
  6190. constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {
  6191. this.defaultEstimate_ = void 0;
  6192. this.minWeight_ = void 0;
  6193. this.minDelayMs_ = void 0;
  6194. this.slow_ = void 0;
  6195. this.fast_ = void 0;
  6196. this.defaultTTFB_ = void 0;
  6197. this.ttfb_ = void 0;
  6198. this.defaultEstimate_ = defaultEstimate;
  6199. this.minWeight_ = 0.001;
  6200. this.minDelayMs_ = 50;
  6201. this.slow_ = new EWMA(slow);
  6202. this.fast_ = new EWMA(fast);
  6203. this.defaultTTFB_ = defaultTTFB;
  6204. this.ttfb_ = new EWMA(slow);
  6205. }
  6206. update(slow, fast) {
  6207. const {
  6208. slow_,
  6209. fast_,
  6210. ttfb_
  6211. } = this;
  6212. if (slow_.halfLife !== slow) {
  6213. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  6214. }
  6215. if (fast_.halfLife !== fast) {
  6216. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  6217. }
  6218. if (ttfb_.halfLife !== slow) {
  6219. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  6220. }
  6221. }
  6222. sample(durationMs, numBytes) {
  6223. durationMs = Math.max(durationMs, this.minDelayMs_);
  6224. const numBits = 8 * numBytes;
  6225. // weight is duration in seconds
  6226. const durationS = durationMs / 1000;
  6227. // value is bandwidth in bits/s
  6228. const bandwidthInBps = numBits / durationS;
  6229. this.fast_.sample(durationS, bandwidthInBps);
  6230. this.slow_.sample(durationS, bandwidthInBps);
  6231. }
  6232. sampleTTFB(ttfb) {
  6233. // weight is frequency curve applied to TTFB in seconds
  6234. // (longer times have less weight with expected input under 1 second)
  6235. const seconds = ttfb / 1000;
  6236. const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  6237. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  6238. }
  6239. canEstimate() {
  6240. return this.fast_.getTotalWeight() >= this.minWeight_;
  6241. }
  6242. getEstimate() {
  6243. if (this.canEstimate()) {
  6244. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  6245. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  6246. // Take the minimum of these two estimates. This should have the effect of
  6247. // adapting down quickly, but up more slowly.
  6248. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  6249. } else {
  6250. return this.defaultEstimate_;
  6251. }
  6252. }
  6253. getEstimateTTFB() {
  6254. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  6255. return this.ttfb_.getEstimate();
  6256. } else {
  6257. return this.defaultTTFB_;
  6258. }
  6259. }
  6260. destroy() {}
  6261. }
  6262. const SUPPORTED_INFO_DEFAULT = {
  6263. supported: true,
  6264. configurations: [],
  6265. decodingInfoResults: [{
  6266. supported: true,
  6267. powerEfficient: true,
  6268. smooth: true
  6269. }]
  6270. };
  6271. const SUPPORTED_INFO_CACHE = {};
  6272. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  6273. // Only test support when configuration is exceeds minimum options
  6274. const audioGroups = level.audioCodec ? level.audioGroups : null;
  6275. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6276. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6277. const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  6278. let audioChannels = null;
  6279. if (audioGroups != null && audioGroups.length) {
  6280. try {
  6281. if (audioGroups.length === 1 && audioGroups[0]) {
  6282. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  6283. } else {
  6284. audioChannels = audioGroups.reduce((acc, groupId) => {
  6285. if (groupId) {
  6286. const audioTrackGroup = audioTracksByGroup.groups[groupId];
  6287. if (!audioTrackGroup) {
  6288. throw new Error(`Audio track group ${groupId} not found`);
  6289. }
  6290. // Sum all channel key values
  6291. Object.keys(audioTrackGroup.channels).forEach(key => {
  6292. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  6293. });
  6294. }
  6295. return acc;
  6296. }, {
  6297. 2: 0
  6298. });
  6299. }
  6300. } catch (error) {
  6301. return true;
  6302. }
  6303. }
  6304. 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);
  6305. }
  6306. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities) {
  6307. const videoCodecs = level.videoCodec;
  6308. const audioCodecs = level.audioCodec;
  6309. if (!videoCodecs || !audioCodecs || !mediaCapabilities) {
  6310. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  6311. }
  6312. const baseVideoConfiguration = {
  6313. width: level.width,
  6314. height: level.height,
  6315. bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)),
  6316. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  6317. framerate: level.frameRate || 30
  6318. };
  6319. const videoRange = level.videoRange;
  6320. if (videoRange !== 'SDR') {
  6321. baseVideoConfiguration.transferFunction = videoRange.toLowerCase();
  6322. }
  6323. const configurations = videoCodecs.split(',').map(videoCodec => ({
  6324. type: 'media-source',
  6325. video: _objectSpread2(_objectSpread2({}, baseVideoConfiguration), {}, {
  6326. contentType: mimeTypeForCodec(videoCodec, 'video')
  6327. })
  6328. }));
  6329. if (audioCodecs && level.audioGroups) {
  6330. level.audioGroups.forEach(audioGroupId => {
  6331. var _audioTracksByGroup$g;
  6332. if (!audioGroupId) {
  6333. return;
  6334. }
  6335. (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks.forEach(audioTrack => {
  6336. if (audioTrack.groupId === audioGroupId) {
  6337. const channels = audioTrack.channels || '';
  6338. const channelsNumber = parseFloat(channels);
  6339. if (isFiniteNumber(channelsNumber) && channelsNumber > 2) {
  6340. configurations.push.apply(configurations, audioCodecs.split(',').map(audioCodec => ({
  6341. type: 'media-source',
  6342. audio: {
  6343. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  6344. channels: '' + channelsNumber
  6345. // spatialRendering:
  6346. // audioCodec === 'ec-3' && channels.indexOf('JOC'),
  6347. }
  6348. })));
  6349. }
  6350. }
  6351. });
  6352. });
  6353. }
  6354. return Promise.all(configurations.map(configuration => {
  6355. // Cache MediaCapabilities promises
  6356. const decodingInfoKey = getMediaDecodingInfoKey(configuration);
  6357. return SUPPORTED_INFO_CACHE[decodingInfoKey] || (SUPPORTED_INFO_CACHE[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  6358. })).then(decodingInfoResults => ({
  6359. supported: !decodingInfoResults.some(info => !info.supported),
  6360. configurations,
  6361. decodingInfoResults
  6362. })).catch(error => ({
  6363. supported: false,
  6364. configurations,
  6365. decodingInfoResults: [],
  6366. error
  6367. }));
  6368. }
  6369. function getMediaDecodingInfoKey(config) {
  6370. const {
  6371. audio,
  6372. video
  6373. } = config;
  6374. const mediaConfig = video || audio;
  6375. if (mediaConfig) {
  6376. const codec = mediaConfig.contentType.split('"')[1];
  6377. if (video) {
  6378. return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || 'sd'}_${codec}_${Math.ceil(video.bitrate / 1e5)}`;
  6379. }
  6380. if (audio) {
  6381. return `c${audio.channels}${audio.spatialRendering ? 's' : 'n'}_${codec}`;
  6382. }
  6383. }
  6384. return '';
  6385. }
  6386. /**
  6387. * @returns Whether we can detect and validate HDR capability within the window context
  6388. */
  6389. function isHdrSupported() {
  6390. if (typeof matchMedia === 'function') {
  6391. const mediaQueryList = matchMedia('(dynamic-range: high)');
  6392. const badQuery = matchMedia('bad query');
  6393. if (mediaQueryList.media !== badQuery.media) {
  6394. return mediaQueryList.matches === true;
  6395. }
  6396. }
  6397. return false;
  6398. }
  6399. /**
  6400. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  6401. * When both inputs are null:
  6402. *
  6403. * `{ preferHDR: false, allowedVideoRanges: [] }`
  6404. *
  6405. * When `currentVideoRange` non-null, maintain the active range:
  6406. *
  6407. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  6408. *
  6409. * When VideoSelectionOption non-null:
  6410. *
  6411. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  6412. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  6413. * - Else check window for HDR support and set `preferHDR` to the result.
  6414. *
  6415. * @param currentVideoRange
  6416. * @param videoPreference
  6417. */
  6418. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  6419. let preferHDR = false;
  6420. let allowedVideoRanges = [];
  6421. if (currentVideoRange) {
  6422. preferHDR = currentVideoRange !== 'SDR';
  6423. allowedVideoRanges = [currentVideoRange];
  6424. }
  6425. if (videoPreference) {
  6426. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  6427. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : isHdrSupported();
  6428. if (preferHDR) {
  6429. allowedVideoRanges = allowedVideoRanges.filter(range => range !== 'SDR');
  6430. } else {
  6431. allowedVideoRanges = ['SDR'];
  6432. }
  6433. }
  6434. return {
  6435. preferHDR,
  6436. allowedVideoRanges
  6437. };
  6438. }
  6439. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  6440. const codecSets = Object.keys(codecTiers);
  6441. const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6442. const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6443. const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  6444. // Use first level set to determine stereo, and minimum resolution and framerate
  6445. let hasStereo = true;
  6446. let hasCurrentVideoRange = false;
  6447. let minHeight = Infinity;
  6448. let minFramerate = Infinity;
  6449. let minBitrate = Infinity;
  6450. let selectedScore = 0;
  6451. let videoRanges = [];
  6452. const {
  6453. preferHDR,
  6454. allowedVideoRanges
  6455. } = getVideoSelectionOptions(currentVideoRange, videoPreference);
  6456. for (let i = codecSets.length; i--;) {
  6457. const tier = codecTiers[codecSets[i]];
  6458. hasStereo = tier.channels[2] > 0;
  6459. minHeight = Math.min(minHeight, tier.minHeight);
  6460. minFramerate = Math.min(minFramerate, tier.minFramerate);
  6461. minBitrate = Math.min(minBitrate, tier.minBitrate);
  6462. const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);
  6463. if (matchingVideoRanges.length > 0) {
  6464. hasCurrentVideoRange = true;
  6465. videoRanges = matchingVideoRanges;
  6466. }
  6467. }
  6468. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  6469. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  6470. const maxHeight = Math.max(1080, minHeight);
  6471. const maxFramerate = Math.max(30, minFramerate);
  6472. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  6473. currentBw = Math.max(minBitrate, currentBw);
  6474. // If there are no variants with matching preference, set currentVideoRange to undefined
  6475. if (!hasCurrentVideoRange) {
  6476. currentVideoRange = undefined;
  6477. videoRanges = [];
  6478. }
  6479. const codecSet = codecSets.reduce((selected, candidate) => {
  6480. // 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
  6481. const candidateTier = codecTiers[candidate];
  6482. if (candidate === selected) {
  6483. return selected;
  6484. }
  6485. if (candidateTier.minBitrate > currentBw) {
  6486. logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);
  6487. return selected;
  6488. }
  6489. if (!candidateTier.hasDefaultAudio) {
  6490. logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);
  6491. return selected;
  6492. }
  6493. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  6494. logStartCodecCandidateIgnored(candidate, `audio codec preference "${audioCodecPreference}" not found`);
  6495. return selected;
  6496. }
  6497. if (channelsPreference && !preferStereo) {
  6498. if (!candidateTier.channels[channelsPreference]) {
  6499. logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);
  6500. return selected;
  6501. }
  6502. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  6503. logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);
  6504. return selected;
  6505. }
  6506. if (candidateTier.minHeight > maxHeight) {
  6507. logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);
  6508. return selected;
  6509. }
  6510. if (candidateTier.minFramerate > maxFramerate) {
  6511. logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);
  6512. return selected;
  6513. }
  6514. if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {
  6515. logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${JSON.stringify(videoRanges)} found`);
  6516. return selected;
  6517. }
  6518. if (candidateTier.maxScore < selectedScore) {
  6519. logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);
  6520. return selected;
  6521. }
  6522. // Remove candiates with less preferred codecs or more errors
  6523. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  6524. return selected;
  6525. }
  6526. selectedScore = candidateTier.maxScore;
  6527. return candidate;
  6528. }, undefined);
  6529. return {
  6530. codecSet,
  6531. videoRanges,
  6532. preferHDR,
  6533. minFramerate,
  6534. minBitrate
  6535. };
  6536. }
  6537. function logStartCodecCandidateIgnored(codeSet, reason) {
  6538. logger.log(`[abr] start candidates with "${codeSet}" ignored because ${reason}`);
  6539. }
  6540. function getAudioTracksByGroup(allAudioTracks) {
  6541. return allAudioTracks.reduce((audioTracksByGroup, track) => {
  6542. let trackGroup = audioTracksByGroup.groups[track.groupId];
  6543. if (!trackGroup) {
  6544. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  6545. tracks: [],
  6546. channels: {
  6547. 2: 0
  6548. },
  6549. hasDefault: false,
  6550. hasAutoSelect: false
  6551. };
  6552. }
  6553. trackGroup.tracks.push(track);
  6554. const channelsKey = track.channels || '2';
  6555. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  6556. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  6557. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  6558. if (trackGroup.hasDefault) {
  6559. audioTracksByGroup.hasDefaultAudio = true;
  6560. }
  6561. if (trackGroup.hasAutoSelect) {
  6562. audioTracksByGroup.hasAutoSelectAudio = true;
  6563. }
  6564. return audioTracksByGroup;
  6565. }, {
  6566. hasDefaultAudio: false,
  6567. hasAutoSelectAudio: false,
  6568. groups: {}
  6569. });
  6570. }
  6571. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  6572. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level) => {
  6573. if (!level.codecSet) {
  6574. return tiers;
  6575. }
  6576. const audioGroups = level.audioGroups;
  6577. let tier = tiers[level.codecSet];
  6578. if (!tier) {
  6579. tiers[level.codecSet] = tier = {
  6580. minBitrate: Infinity,
  6581. minHeight: Infinity,
  6582. minFramerate: Infinity,
  6583. maxScore: 0,
  6584. videoRanges: {
  6585. SDR: 0
  6586. },
  6587. channels: {
  6588. '2': 0
  6589. },
  6590. hasDefaultAudio: !audioGroups,
  6591. fragmentError: 0
  6592. };
  6593. }
  6594. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  6595. const lesserWidthOrHeight = Math.min(level.height, level.width);
  6596. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  6597. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  6598. tier.maxScore = Math.max(tier.maxScore, level.score);
  6599. tier.fragmentError += level.fragmentError;
  6600. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  6601. if (audioGroups) {
  6602. audioGroups.forEach(audioGroupId => {
  6603. if (!audioGroupId) {
  6604. return;
  6605. }
  6606. const audioGroup = audioTracksByGroup.groups[audioGroupId];
  6607. if (!audioGroup) {
  6608. return;
  6609. }
  6610. // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants
  6611. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  6612. Object.keys(audioGroup.channels).forEach(channels => {
  6613. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  6614. });
  6615. });
  6616. }
  6617. return tiers;
  6618. }, {});
  6619. }
  6620. function findMatchingOption(option, tracks, matchPredicate) {
  6621. if ('attrs' in option) {
  6622. const index = tracks.indexOf(option);
  6623. if (index !== -1) {
  6624. return index;
  6625. }
  6626. }
  6627. for (let i = 0; i < tracks.length; i++) {
  6628. const track = tracks[i];
  6629. if (matchesOption(option, track, matchPredicate)) {
  6630. return i;
  6631. }
  6632. }
  6633. return -1;
  6634. }
  6635. function matchesOption(option, track, matchPredicate) {
  6636. const {
  6637. groupId,
  6638. name,
  6639. lang,
  6640. assocLang,
  6641. characteristics,
  6642. default: isDefault
  6643. } = option;
  6644. const forced = option.forced;
  6645. 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));
  6646. }
  6647. function characteristicsMatch(characteristicsA, characteristicsB = '') {
  6648. const arrA = characteristicsA.split(',');
  6649. const arrB = characteristicsB.split(',');
  6650. // Expects each item to be unique:
  6651. return arrA.length === arrB.length && !arrA.some(el => arrB.indexOf(el) === -1);
  6652. }
  6653. function audioMatchPredicate(option, track) {
  6654. const {
  6655. audioCodec,
  6656. channels
  6657. } = option;
  6658. return (audioCodec === undefined || (track.audioCodec || '').substring(0, 4) === audioCodec.substring(0, 4)) && (channels === undefined || channels === (track.channels || '2'));
  6659. }
  6660. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  6661. const currentLevel = levels[searchIndex];
  6662. // Are there variants with same URI as current level?
  6663. // If so, find a match that does not require any level URI change
  6664. const variants = levels.reduce((variantMap, level, index) => {
  6665. const uri = level.uri;
  6666. const renditions = variantMap[uri] || (variantMap[uri] = []);
  6667. renditions.push(index);
  6668. return variantMap;
  6669. }, {});
  6670. const renditions = variants[currentLevel.uri];
  6671. if (renditions.length > 1) {
  6672. searchIndex = Math.max.apply(Math, renditions);
  6673. }
  6674. // Find best match
  6675. const currentVideoRange = currentLevel.videoRange;
  6676. const currentFrameRate = currentLevel.frameRate;
  6677. const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  6678. const matchingVideo = searchDownAndUpList(levels, searchIndex, level => {
  6679. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  6680. return false;
  6681. }
  6682. const audioGroups = level.audioGroups;
  6683. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  6684. return findMatchingOption(option, tracks, matchPredicate) > -1;
  6685. });
  6686. if (matchingVideo > -1) {
  6687. return matchingVideo;
  6688. }
  6689. return searchDownAndUpList(levels, searchIndex, level => {
  6690. const audioGroups = level.audioGroups;
  6691. const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  6692. return findMatchingOption(option, tracks, matchPredicate) > -1;
  6693. });
  6694. }
  6695. function searchDownAndUpList(arr, searchIndex, predicate) {
  6696. for (let i = searchIndex; i; i--) {
  6697. if (predicate(arr[i])) {
  6698. return i;
  6699. }
  6700. }
  6701. for (let i = searchIndex + 1; i < arr.length; i++) {
  6702. if (predicate(arr[i])) {
  6703. return i;
  6704. }
  6705. }
  6706. return -1;
  6707. }
  6708. class AbrController {
  6709. constructor(_hls) {
  6710. this.hls = void 0;
  6711. this.lastLevelLoadSec = 0;
  6712. this.lastLoadedFragLevel = -1;
  6713. this.firstSelection = -1;
  6714. this._nextAutoLevel = -1;
  6715. this.nextAutoLevelKey = '';
  6716. this.audioTracksByGroup = null;
  6717. this.codecTiers = null;
  6718. this.timer = -1;
  6719. this.fragCurrent = null;
  6720. this.partCurrent = null;
  6721. this.bitrateTestDelay = 0;
  6722. this.bwEstimator = void 0;
  6723. /*
  6724. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  6725. quickly enough to prevent underbuffering
  6726. */
  6727. this._abandonRulesCheck = () => {
  6728. const {
  6729. fragCurrent: frag,
  6730. partCurrent: part,
  6731. hls
  6732. } = this;
  6733. const {
  6734. autoLevelEnabled,
  6735. media
  6736. } = hls;
  6737. if (!frag || !media) {
  6738. return;
  6739. }
  6740. const now = performance.now();
  6741. const stats = part ? part.stats : frag.stats;
  6742. const duration = part ? part.duration : frag.duration;
  6743. const timeLoading = now - stats.loading.start;
  6744. const minAutoLevel = hls.minAutoLevel;
  6745. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  6746. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) {
  6747. this.clearTimer();
  6748. // reset forced auto level value so that next level will be selected
  6749. this._nextAutoLevel = -1;
  6750. return;
  6751. }
  6752. // This check only runs if we're in ABR mode and actually playing
  6753. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  6754. return;
  6755. }
  6756. const bufferInfo = hls.mainForwardBufferInfo;
  6757. if (bufferInfo === null) {
  6758. return;
  6759. }
  6760. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6761. const playbackRate = Math.abs(media.playbackRate);
  6762. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  6763. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  6764. return;
  6765. }
  6766. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  6767. const bufferStarvationDelay = bufferInfo.len / playbackRate;
  6768. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6769. const loadedFirstByte = stats.loaded && ttfb > -1;
  6770. const bwEstimate = this.getBwEstimate();
  6771. const levels = hls.levels;
  6772. const level = levels[frag.level];
  6773. const expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8));
  6774. let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  6775. if (timeStreaming < 1 && loadedFirstByte) {
  6776. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  6777. }
  6778. const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  6779. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  6780. const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1000;
  6781. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  6782. if (fragLoadedDelay <= bufferStarvationDelay) {
  6783. return;
  6784. }
  6785. const bwe = loadRate ? loadRate * 8 : bwEstimate;
  6786. let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  6787. let nextLoadLevel;
  6788. // Iterate through lower level and try to find the largest one that avoids rebuffering
  6789. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  6790. // compute time to load next fragment at lower level
  6791. // 8 = bits per byte (bps/Bps)
  6792. const levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  6793. fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbEstimate / 1000, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details);
  6794. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  6795. break;
  6796. }
  6797. }
  6798. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  6799. // to load the current one
  6800. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  6801. return;
  6802. }
  6803. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  6804. if (fragLevelNextLoadedDelay > duration * 10) {
  6805. return;
  6806. }
  6807. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  6808. if (loadedFirstByte) {
  6809. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  6810. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6811. } else {
  6812. // If there has been no loading progress, sample TTFB
  6813. this.bwEstimator.sampleTTFB(timeLoading);
  6814. }
  6815. const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  6816. if (this.getBwEstimate() * this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) {
  6817. this.resetEstimator(nextLoadLevelBitrate);
  6818. }
  6819. this.clearTimer();
  6820. logger.warn(`[abr] Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} is loading too slowly;
  6821. Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s
  6822. Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s
  6823. Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s
  6824. TTFB estimate: ${ttfb | 0} ms
  6825. Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps
  6826. New BW estimate: ${this.getBwEstimate() | 0} bps
  6827. Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);
  6828. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  6829. frag,
  6830. part,
  6831. stats
  6832. });
  6833. };
  6834. this.hls = _hls;
  6835. this.bwEstimator = this.initEstimator();
  6836. this.registerListeners();
  6837. }
  6838. resetEstimator(abrEwmaDefaultEstimate) {
  6839. if (abrEwmaDefaultEstimate) {
  6840. logger.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);
  6841. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  6842. }
  6843. this.firstSelection = -1;
  6844. this.bwEstimator = this.initEstimator();
  6845. }
  6846. initEstimator() {
  6847. const config = this.hls.config;
  6848. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  6849. }
  6850. registerListeners() {
  6851. const {
  6852. hls
  6853. } = this;
  6854. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6855. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  6856. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6857. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6858. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6859. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6860. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6861. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6862. hls.on(Events.ERROR, this.onError, this);
  6863. }
  6864. unregisterListeners() {
  6865. const {
  6866. hls
  6867. } = this;
  6868. if (!hls) {
  6869. return;
  6870. }
  6871. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6872. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  6873. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6874. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6875. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6876. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6877. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6878. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6879. hls.off(Events.ERROR, this.onError, this);
  6880. }
  6881. destroy() {
  6882. this.unregisterListeners();
  6883. this.clearTimer();
  6884. // @ts-ignore
  6885. this.hls = this._abandonRulesCheck = null;
  6886. this.fragCurrent = this.partCurrent = null;
  6887. }
  6888. onManifestLoading(event, data) {
  6889. this.lastLoadedFragLevel = -1;
  6890. this.firstSelection = -1;
  6891. this.lastLevelLoadSec = 0;
  6892. this.fragCurrent = this.partCurrent = null;
  6893. this.onLevelsUpdated();
  6894. this.clearTimer();
  6895. }
  6896. onLevelsUpdated() {
  6897. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  6898. this.lastLoadedFragLevel = this.fragCurrent.level;
  6899. }
  6900. this._nextAutoLevel = -1;
  6901. this.onMaxAutoLevelUpdated();
  6902. this.codecTiers = null;
  6903. this.audioTracksByGroup = null;
  6904. }
  6905. onMaxAutoLevelUpdated() {
  6906. this.firstSelection = -1;
  6907. this.nextAutoLevelKey = '';
  6908. }
  6909. onFragLoading(event, data) {
  6910. const frag = data.frag;
  6911. if (this.ignoreFragment(frag)) {
  6912. return;
  6913. }
  6914. if (!frag.bitrateTest) {
  6915. var _data$part;
  6916. this.fragCurrent = frag;
  6917. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  6918. }
  6919. this.clearTimer();
  6920. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  6921. }
  6922. onLevelSwitching(event, data) {
  6923. this.clearTimer();
  6924. }
  6925. onError(event, data) {
  6926. if (data.fatal) {
  6927. return;
  6928. }
  6929. switch (data.details) {
  6930. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  6931. case ErrorDetails.BUFFER_APPEND_ERROR:
  6932. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  6933. this.lastLoadedFragLevel = -1;
  6934. this.firstSelection = -1;
  6935. break;
  6936. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  6937. {
  6938. const frag = data.frag;
  6939. const {
  6940. fragCurrent,
  6941. partCurrent: part
  6942. } = this;
  6943. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  6944. const now = performance.now();
  6945. const stats = part ? part.stats : frag.stats;
  6946. const timeLoading = now - stats.loading.start;
  6947. const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6948. const loadedFirstByte = stats.loaded && ttfb > -1;
  6949. if (loadedFirstByte) {
  6950. const ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6951. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6952. } else {
  6953. this.bwEstimator.sampleTTFB(timeLoading);
  6954. }
  6955. }
  6956. break;
  6957. }
  6958. }
  6959. }
  6960. getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  6961. const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  6962. const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
  6963. return fragLoadSec + playlistLoadSec;
  6964. }
  6965. onLevelLoaded(event, data) {
  6966. const config = this.hls.config;
  6967. const {
  6968. loading
  6969. } = data.stats;
  6970. const timeLoadingMs = loading.end - loading.start;
  6971. if (isFiniteNumber(timeLoadingMs)) {
  6972. this.lastLevelLoadSec = timeLoadingMs / 1000;
  6973. }
  6974. if (data.details.live) {
  6975. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  6976. } else {
  6977. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  6978. }
  6979. }
  6980. onFragLoaded(event, {
  6981. frag,
  6982. part
  6983. }) {
  6984. const stats = part ? part.stats : frag.stats;
  6985. if (frag.type === PlaylistLevelType.MAIN) {
  6986. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  6987. }
  6988. if (this.ignoreFragment(frag)) {
  6989. return;
  6990. }
  6991. // stop monitoring bw once frag loaded
  6992. this.clearTimer();
  6993. // reset forced auto level value so that next level will be selected
  6994. if (frag.level === this._nextAutoLevel) {
  6995. this._nextAutoLevel = -1;
  6996. }
  6997. this.firstSelection = -1;
  6998. // compute level average bitrate
  6999. if (this.hls.config.abrMaxWithRealBitrate) {
  7000. const duration = part ? part.duration : frag.duration;
  7001. const level = this.hls.levels[frag.level];
  7002. const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  7003. const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  7004. level.loaded = {
  7005. bytes: loadedBytes,
  7006. duration: loadedDuration
  7007. };
  7008. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  7009. }
  7010. if (frag.bitrateTest) {
  7011. const fragBufferedData = {
  7012. stats,
  7013. frag,
  7014. part,
  7015. id: frag.type
  7016. };
  7017. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  7018. frag.bitrateTest = false;
  7019. } else {
  7020. // store level id after successful fragment load for playback
  7021. this.lastLoadedFragLevel = frag.level;
  7022. }
  7023. }
  7024. onFragBuffered(event, data) {
  7025. const {
  7026. frag,
  7027. part
  7028. } = data;
  7029. const stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  7030. if (stats.aborted) {
  7031. return;
  7032. }
  7033. if (this.ignoreFragment(frag)) {
  7034. return;
  7035. }
  7036. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  7037. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  7038. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  7039. const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  7040. this.bwEstimator.sample(processingMs, stats.loaded);
  7041. stats.bwEstimate = this.getBwEstimate();
  7042. if (frag.bitrateTest) {
  7043. this.bitrateTestDelay = processingMs / 1000;
  7044. } else {
  7045. this.bitrateTestDelay = 0;
  7046. }
  7047. }
  7048. ignoreFragment(frag) {
  7049. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  7050. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  7051. }
  7052. clearTimer() {
  7053. if (this.timer > -1) {
  7054. self.clearInterval(this.timer);
  7055. this.timer = -1;
  7056. }
  7057. }
  7058. get firstAutoLevel() {
  7059. const {
  7060. maxAutoLevel,
  7061. minAutoLevel
  7062. } = this.hls;
  7063. const bwEstimate = this.getBwEstimate();
  7064. const maxStartDelay = this.hls.config.maxStarvationDelay;
  7065. const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  7066. if (abrAutoLevel > -1) {
  7067. return abrAutoLevel;
  7068. }
  7069. const firstLevel = this.hls.firstLevel;
  7070. const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  7071. logger.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);
  7072. return clamped;
  7073. }
  7074. get forcedAutoLevel() {
  7075. if (this.nextAutoLevelKey) {
  7076. return -1;
  7077. }
  7078. return this._nextAutoLevel;
  7079. }
  7080. // return next auto level
  7081. get nextAutoLevel() {
  7082. const forcedAutoLevel = this.forcedAutoLevel;
  7083. const bwEstimator = this.bwEstimator;
  7084. const useEstimate = bwEstimator.canEstimate();
  7085. const loadedFirstFrag = this.lastLoadedFragLevel > -1;
  7086. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  7087. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  7088. return forcedAutoLevel;
  7089. }
  7090. // compute next level using ABR logic
  7091. const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  7092. // use forced auto level while it hasn't errored more than ABR selection
  7093. if (forcedAutoLevel !== -1) {
  7094. const levels = this.hls.levels;
  7095. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  7096. return forcedAutoLevel;
  7097. }
  7098. }
  7099. // save result until state has changed
  7100. this._nextAutoLevel = nextABRAutoLevel;
  7101. this.nextAutoLevelKey = this.getAutoLevelKey();
  7102. return nextABRAutoLevel;
  7103. }
  7104. getAutoLevelKey() {
  7105. return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;
  7106. }
  7107. getNextABRAutoLevel() {
  7108. const {
  7109. fragCurrent,
  7110. partCurrent,
  7111. hls
  7112. } = this;
  7113. const {
  7114. maxAutoLevel,
  7115. config,
  7116. minAutoLevel
  7117. } = hls;
  7118. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  7119. const avgbw = this.getBwEstimate();
  7120. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  7121. const bufferStarvationDelay = this.getStarvationDelay();
  7122. let bwFactor = config.abrBandWidthFactor;
  7123. let bwUpFactor = config.abrBandWidthUpFactor;
  7124. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  7125. if (bufferStarvationDelay) {
  7126. const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  7127. if (_bestLevel >= 0) {
  7128. return _bestLevel;
  7129. }
  7130. }
  7131. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  7132. let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  7133. if (!bufferStarvationDelay) {
  7134. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  7135. const bitrateTestDelay = this.bitrateTestDelay;
  7136. if (bitrateTestDelay) {
  7137. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  7138. // max video loading delay used in automatic start level selection :
  7139. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  7140. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  7141. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  7142. const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  7143. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  7144. logger.info(`[abr] bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);
  7145. // don't use conservative factor on bitrate test
  7146. bwFactor = bwUpFactor = 1;
  7147. }
  7148. }
  7149. const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  7150. logger.info(`[abr] ${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);
  7151. if (bestLevel > -1) {
  7152. return bestLevel;
  7153. }
  7154. // If no matching level found, see if min auto level would be a better option
  7155. const minLevel = hls.levels[minAutoLevel];
  7156. const autoLevel = hls.levels[hls.loadLevel];
  7157. if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) {
  7158. return minAutoLevel;
  7159. }
  7160. // or if bitrate is not lower, continue to use loadLevel
  7161. return hls.loadLevel;
  7162. }
  7163. getStarvationDelay() {
  7164. const hls = this.hls;
  7165. const media = hls.media;
  7166. if (!media) {
  7167. return Infinity;
  7168. }
  7169. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  7170. // if we're playing back at the normal rate.
  7171. const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  7172. const bufferInfo = hls.mainForwardBufferInfo;
  7173. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  7174. }
  7175. getBwEstimate() {
  7176. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  7177. }
  7178. findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  7179. var _level$details;
  7180. const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  7181. const lastLoadedFragLevel = this.lastLoadedFragLevel;
  7182. const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  7183. const {
  7184. fragCurrent,
  7185. partCurrent
  7186. } = this;
  7187. const {
  7188. levels,
  7189. allAudioTracks,
  7190. loadLevel,
  7191. config
  7192. } = this.hls;
  7193. if (levels.length === 1) {
  7194. return 0;
  7195. }
  7196. const level = levels[selectionBaseLevel];
  7197. const live = !!(level != null && (_level$details = level.details) != null && _level$details.live);
  7198. const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  7199. let currentCodecSet;
  7200. let currentVideoRange = 'SDR';
  7201. let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  7202. const {
  7203. audioPreference,
  7204. videoPreference
  7205. } = config;
  7206. const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  7207. if (firstSelection) {
  7208. if (this.firstSelection !== -1) {
  7209. return this.firstSelection;
  7210. }
  7211. const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  7212. const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  7213. const {
  7214. codecSet,
  7215. videoRanges,
  7216. minFramerate,
  7217. minBitrate,
  7218. preferHDR
  7219. } = startTier;
  7220. currentCodecSet = codecSet;
  7221. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  7222. currentFrameRate = minFramerate;
  7223. currentBw = Math.max(currentBw, minBitrate);
  7224. logger.log(`[abr] picked start tier ${JSON.stringify(startTier)}`);
  7225. } else {
  7226. currentCodecSet = level == null ? void 0 : level.codecSet;
  7227. currentVideoRange = level == null ? void 0 : level.videoRange;
  7228. }
  7229. const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  7230. const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  7231. const levelsSkipped = [];
  7232. for (let i = maxAutoLevel; i >= minAutoLevel; i--) {
  7233. var _levelInfo$supportedR;
  7234. const levelInfo = levels[i];
  7235. const upSwitch = i > selectionBaseLevel;
  7236. if (!levelInfo) {
  7237. continue;
  7238. }
  7239. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  7240. const mediaCapabilities = navigator.mediaCapabilities;
  7241. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === 'function' && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  7242. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities);
  7243. levelInfo.supportedPromise.then(decodingInfo => {
  7244. if (!this.hls) {
  7245. return;
  7246. }
  7247. levelInfo.supportedResult = decodingInfo;
  7248. const levels = this.hls.levels;
  7249. const index = levels.indexOf(levelInfo);
  7250. if (decodingInfo.error) {
  7251. logger.warn(`[abr] MediaCapabilities decodingInfo error: "${decodingInfo.error}" for level ${index} ${JSON.stringify(decodingInfo)}`);
  7252. } else if (!decodingInfo.supported) {
  7253. logger.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${index} ${JSON.stringify(decodingInfo)}`);
  7254. if (index > -1 && levels.length > 1) {
  7255. logger.log(`[abr] Removing unsupported level ${index}`);
  7256. this.hls.removeLevel(index);
  7257. }
  7258. }
  7259. });
  7260. } else {
  7261. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  7262. }
  7263. }
  7264. // skip candidates which change codec-family or video-range,
  7265. // and which decrease or increase frame-rate for up and down-switch respectfully
  7266. 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)) {
  7267. levelsSkipped.push(i);
  7268. continue;
  7269. }
  7270. const levelDetails = levelInfo.details;
  7271. const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  7272. let adjustedbw;
  7273. // follow algorithm captured from stagefright :
  7274. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  7275. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  7276. // consider only 80% of the available bandwidth, but if we are switching up,
  7277. // be even more conservative (70%) to avoid overestimating and immediately
  7278. // switching back.
  7279. if (!upSwitch) {
  7280. adjustedbw = bwFactor * currentBw;
  7281. } else {
  7282. adjustedbw = bwUpFactor * currentBw;
  7283. }
  7284. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  7285. const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i].averageBitrate : levels[i].maxBitrate;
  7286. const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  7287. const canSwitchWithinTolerance =
  7288. // if adjusted bw is greater than level bitrate AND
  7289. adjustedbw >= bitrate && (
  7290. // no level change, or new level has no error history
  7291. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  7292. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  7293. // 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 ...
  7294. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  7295. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);
  7296. if (canSwitchWithinTolerance) {
  7297. const forcedAutoLevel = this.forcedAutoLevel;
  7298. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  7299. if (levelsSkipped.length) {
  7300. 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}`);
  7301. }
  7302. 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}`);
  7303. }
  7304. if (firstSelection) {
  7305. this.firstSelection = i;
  7306. }
  7307. // as we are looping from highest to lowest, this will return the best achievable quality level
  7308. return i;
  7309. }
  7310. }
  7311. // not enough time budget even with quality level 0 ... rebuffering might happen
  7312. return -1;
  7313. }
  7314. set nextAutoLevel(nextLevel) {
  7315. const {
  7316. maxAutoLevel,
  7317. minAutoLevel
  7318. } = this.hls;
  7319. const value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  7320. if (this._nextAutoLevel !== value) {
  7321. this.nextAutoLevelKey = '';
  7322. this._nextAutoLevel = value;
  7323. }
  7324. }
  7325. }
  7326. /**
  7327. * @ignore
  7328. * Sub-class specialization of EventHandler base class.
  7329. *
  7330. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  7331. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  7332. *
  7333. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  7334. * using the `tick` method.
  7335. *
  7336. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  7337. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  7338. *
  7339. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  7340. * and cancelled with `clearNextTick`.
  7341. *
  7342. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  7343. *
  7344. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  7345. *
  7346. * Further explanations:
  7347. *
  7348. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  7349. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  7350. *
  7351. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  7352. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  7353. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  7354. */
  7355. class TaskLoop {
  7356. constructor() {
  7357. this._boundTick = void 0;
  7358. this._tickTimer = null;
  7359. this._tickInterval = null;
  7360. this._tickCallCount = 0;
  7361. this._boundTick = this.tick.bind(this);
  7362. }
  7363. destroy() {
  7364. this.onHandlerDestroying();
  7365. this.onHandlerDestroyed();
  7366. }
  7367. onHandlerDestroying() {
  7368. // clear all timers before unregistering from event bus
  7369. this.clearNextTick();
  7370. this.clearInterval();
  7371. }
  7372. onHandlerDestroyed() {}
  7373. hasInterval() {
  7374. return !!this._tickInterval;
  7375. }
  7376. hasNextTick() {
  7377. return !!this._tickTimer;
  7378. }
  7379. /**
  7380. * @param millis - Interval time (ms)
  7381. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  7382. */
  7383. setInterval(millis) {
  7384. if (!this._tickInterval) {
  7385. this._tickCallCount = 0;
  7386. this._tickInterval = self.setInterval(this._boundTick, millis);
  7387. return true;
  7388. }
  7389. return false;
  7390. }
  7391. /**
  7392. * @returns True when interval was cleared, false when none was set (no effect)
  7393. */
  7394. clearInterval() {
  7395. if (this._tickInterval) {
  7396. self.clearInterval(this._tickInterval);
  7397. this._tickInterval = null;
  7398. return true;
  7399. }
  7400. return false;
  7401. }
  7402. /**
  7403. * @returns True when timeout was cleared, false when none was set (no effect)
  7404. */
  7405. clearNextTick() {
  7406. if (this._tickTimer) {
  7407. self.clearTimeout(this._tickTimer);
  7408. this._tickTimer = null;
  7409. return true;
  7410. }
  7411. return false;
  7412. }
  7413. /**
  7414. * Will call the subclass doTick implementation in this main loop tick
  7415. * or in the next one (via setTimeout(,0)) in case it has already been called
  7416. * in this tick (in case this is a re-entrant call).
  7417. */
  7418. tick() {
  7419. this._tickCallCount++;
  7420. if (this._tickCallCount === 1) {
  7421. this.doTick();
  7422. // re-entrant call to tick from previous doTick call stack
  7423. // -> schedule a call on the next main loop iteration to process this task processing request
  7424. if (this._tickCallCount > 1) {
  7425. // make sure only one timer exists at any time at max
  7426. this.tickImmediate();
  7427. }
  7428. this._tickCallCount = 0;
  7429. }
  7430. }
  7431. tickImmediate() {
  7432. this.clearNextTick();
  7433. this._tickTimer = self.setTimeout(this._boundTick, 0);
  7434. }
  7435. /**
  7436. * For subclass to implement task logic
  7437. * @abstract
  7438. */
  7439. doTick() {}
  7440. }
  7441. var FragmentState = {
  7442. NOT_LOADED: "NOT_LOADED",
  7443. APPENDING: "APPENDING",
  7444. PARTIAL: "PARTIAL",
  7445. OK: "OK"
  7446. };
  7447. class FragmentTracker {
  7448. constructor(hls) {
  7449. this.activePartLists = Object.create(null);
  7450. this.endListFragments = Object.create(null);
  7451. this.fragments = Object.create(null);
  7452. this.timeRanges = Object.create(null);
  7453. this.bufferPadding = 0.2;
  7454. this.hls = void 0;
  7455. this.hasGaps = false;
  7456. this.hls = hls;
  7457. this._registerListeners();
  7458. }
  7459. _registerListeners() {
  7460. const {
  7461. hls
  7462. } = this;
  7463. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  7464. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  7465. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  7466. }
  7467. _unregisterListeners() {
  7468. const {
  7469. hls
  7470. } = this;
  7471. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  7472. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  7473. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  7474. }
  7475. destroy() {
  7476. this._unregisterListeners();
  7477. // @ts-ignore
  7478. this.fragments =
  7479. // @ts-ignore
  7480. this.activePartLists =
  7481. // @ts-ignore
  7482. this.endListFragments = this.timeRanges = null;
  7483. }
  7484. /**
  7485. * Return a Fragment or Part with an appended range that matches the position and levelType
  7486. * Otherwise, return null
  7487. */
  7488. getAppendedFrag(position, levelType) {
  7489. const activeParts = this.activePartLists[levelType];
  7490. if (activeParts) {
  7491. for (let i = activeParts.length; i--;) {
  7492. const activePart = activeParts[i];
  7493. if (!activePart) {
  7494. break;
  7495. }
  7496. const appendedPTS = activePart.end;
  7497. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  7498. return activePart;
  7499. }
  7500. }
  7501. }
  7502. return this.getBufferedFrag(position, levelType);
  7503. }
  7504. /**
  7505. * Return a buffered Fragment that matches the position and levelType.
  7506. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  7507. * If not found any Fragment, return null
  7508. */
  7509. getBufferedFrag(position, levelType) {
  7510. const {
  7511. fragments
  7512. } = this;
  7513. const keys = Object.keys(fragments);
  7514. for (let i = keys.length; i--;) {
  7515. const fragmentEntity = fragments[keys[i]];
  7516. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  7517. const frag = fragmentEntity.body;
  7518. if (frag.start <= position && position <= frag.end) {
  7519. return frag;
  7520. }
  7521. }
  7522. }
  7523. return null;
  7524. }
  7525. /**
  7526. * Partial fragments effected by coded frame eviction will be removed
  7527. * The browser will unload parts of the buffer to free up memory for new buffer data
  7528. * 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)
  7529. */
  7530. detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) {
  7531. if (this.timeRanges) {
  7532. this.timeRanges[elementaryStream] = timeRange;
  7533. }
  7534. // Check if any flagged fragments have been unloaded
  7535. // excluding anything newer than appendedPartSn
  7536. const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  7537. Object.keys(this.fragments).forEach(key => {
  7538. const fragmentEntity = this.fragments[key];
  7539. if (!fragmentEntity) {
  7540. return;
  7541. }
  7542. if (appendedPartSn >= fragmentEntity.body.sn) {
  7543. return;
  7544. }
  7545. if (!fragmentEntity.buffered && !fragmentEntity.loaded) {
  7546. if (fragmentEntity.body.type === playlistType) {
  7547. this.removeFragment(fragmentEntity.body);
  7548. }
  7549. return;
  7550. }
  7551. const esData = fragmentEntity.range[elementaryStream];
  7552. if (!esData) {
  7553. return;
  7554. }
  7555. esData.time.some(time => {
  7556. const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  7557. if (isNotBuffered) {
  7558. // Unregister partial fragment as it needs to load again to be reused
  7559. this.removeFragment(fragmentEntity.body);
  7560. }
  7561. return isNotBuffered;
  7562. });
  7563. });
  7564. }
  7565. /**
  7566. * Checks if the fragment passed in is loaded in the buffer properly
  7567. * Partially loaded fragments will be registered as a partial fragment
  7568. */
  7569. detectPartialFragments(data) {
  7570. const timeRanges = this.timeRanges;
  7571. const {
  7572. frag,
  7573. part
  7574. } = data;
  7575. if (!timeRanges || frag.sn === 'initSegment') {
  7576. return;
  7577. }
  7578. const fragKey = getFragmentKey(frag);
  7579. const fragmentEntity = this.fragments[fragKey];
  7580. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  7581. return;
  7582. }
  7583. const isFragHint = !frag.relurl;
  7584. Object.keys(timeRanges).forEach(elementaryStream => {
  7585. const streamInfo = frag.elementaryStreams[elementaryStream];
  7586. if (!streamInfo) {
  7587. return;
  7588. }
  7589. const timeRange = timeRanges[elementaryStream];
  7590. const partial = isFragHint || streamInfo.partial === true;
  7591. fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, part, partial, timeRange);
  7592. });
  7593. fragmentEntity.loaded = null;
  7594. if (Object.keys(fragmentEntity.range).length) {
  7595. fragmentEntity.buffered = true;
  7596. const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  7597. if (endList) {
  7598. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  7599. }
  7600. if (!isPartial(fragmentEntity)) {
  7601. // Remove older fragment parts from lookup after frag is tracked as buffered
  7602. this.removeParts(frag.sn - 1, frag.type);
  7603. }
  7604. } else {
  7605. // remove fragment if nothing was appended
  7606. this.removeFragment(fragmentEntity.body);
  7607. }
  7608. }
  7609. removeParts(snToKeep, levelType) {
  7610. const activeParts = this.activePartLists[levelType];
  7611. if (!activeParts) {
  7612. return;
  7613. }
  7614. this.activePartLists[levelType] = activeParts.filter(part => part.fragment.sn >= snToKeep);
  7615. }
  7616. fragBuffered(frag, force) {
  7617. const fragKey = getFragmentKey(frag);
  7618. let fragmentEntity = this.fragments[fragKey];
  7619. if (!fragmentEntity && force) {
  7620. fragmentEntity = this.fragments[fragKey] = {
  7621. body: frag,
  7622. appendedPTS: null,
  7623. loaded: null,
  7624. buffered: false,
  7625. range: Object.create(null)
  7626. };
  7627. if (frag.gap) {
  7628. this.hasGaps = true;
  7629. }
  7630. }
  7631. if (fragmentEntity) {
  7632. fragmentEntity.loaded = null;
  7633. fragmentEntity.buffered = true;
  7634. }
  7635. }
  7636. getBufferedTimes(fragment, part, partial, timeRange) {
  7637. const buffered = {
  7638. time: [],
  7639. partial
  7640. };
  7641. const startPTS = fragment.start;
  7642. const endPTS = fragment.end;
  7643. const minEndPTS = fragment.minEndPTS || endPTS;
  7644. const maxStartPTS = fragment.maxStartPTS || startPTS;
  7645. for (let i = 0; i < timeRange.length; i++) {
  7646. const startTime = timeRange.start(i) - this.bufferPadding;
  7647. const endTime = timeRange.end(i) + this.bufferPadding;
  7648. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  7649. // Fragment is entirely contained in buffer
  7650. // No need to check the other timeRange times since it's completely playable
  7651. buffered.time.push({
  7652. startPTS: Math.max(startPTS, timeRange.start(i)),
  7653. endPTS: Math.min(endPTS, timeRange.end(i))
  7654. });
  7655. break;
  7656. } else if (startPTS < endTime && endPTS > startTime) {
  7657. const start = Math.max(startPTS, timeRange.start(i));
  7658. const end = Math.min(endPTS, timeRange.end(i));
  7659. if (end > start) {
  7660. buffered.partial = true;
  7661. // Check for intersection with buffer
  7662. // Get playable sections of the fragment
  7663. buffered.time.push({
  7664. startPTS: start,
  7665. endPTS: end
  7666. });
  7667. }
  7668. } else if (endPTS <= startTime) {
  7669. // No need to check the rest of the timeRange as it is in order
  7670. break;
  7671. }
  7672. }
  7673. return buffered;
  7674. }
  7675. /**
  7676. * Gets the partial fragment for a certain time
  7677. */
  7678. getPartialFragment(time) {
  7679. let bestFragment = null;
  7680. let timePadding;
  7681. let startTime;
  7682. let endTime;
  7683. let bestOverlap = 0;
  7684. const {
  7685. bufferPadding,
  7686. fragments
  7687. } = this;
  7688. Object.keys(fragments).forEach(key => {
  7689. const fragmentEntity = fragments[key];
  7690. if (!fragmentEntity) {
  7691. return;
  7692. }
  7693. if (isPartial(fragmentEntity)) {
  7694. startTime = fragmentEntity.body.start - bufferPadding;
  7695. endTime = fragmentEntity.body.end + bufferPadding;
  7696. if (time >= startTime && time <= endTime) {
  7697. // Use the fragment that has the most padding from start and end time
  7698. timePadding = Math.min(time - startTime, endTime - time);
  7699. if (bestOverlap <= timePadding) {
  7700. bestFragment = fragmentEntity.body;
  7701. bestOverlap = timePadding;
  7702. }
  7703. }
  7704. }
  7705. });
  7706. return bestFragment;
  7707. }
  7708. isEndListAppended(type) {
  7709. const lastFragmentEntity = this.endListFragments[type];
  7710. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  7711. }
  7712. getState(fragment) {
  7713. const fragKey = getFragmentKey(fragment);
  7714. const fragmentEntity = this.fragments[fragKey];
  7715. if (fragmentEntity) {
  7716. if (!fragmentEntity.buffered) {
  7717. return FragmentState.APPENDING;
  7718. } else if (isPartial(fragmentEntity)) {
  7719. return FragmentState.PARTIAL;
  7720. } else {
  7721. return FragmentState.OK;
  7722. }
  7723. }
  7724. return FragmentState.NOT_LOADED;
  7725. }
  7726. isTimeBuffered(startPTS, endPTS, timeRange) {
  7727. let startTime;
  7728. let endTime;
  7729. for (let i = 0; i < timeRange.length; i++) {
  7730. startTime = timeRange.start(i) - this.bufferPadding;
  7731. endTime = timeRange.end(i) + this.bufferPadding;
  7732. if (startPTS >= startTime && endPTS <= endTime) {
  7733. return true;
  7734. }
  7735. if (endPTS <= startTime) {
  7736. // No need to check the rest of the timeRange as it is in order
  7737. return false;
  7738. }
  7739. }
  7740. return false;
  7741. }
  7742. onFragLoaded(event, data) {
  7743. const {
  7744. frag,
  7745. part
  7746. } = data;
  7747. // don't track initsegment (for which sn is not a number)
  7748. // don't track frags used for bitrateTest, they're irrelevant.
  7749. if (frag.sn === 'initSegment' || frag.bitrateTest) {
  7750. return;
  7751. }
  7752. // Fragment entity `loaded` FragLoadedData is null when loading parts
  7753. const loaded = part ? null : data;
  7754. const fragKey = getFragmentKey(frag);
  7755. this.fragments[fragKey] = {
  7756. body: frag,
  7757. appendedPTS: null,
  7758. loaded,
  7759. buffered: false,
  7760. range: Object.create(null)
  7761. };
  7762. }
  7763. onBufferAppended(event, data) {
  7764. const {
  7765. frag,
  7766. part,
  7767. timeRanges
  7768. } = data;
  7769. if (frag.sn === 'initSegment') {
  7770. return;
  7771. }
  7772. const playlistType = frag.type;
  7773. if (part) {
  7774. let activeParts = this.activePartLists[playlistType];
  7775. if (!activeParts) {
  7776. this.activePartLists[playlistType] = activeParts = [];
  7777. }
  7778. activeParts.push(part);
  7779. }
  7780. // Store the latest timeRanges loaded in the buffer
  7781. this.timeRanges = timeRanges;
  7782. Object.keys(timeRanges).forEach(elementaryStream => {
  7783. const timeRange = timeRanges[elementaryStream];
  7784. this.detectEvictedFragments(elementaryStream, timeRange, playlistType, part);
  7785. });
  7786. }
  7787. onFragBuffered(event, data) {
  7788. this.detectPartialFragments(data);
  7789. }
  7790. hasFragment(fragment) {
  7791. const fragKey = getFragmentKey(fragment);
  7792. return !!this.fragments[fragKey];
  7793. }
  7794. hasParts(type) {
  7795. var _this$activePartLists;
  7796. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  7797. }
  7798. removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  7799. if (withGapOnly && !this.hasGaps) {
  7800. return;
  7801. }
  7802. Object.keys(this.fragments).forEach(key => {
  7803. const fragmentEntity = this.fragments[key];
  7804. if (!fragmentEntity) {
  7805. return;
  7806. }
  7807. const frag = fragmentEntity.body;
  7808. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  7809. return;
  7810. }
  7811. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  7812. this.removeFragment(frag);
  7813. }
  7814. });
  7815. }
  7816. removeFragment(fragment) {
  7817. const fragKey = getFragmentKey(fragment);
  7818. fragment.stats.loaded = 0;
  7819. fragment.clearElementaryStreamInfo();
  7820. const activeParts = this.activePartLists[fragment.type];
  7821. if (activeParts) {
  7822. const snToRemove = fragment.sn;
  7823. this.activePartLists[fragment.type] = activeParts.filter(part => part.fragment.sn !== snToRemove);
  7824. }
  7825. delete this.fragments[fragKey];
  7826. if (fragment.endList) {
  7827. delete this.endListFragments[fragment.type];
  7828. }
  7829. }
  7830. removeAllFragments() {
  7831. this.fragments = Object.create(null);
  7832. this.endListFragments = Object.create(null);
  7833. this.activePartLists = Object.create(null);
  7834. this.hasGaps = false;
  7835. }
  7836. }
  7837. function isPartial(fragmentEntity) {
  7838. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  7839. 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));
  7840. }
  7841. function getFragmentKey(fragment) {
  7842. return `${fragment.type}_${fragment.level}_${fragment.sn}`;
  7843. }
  7844. /**
  7845. * Provides methods dealing with buffer length retrieval for example.
  7846. *
  7847. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  7848. *
  7849. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  7850. */
  7851. const noopBuffered = {
  7852. length: 0,
  7853. start: () => 0,
  7854. end: () => 0
  7855. };
  7856. class BufferHelper {
  7857. /**
  7858. * Return true if `media`'s buffered include `position`
  7859. */
  7860. static isBuffered(media, position) {
  7861. try {
  7862. if (media) {
  7863. const buffered = BufferHelper.getBuffered(media);
  7864. for (let i = 0; i < buffered.length; i++) {
  7865. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  7866. return true;
  7867. }
  7868. }
  7869. }
  7870. } catch (error) {
  7871. // this is to catch
  7872. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7873. // This SourceBuffer has been removed from the parent media source
  7874. }
  7875. return false;
  7876. }
  7877. static bufferInfo(media, pos, maxHoleDuration) {
  7878. try {
  7879. if (media) {
  7880. const vbuffered = BufferHelper.getBuffered(media);
  7881. const buffered = [];
  7882. let i;
  7883. for (i = 0; i < vbuffered.length; i++) {
  7884. buffered.push({
  7885. start: vbuffered.start(i),
  7886. end: vbuffered.end(i)
  7887. });
  7888. }
  7889. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  7890. }
  7891. } catch (error) {
  7892. // this is to catch
  7893. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7894. // This SourceBuffer has been removed from the parent media source
  7895. }
  7896. return {
  7897. len: 0,
  7898. start: pos,
  7899. end: pos,
  7900. nextStart: undefined
  7901. };
  7902. }
  7903. static bufferedInfo(buffered, pos, maxHoleDuration) {
  7904. pos = Math.max(0, pos);
  7905. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  7906. buffered.sort(function (a, b) {
  7907. const diff = a.start - b.start;
  7908. if (diff) {
  7909. return diff;
  7910. } else {
  7911. return b.end - a.end;
  7912. }
  7913. });
  7914. let buffered2 = [];
  7915. if (maxHoleDuration) {
  7916. // there might be some small holes between buffer time range
  7917. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  7918. // buffer time range representations that discards those holes
  7919. for (let i = 0; i < buffered.length; i++) {
  7920. const buf2len = buffered2.length;
  7921. if (buf2len) {
  7922. const buf2end = buffered2[buf2len - 1].end;
  7923. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  7924. if (buffered[i].start - buf2end < maxHoleDuration) {
  7925. // merge overlapping time ranges
  7926. // update lastRange.end only if smaller than item.end
  7927. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  7928. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  7929. if (buffered[i].end > buf2end) {
  7930. buffered2[buf2len - 1].end = buffered[i].end;
  7931. }
  7932. } else {
  7933. // big hole
  7934. buffered2.push(buffered[i]);
  7935. }
  7936. } else {
  7937. // first value
  7938. buffered2.push(buffered[i]);
  7939. }
  7940. }
  7941. } else {
  7942. buffered2 = buffered;
  7943. }
  7944. let bufferLen = 0;
  7945. // bufferStartNext can possibly be undefined based on the conditional logic below
  7946. let bufferStartNext;
  7947. // bufferStart and bufferEnd are buffer boundaries around current video position
  7948. let bufferStart = pos;
  7949. let bufferEnd = pos;
  7950. for (let i = 0; i < buffered2.length; i++) {
  7951. const start = buffered2[i].start;
  7952. const end = buffered2[i].end;
  7953. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  7954. if (pos + maxHoleDuration >= start && pos < end) {
  7955. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7956. bufferStart = start;
  7957. bufferEnd = end;
  7958. bufferLen = bufferEnd - pos;
  7959. } else if (pos + maxHoleDuration < start) {
  7960. bufferStartNext = start;
  7961. break;
  7962. }
  7963. }
  7964. return {
  7965. len: bufferLen,
  7966. start: bufferStart || 0,
  7967. end: bufferEnd || 0,
  7968. nextStart: bufferStartNext
  7969. };
  7970. }
  7971. /**
  7972. * Safe method to get buffered property.
  7973. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  7974. */
  7975. static getBuffered(media) {
  7976. try {
  7977. return media.buffered;
  7978. } catch (e) {
  7979. logger.log('failed to get media.buffered', e);
  7980. return noopBuffered;
  7981. }
  7982. }
  7983. }
  7984. class ChunkMetadata {
  7985. constructor(level, sn, id, size = 0, part = -1, partial = false) {
  7986. this.level = void 0;
  7987. this.sn = void 0;
  7988. this.part = void 0;
  7989. this.id = void 0;
  7990. this.size = void 0;
  7991. this.partial = void 0;
  7992. this.transmuxing = getNewPerformanceTiming();
  7993. this.buffering = {
  7994. audio: getNewPerformanceTiming(),
  7995. video: getNewPerformanceTiming(),
  7996. audiovideo: getNewPerformanceTiming()
  7997. };
  7998. this.level = level;
  7999. this.sn = sn;
  8000. this.id = id;
  8001. this.size = size;
  8002. this.part = part;
  8003. this.partial = partial;
  8004. }
  8005. }
  8006. function getNewPerformanceTiming() {
  8007. return {
  8008. start: 0,
  8009. executeStart: 0,
  8010. executeEnd: 0,
  8011. end: 0
  8012. };
  8013. }
  8014. function findFirstFragWithCC(fragments, cc) {
  8015. for (let i = 0, len = fragments.length; i < len; i++) {
  8016. var _fragments$i;
  8017. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  8018. return fragments[i];
  8019. }
  8020. }
  8021. return null;
  8022. }
  8023. function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) {
  8024. if (switchDetails) {
  8025. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  8026. return true;
  8027. }
  8028. }
  8029. return false;
  8030. }
  8031. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  8032. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  8033. const prevFrags = prevDetails.fragments;
  8034. const curFrags = curDetails.fragments;
  8035. if (!curFrags.length || !prevFrags.length) {
  8036. logger.log('No fragments to align');
  8037. return;
  8038. }
  8039. const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  8040. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  8041. logger.log('No frag in previous level to align on');
  8042. return;
  8043. }
  8044. return prevStartFrag;
  8045. }
  8046. function adjustFragmentStart(frag, sliding) {
  8047. if (frag) {
  8048. const start = frag.start + sliding;
  8049. frag.start = frag.startPTS = start;
  8050. frag.endPTS = start + frag.duration;
  8051. }
  8052. }
  8053. function adjustSlidingStart(sliding, details) {
  8054. // Update segments
  8055. const fragments = details.fragments;
  8056. for (let i = 0, len = fragments.length; i < len; i++) {
  8057. adjustFragmentStart(fragments[i], sliding);
  8058. }
  8059. // Update LL-HLS parts at the end of the playlist
  8060. if (details.fragmentHint) {
  8061. adjustFragmentStart(details.fragmentHint, sliding);
  8062. }
  8063. details.alignedSliding = true;
  8064. }
  8065. /**
  8066. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  8067. * contiguous stream with the last fragments.
  8068. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  8069. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  8070. * and an extra download.
  8071. * @param lastFrag
  8072. * @param lastLevel
  8073. * @param details
  8074. */
  8075. function alignStream(lastFrag, switchDetails, details) {
  8076. if (!switchDetails) {
  8077. return;
  8078. }
  8079. alignDiscontinuities(lastFrag, details, switchDetails);
  8080. if (!details.alignedSliding && switchDetails) {
  8081. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  8082. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  8083. // discontinuity sequence.
  8084. alignMediaPlaylistByPDT(details, switchDetails);
  8085. }
  8086. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  8087. // Try to align on sn so that we pick a better start fragment.
  8088. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  8089. // and adjustSliding only adjusts fragments after skippedSegments.
  8090. adjustSliding(switchDetails, details);
  8091. }
  8092. }
  8093. /**
  8094. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  8095. * discontinuity sequence.
  8096. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  8097. * @param lastLevel - The details of the last loaded level
  8098. * @param details - The details of the new level
  8099. */
  8100. function alignDiscontinuities(lastFrag, details, switchDetails) {
  8101. if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {
  8102. const referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details);
  8103. if (referenceFrag && isFiniteNumber(referenceFrag.start)) {
  8104. logger.log(`Adjusting PTS using last level due to CC increase within current level ${details.url}`);
  8105. adjustSlidingStart(referenceFrag.start, details);
  8106. }
  8107. }
  8108. }
  8109. /**
  8110. * Ensures appropriate time-alignment between renditions based on PDT.
  8111. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  8112. * for the last discontinuity sequence number shared by both playlists when present,
  8113. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  8114. * times/timelines of `details` accordingly.
  8115. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  8116. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  8117. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  8118. * be consistent across playlists, per the HLS spec.
  8119. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  8120. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  8121. */
  8122. function alignMediaPlaylistByPDT(details, refDetails) {
  8123. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  8124. return;
  8125. }
  8126. const fragments = details.fragments;
  8127. const refFragments = refDetails.fragments;
  8128. if (!fragments.length || !refFragments.length) {
  8129. return;
  8130. }
  8131. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  8132. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  8133. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  8134. let refFrag;
  8135. let frag;
  8136. const targetCC = Math.min(refDetails.endCC, details.endCC);
  8137. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  8138. refFrag = findFirstFragWithCC(refFragments, targetCC);
  8139. frag = findFirstFragWithCC(fragments, targetCC);
  8140. }
  8141. if (!refFrag || !frag) {
  8142. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  8143. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  8144. }
  8145. const refPDT = refFrag.programDateTime;
  8146. const targetPDT = frag.programDateTime;
  8147. if (!refPDT || !targetPDT) {
  8148. return;
  8149. }
  8150. const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  8151. adjustSlidingStart(delta, details);
  8152. }
  8153. const MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  8154. class FragmentLoader {
  8155. constructor(config) {
  8156. this.config = void 0;
  8157. this.loader = null;
  8158. this.partLoadTimeout = -1;
  8159. this.config = config;
  8160. }
  8161. destroy() {
  8162. if (this.loader) {
  8163. this.loader.destroy();
  8164. this.loader = null;
  8165. }
  8166. }
  8167. abort() {
  8168. if (this.loader) {
  8169. // Abort the loader for current fragment. Only one may load at any given time
  8170. this.loader.abort();
  8171. }
  8172. }
  8173. load(frag, onProgress) {
  8174. const url = frag.url;
  8175. if (!url) {
  8176. return Promise.reject(new LoadError({
  8177. type: ErrorTypes.NETWORK_ERROR,
  8178. details: ErrorDetails.FRAG_LOAD_ERROR,
  8179. fatal: false,
  8180. frag,
  8181. error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),
  8182. networkDetails: null
  8183. }));
  8184. }
  8185. this.abort();
  8186. const config = this.config;
  8187. const FragmentILoader = config.fLoader;
  8188. const DefaultILoader = config.loader;
  8189. return new Promise((resolve, reject) => {
  8190. if (this.loader) {
  8191. this.loader.destroy();
  8192. }
  8193. if (frag.gap) {
  8194. if (frag.tagList.some(tags => tags[0] === 'GAP')) {
  8195. reject(createGapLoadError(frag));
  8196. return;
  8197. } else {
  8198. // Reset temporary treatment as GAP tag
  8199. frag.gap = false;
  8200. }
  8201. }
  8202. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  8203. const loaderContext = createLoaderContext(frag);
  8204. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  8205. const loaderConfig = {
  8206. loadPolicy,
  8207. timeout: loadPolicy.maxLoadTimeMs,
  8208. maxRetry: 0,
  8209. retryDelay: 0,
  8210. maxRetryDelay: 0,
  8211. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  8212. };
  8213. // Assign frag stats to the loader's stats reference
  8214. frag.stats = loader.stats;
  8215. loader.load(loaderContext, loaderConfig, {
  8216. onSuccess: (response, stats, context, networkDetails) => {
  8217. this.resetLoader(frag, loader);
  8218. let payload = response.data;
  8219. if (context.resetIV && frag.decryptdata) {
  8220. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  8221. payload = payload.slice(16);
  8222. }
  8223. resolve({
  8224. frag,
  8225. part: null,
  8226. payload,
  8227. networkDetails
  8228. });
  8229. },
  8230. onError: (response, context, networkDetails, stats) => {
  8231. this.resetLoader(frag, loader);
  8232. reject(new LoadError({
  8233. type: ErrorTypes.NETWORK_ERROR,
  8234. details: ErrorDetails.FRAG_LOAD_ERROR,
  8235. fatal: false,
  8236. frag,
  8237. response: _objectSpread2({
  8238. url,
  8239. data: undefined
  8240. }, response),
  8241. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  8242. networkDetails,
  8243. stats
  8244. }));
  8245. },
  8246. onAbort: (stats, context, networkDetails) => {
  8247. this.resetLoader(frag, loader);
  8248. reject(new LoadError({
  8249. type: ErrorTypes.NETWORK_ERROR,
  8250. details: ErrorDetails.INTERNAL_ABORTED,
  8251. fatal: false,
  8252. frag,
  8253. error: new Error('Aborted'),
  8254. networkDetails,
  8255. stats
  8256. }));
  8257. },
  8258. onTimeout: (stats, context, networkDetails) => {
  8259. this.resetLoader(frag, loader);
  8260. reject(new LoadError({
  8261. type: ErrorTypes.NETWORK_ERROR,
  8262. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  8263. fatal: false,
  8264. frag,
  8265. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  8266. networkDetails,
  8267. stats
  8268. }));
  8269. },
  8270. onProgress: (stats, context, data, networkDetails) => {
  8271. if (onProgress) {
  8272. onProgress({
  8273. frag,
  8274. part: null,
  8275. payload: data,
  8276. networkDetails
  8277. });
  8278. }
  8279. }
  8280. });
  8281. });
  8282. }
  8283. loadPart(frag, part, onProgress) {
  8284. this.abort();
  8285. const config = this.config;
  8286. const FragmentILoader = config.fLoader;
  8287. const DefaultILoader = config.loader;
  8288. return new Promise((resolve, reject) => {
  8289. if (this.loader) {
  8290. this.loader.destroy();
  8291. }
  8292. if (frag.gap || part.gap) {
  8293. reject(createGapLoadError(frag, part));
  8294. return;
  8295. }
  8296. const loader = this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  8297. const loaderContext = createLoaderContext(frag, part);
  8298. // Should we define another load policy for parts?
  8299. const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  8300. const loaderConfig = {
  8301. loadPolicy,
  8302. timeout: loadPolicy.maxLoadTimeMs,
  8303. maxRetry: 0,
  8304. retryDelay: 0,
  8305. maxRetryDelay: 0,
  8306. highWaterMark: MIN_CHUNK_SIZE
  8307. };
  8308. // Assign part stats to the loader's stats reference
  8309. part.stats = loader.stats;
  8310. loader.load(loaderContext, loaderConfig, {
  8311. onSuccess: (response, stats, context, networkDetails) => {
  8312. this.resetLoader(frag, loader);
  8313. this.updateStatsFromPart(frag, part);
  8314. const partLoadedData = {
  8315. frag,
  8316. part,
  8317. payload: response.data,
  8318. networkDetails
  8319. };
  8320. onProgress(partLoadedData);
  8321. resolve(partLoadedData);
  8322. },
  8323. onError: (response, context, networkDetails, stats) => {
  8324. this.resetLoader(frag, loader);
  8325. reject(new LoadError({
  8326. type: ErrorTypes.NETWORK_ERROR,
  8327. details: ErrorDetails.FRAG_LOAD_ERROR,
  8328. fatal: false,
  8329. frag,
  8330. part,
  8331. response: _objectSpread2({
  8332. url: loaderContext.url,
  8333. data: undefined
  8334. }, response),
  8335. error: new Error(`HTTP Error ${response.code} ${response.text}`),
  8336. networkDetails,
  8337. stats
  8338. }));
  8339. },
  8340. onAbort: (stats, context, networkDetails) => {
  8341. frag.stats.aborted = part.stats.aborted;
  8342. this.resetLoader(frag, loader);
  8343. reject(new LoadError({
  8344. type: ErrorTypes.NETWORK_ERROR,
  8345. details: ErrorDetails.INTERNAL_ABORTED,
  8346. fatal: false,
  8347. frag,
  8348. part,
  8349. error: new Error('Aborted'),
  8350. networkDetails,
  8351. stats
  8352. }));
  8353. },
  8354. onTimeout: (stats, context, networkDetails) => {
  8355. this.resetLoader(frag, loader);
  8356. reject(new LoadError({
  8357. type: ErrorTypes.NETWORK_ERROR,
  8358. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  8359. fatal: false,
  8360. frag,
  8361. part,
  8362. error: new Error(`Timeout after ${loaderConfig.timeout}ms`),
  8363. networkDetails,
  8364. stats
  8365. }));
  8366. }
  8367. });
  8368. });
  8369. }
  8370. updateStatsFromPart(frag, part) {
  8371. const fragStats = frag.stats;
  8372. const partStats = part.stats;
  8373. const partTotal = partStats.total;
  8374. fragStats.loaded += partStats.loaded;
  8375. if (partTotal) {
  8376. const estTotalParts = Math.round(frag.duration / part.duration);
  8377. const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  8378. const estRemainingParts = estTotalParts - estLoadedParts;
  8379. const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  8380. fragStats.total = fragStats.loaded + estRemainingBytes;
  8381. } else {
  8382. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  8383. }
  8384. const fragLoading = fragStats.loading;
  8385. const partLoading = partStats.loading;
  8386. if (fragLoading.start) {
  8387. // add to fragment loader latency
  8388. fragLoading.first += partLoading.first - partLoading.start;
  8389. } else {
  8390. fragLoading.start = partLoading.start;
  8391. fragLoading.first = partLoading.first;
  8392. }
  8393. fragLoading.end = partLoading.end;
  8394. }
  8395. resetLoader(frag, loader) {
  8396. frag.loader = null;
  8397. if (this.loader === loader) {
  8398. self.clearTimeout(this.partLoadTimeout);
  8399. this.loader = null;
  8400. }
  8401. loader.destroy();
  8402. }
  8403. }
  8404. function createLoaderContext(frag, part = null) {
  8405. const segment = part || frag;
  8406. const loaderContext = {
  8407. frag,
  8408. part,
  8409. responseType: 'arraybuffer',
  8410. url: segment.url,
  8411. headers: {},
  8412. rangeStart: 0,
  8413. rangeEnd: 0
  8414. };
  8415. const start = segment.byteRangeStartOffset;
  8416. const end = segment.byteRangeEndOffset;
  8417. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  8418. var _frag$decryptdata;
  8419. let byteRangeStart = start;
  8420. let byteRangeEnd = end;
  8421. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  8422. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  8423. // has the unencrypted size specified in the range.
  8424. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  8425. const fragmentLen = end - start;
  8426. if (fragmentLen % 16) {
  8427. byteRangeEnd = end + (16 - fragmentLen % 16);
  8428. }
  8429. if (start !== 0) {
  8430. loaderContext.resetIV = true;
  8431. byteRangeStart = start - 16;
  8432. }
  8433. }
  8434. loaderContext.rangeStart = byteRangeStart;
  8435. loaderContext.rangeEnd = byteRangeEnd;
  8436. }
  8437. return loaderContext;
  8438. }
  8439. function createGapLoadError(frag, part) {
  8440. const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);
  8441. const errorData = {
  8442. type: ErrorTypes.MEDIA_ERROR,
  8443. details: ErrorDetails.FRAG_GAP,
  8444. fatal: false,
  8445. frag,
  8446. error,
  8447. networkDetails: null
  8448. };
  8449. if (part) {
  8450. errorData.part = part;
  8451. }
  8452. (part ? part : frag).stats.aborted = true;
  8453. return new LoadError(errorData);
  8454. }
  8455. class LoadError extends Error {
  8456. constructor(data) {
  8457. super(data.error.message);
  8458. this.data = void 0;
  8459. this.data = data;
  8460. }
  8461. }
  8462. class AESCrypto {
  8463. constructor(subtle, iv) {
  8464. this.subtle = void 0;
  8465. this.aesIV = void 0;
  8466. this.subtle = subtle;
  8467. this.aesIV = iv;
  8468. }
  8469. decrypt(data, key) {
  8470. return this.subtle.decrypt({
  8471. name: 'AES-CBC',
  8472. iv: this.aesIV
  8473. }, key, data);
  8474. }
  8475. }
  8476. class FastAESKey {
  8477. constructor(subtle, key) {
  8478. this.subtle = void 0;
  8479. this.key = void 0;
  8480. this.subtle = subtle;
  8481. this.key = key;
  8482. }
  8483. expandKey() {
  8484. return this.subtle.importKey('raw', this.key, {
  8485. name: 'AES-CBC'
  8486. }, false, ['encrypt', 'decrypt']);
  8487. }
  8488. }
  8489. // PKCS7
  8490. function removePadding(array) {
  8491. const outputBytes = array.byteLength;
  8492. const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  8493. if (paddingBytes) {
  8494. return sliceUint8(array, 0, outputBytes - paddingBytes);
  8495. }
  8496. return array;
  8497. }
  8498. class AESDecryptor {
  8499. constructor() {
  8500. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  8501. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8502. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  8503. this.sBox = new Uint32Array(256);
  8504. this.invSBox = new Uint32Array(256);
  8505. this.key = new Uint32Array(0);
  8506. this.ksRows = 0;
  8507. this.keySize = 0;
  8508. this.keySchedule = void 0;
  8509. this.invKeySchedule = void 0;
  8510. this.initTable();
  8511. }
  8512. // Using view.getUint32() also swaps the byte order.
  8513. uint8ArrayToUint32Array_(arrayBuffer) {
  8514. const view = new DataView(arrayBuffer);
  8515. const newArray = new Uint32Array(4);
  8516. for (let i = 0; i < 4; i++) {
  8517. newArray[i] = view.getUint32(i * 4);
  8518. }
  8519. return newArray;
  8520. }
  8521. initTable() {
  8522. const sBox = this.sBox;
  8523. const invSBox = this.invSBox;
  8524. const subMix = this.subMix;
  8525. const subMix0 = subMix[0];
  8526. const subMix1 = subMix[1];
  8527. const subMix2 = subMix[2];
  8528. const subMix3 = subMix[3];
  8529. const invSubMix = this.invSubMix;
  8530. const invSubMix0 = invSubMix[0];
  8531. const invSubMix1 = invSubMix[1];
  8532. const invSubMix2 = invSubMix[2];
  8533. const invSubMix3 = invSubMix[3];
  8534. const d = new Uint32Array(256);
  8535. let x = 0;
  8536. let xi = 0;
  8537. let i = 0;
  8538. for (i = 0; i < 256; i++) {
  8539. if (i < 128) {
  8540. d[i] = i << 1;
  8541. } else {
  8542. d[i] = i << 1 ^ 0x11b;
  8543. }
  8544. }
  8545. for (i = 0; i < 256; i++) {
  8546. let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  8547. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  8548. sBox[x] = sx;
  8549. invSBox[sx] = x;
  8550. // Compute multiplication
  8551. const x2 = d[x];
  8552. const x4 = d[x2];
  8553. const x8 = d[x4];
  8554. // Compute sub/invSub bytes, mix columns tables
  8555. let t = d[sx] * 0x101 ^ sx * 0x1010100;
  8556. subMix0[x] = t << 24 | t >>> 8;
  8557. subMix1[x] = t << 16 | t >>> 16;
  8558. subMix2[x] = t << 8 | t >>> 24;
  8559. subMix3[x] = t;
  8560. // Compute inv sub bytes, inv mix columns tables
  8561. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  8562. invSubMix0[sx] = t << 24 | t >>> 8;
  8563. invSubMix1[sx] = t << 16 | t >>> 16;
  8564. invSubMix2[sx] = t << 8 | t >>> 24;
  8565. invSubMix3[sx] = t;
  8566. // Compute next counter
  8567. if (!x) {
  8568. x = xi = 1;
  8569. } else {
  8570. x = x2 ^ d[d[d[x8 ^ x2]]];
  8571. xi ^= d[d[xi]];
  8572. }
  8573. }
  8574. }
  8575. expandKey(keyBuffer) {
  8576. // convert keyBuffer to Uint32Array
  8577. const key = this.uint8ArrayToUint32Array_(keyBuffer);
  8578. let sameKey = true;
  8579. let offset = 0;
  8580. while (offset < key.length && sameKey) {
  8581. sameKey = key[offset] === this.key[offset];
  8582. offset++;
  8583. }
  8584. if (sameKey) {
  8585. return;
  8586. }
  8587. this.key = key;
  8588. const keySize = this.keySize = key.length;
  8589. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  8590. throw new Error('Invalid aes key size=' + keySize);
  8591. }
  8592. const ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  8593. let ksRow;
  8594. let invKsRow;
  8595. const keySchedule = this.keySchedule = new Uint32Array(ksRows);
  8596. const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  8597. const sbox = this.sBox;
  8598. const rcon = this.rcon;
  8599. const invSubMix = this.invSubMix;
  8600. const invSubMix0 = invSubMix[0];
  8601. const invSubMix1 = invSubMix[1];
  8602. const invSubMix2 = invSubMix[2];
  8603. const invSubMix3 = invSubMix[3];
  8604. let prev;
  8605. let t;
  8606. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  8607. if (ksRow < keySize) {
  8608. prev = keySchedule[ksRow] = key[ksRow];
  8609. continue;
  8610. }
  8611. t = prev;
  8612. if (ksRow % keySize === 0) {
  8613. // Rot word
  8614. t = t << 8 | t >>> 24;
  8615. // Sub word
  8616. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8617. // Mix Rcon
  8618. t ^= rcon[ksRow / keySize | 0] << 24;
  8619. } else if (keySize > 6 && ksRow % keySize === 4) {
  8620. // Sub word
  8621. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  8622. }
  8623. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  8624. }
  8625. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  8626. ksRow = ksRows - invKsRow;
  8627. if (invKsRow & 3) {
  8628. t = keySchedule[ksRow];
  8629. } else {
  8630. t = keySchedule[ksRow - 4];
  8631. }
  8632. if (invKsRow < 4 || ksRow <= 4) {
  8633. invKeySchedule[invKsRow] = t;
  8634. } else {
  8635. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  8636. }
  8637. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  8638. }
  8639. }
  8640. // Adding this as a method greatly improves performance.
  8641. networkToHostOrderSwap(word) {
  8642. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  8643. }
  8644. decrypt(inputArrayBuffer, offset, aesIV) {
  8645. const nRounds = this.keySize + 6;
  8646. const invKeySchedule = this.invKeySchedule;
  8647. const invSBOX = this.invSBox;
  8648. const invSubMix = this.invSubMix;
  8649. const invSubMix0 = invSubMix[0];
  8650. const invSubMix1 = invSubMix[1];
  8651. const invSubMix2 = invSubMix[2];
  8652. const invSubMix3 = invSubMix[3];
  8653. const initVector = this.uint8ArrayToUint32Array_(aesIV);
  8654. let initVector0 = initVector[0];
  8655. let initVector1 = initVector[1];
  8656. let initVector2 = initVector[2];
  8657. let initVector3 = initVector[3];
  8658. const inputInt32 = new Int32Array(inputArrayBuffer);
  8659. const outputInt32 = new Int32Array(inputInt32.length);
  8660. let t0, t1, t2, t3;
  8661. let s0, s1, s2, s3;
  8662. let inputWords0, inputWords1, inputWords2, inputWords3;
  8663. let ksRow, i;
  8664. const swapWord = this.networkToHostOrderSwap;
  8665. while (offset < inputInt32.length) {
  8666. inputWords0 = swapWord(inputInt32[offset]);
  8667. inputWords1 = swapWord(inputInt32[offset + 1]);
  8668. inputWords2 = swapWord(inputInt32[offset + 2]);
  8669. inputWords3 = swapWord(inputInt32[offset + 3]);
  8670. s0 = inputWords0 ^ invKeySchedule[0];
  8671. s1 = inputWords3 ^ invKeySchedule[1];
  8672. s2 = inputWords2 ^ invKeySchedule[2];
  8673. s3 = inputWords1 ^ invKeySchedule[3];
  8674. ksRow = 4;
  8675. // Iterate through the rounds of decryption
  8676. for (i = 1; i < nRounds; i++) {
  8677. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  8678. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  8679. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  8680. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  8681. // Update state
  8682. s0 = t0;
  8683. s1 = t1;
  8684. s2 = t2;
  8685. s3 = t3;
  8686. ksRow = ksRow + 4;
  8687. }
  8688. // Shift rows, sub bytes, add round key
  8689. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  8690. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  8691. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  8692. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  8693. // Write
  8694. outputInt32[offset] = swapWord(t0 ^ initVector0);
  8695. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  8696. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  8697. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  8698. // reset initVector to last 4 unsigned int
  8699. initVector0 = inputWords0;
  8700. initVector1 = inputWords1;
  8701. initVector2 = inputWords2;
  8702. initVector3 = inputWords3;
  8703. offset = offset + 4;
  8704. }
  8705. return outputInt32.buffer;
  8706. }
  8707. }
  8708. const CHUNK_SIZE = 16; // 16 bytes, 128 bits
  8709. class Decrypter {
  8710. constructor(config, {
  8711. removePKCS7Padding = true
  8712. } = {}) {
  8713. this.logEnabled = true;
  8714. this.removePKCS7Padding = void 0;
  8715. this.subtle = null;
  8716. this.softwareDecrypter = null;
  8717. this.key = null;
  8718. this.fastAesKey = null;
  8719. this.remainderData = null;
  8720. this.currentIV = null;
  8721. this.currentResult = null;
  8722. this.useSoftware = void 0;
  8723. this.useSoftware = config.enableSoftwareAES;
  8724. this.removePKCS7Padding = removePKCS7Padding;
  8725. // built in decryptor expects PKCS7 padding
  8726. if (removePKCS7Padding) {
  8727. try {
  8728. const browserCrypto = self.crypto;
  8729. if (browserCrypto) {
  8730. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  8731. }
  8732. } catch (e) {
  8733. /* no-op */
  8734. }
  8735. }
  8736. this.useSoftware = !this.subtle;
  8737. }
  8738. destroy() {
  8739. this.subtle = null;
  8740. this.softwareDecrypter = null;
  8741. this.key = null;
  8742. this.fastAesKey = null;
  8743. this.remainderData = null;
  8744. this.currentIV = null;
  8745. this.currentResult = null;
  8746. }
  8747. isSync() {
  8748. return this.useSoftware;
  8749. }
  8750. flush() {
  8751. const {
  8752. currentResult,
  8753. remainderData
  8754. } = this;
  8755. if (!currentResult || remainderData) {
  8756. this.reset();
  8757. return null;
  8758. }
  8759. const data = new Uint8Array(currentResult);
  8760. this.reset();
  8761. if (this.removePKCS7Padding) {
  8762. return removePadding(data);
  8763. }
  8764. return data;
  8765. }
  8766. reset() {
  8767. this.currentResult = null;
  8768. this.currentIV = null;
  8769. this.remainderData = null;
  8770. if (this.softwareDecrypter) {
  8771. this.softwareDecrypter = null;
  8772. }
  8773. }
  8774. decrypt(data, key, iv) {
  8775. if (this.useSoftware) {
  8776. return new Promise((resolve, reject) => {
  8777. this.softwareDecrypt(new Uint8Array(data), key, iv);
  8778. const decryptResult = this.flush();
  8779. if (decryptResult) {
  8780. resolve(decryptResult.buffer);
  8781. } else {
  8782. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  8783. }
  8784. });
  8785. }
  8786. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  8787. }
  8788. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  8789. // data is handled in the flush() call
  8790. softwareDecrypt(data, key, iv) {
  8791. const {
  8792. currentIV,
  8793. currentResult,
  8794. remainderData
  8795. } = this;
  8796. this.logOnce('JS AES decrypt');
  8797. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  8798. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  8799. // the end on flush(), but by that time we have already received all bytes for the segment.
  8800. // Progressive decryption does not work with WebCrypto
  8801. if (remainderData) {
  8802. data = appendUint8Array(remainderData, data);
  8803. this.remainderData = null;
  8804. }
  8805. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  8806. const currentChunk = this.getValidChunk(data);
  8807. if (!currentChunk.length) {
  8808. return null;
  8809. }
  8810. if (currentIV) {
  8811. iv = currentIV;
  8812. }
  8813. let softwareDecrypter = this.softwareDecrypter;
  8814. if (!softwareDecrypter) {
  8815. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  8816. }
  8817. softwareDecrypter.expandKey(key);
  8818. const result = currentResult;
  8819. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  8820. this.currentIV = sliceUint8(currentChunk, -16).buffer;
  8821. if (!result) {
  8822. return null;
  8823. }
  8824. return result;
  8825. }
  8826. webCryptoDecrypt(data, key, iv) {
  8827. if (this.key !== key || !this.fastAesKey) {
  8828. if (!this.subtle) {
  8829. return Promise.resolve(this.onWebCryptoError(data, key, iv));
  8830. }
  8831. this.key = key;
  8832. this.fastAesKey = new FastAESKey(this.subtle, key);
  8833. }
  8834. return this.fastAesKey.expandKey().then(aesKey => {
  8835. // decrypt using web crypto
  8836. if (!this.subtle) {
  8837. return Promise.reject(new Error('web crypto not initialized'));
  8838. }
  8839. this.logOnce('WebCrypto AES decrypt');
  8840. const crypto = new AESCrypto(this.subtle, new Uint8Array(iv));
  8841. return crypto.decrypt(data.buffer, aesKey);
  8842. }).catch(err => {
  8843. logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);
  8844. return this.onWebCryptoError(data, key, iv);
  8845. });
  8846. }
  8847. onWebCryptoError(data, key, iv) {
  8848. this.useSoftware = true;
  8849. this.logEnabled = true;
  8850. this.softwareDecrypt(data, key, iv);
  8851. const decryptResult = this.flush();
  8852. if (decryptResult) {
  8853. return decryptResult.buffer;
  8854. }
  8855. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  8856. }
  8857. getValidChunk(data) {
  8858. let currentChunk = data;
  8859. const splitPoint = data.length - data.length % CHUNK_SIZE;
  8860. if (splitPoint !== data.length) {
  8861. currentChunk = sliceUint8(data, 0, splitPoint);
  8862. this.remainderData = sliceUint8(data, splitPoint);
  8863. }
  8864. return currentChunk;
  8865. }
  8866. logOnce(msg) {
  8867. if (!this.logEnabled) {
  8868. return;
  8869. }
  8870. logger.log(`[decrypter]: ${msg}`);
  8871. this.logEnabled = false;
  8872. }
  8873. }
  8874. /**
  8875. * TimeRanges to string helper
  8876. */
  8877. const TimeRanges = {
  8878. toString: function (r) {
  8879. let log = '';
  8880. const len = r.length;
  8881. for (let i = 0; i < len; i++) {
  8882. log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;
  8883. }
  8884. return log;
  8885. }
  8886. };
  8887. const State = {
  8888. STOPPED: 'STOPPED',
  8889. IDLE: 'IDLE',
  8890. KEY_LOADING: 'KEY_LOADING',
  8891. FRAG_LOADING: 'FRAG_LOADING',
  8892. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  8893. WAITING_TRACK: 'WAITING_TRACK',
  8894. PARSING: 'PARSING',
  8895. PARSED: 'PARSED',
  8896. ENDED: 'ENDED',
  8897. ERROR: 'ERROR',
  8898. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  8899. WAITING_LEVEL: 'WAITING_LEVEL'
  8900. };
  8901. class BaseStreamController extends TaskLoop {
  8902. constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  8903. super();
  8904. this.hls = void 0;
  8905. this.fragPrevious = null;
  8906. this.fragCurrent = null;
  8907. this.fragmentTracker = void 0;
  8908. this.transmuxer = null;
  8909. this._state = State.STOPPED;
  8910. this.playlistType = void 0;
  8911. this.media = null;
  8912. this.mediaBuffer = null;
  8913. this.config = void 0;
  8914. this.bitrateTest = false;
  8915. this.lastCurrentTime = 0;
  8916. this.nextLoadPosition = 0;
  8917. this.startPosition = 0;
  8918. this.startTimeOffset = null;
  8919. this.loadedmetadata = false;
  8920. this.retryDate = 0;
  8921. this.levels = null;
  8922. this.fragmentLoader = void 0;
  8923. this.keyLoader = void 0;
  8924. this.levelLastLoaded = null;
  8925. this.startFragRequested = false;
  8926. this.decrypter = void 0;
  8927. this.initPTS = [];
  8928. this.onvseeking = null;
  8929. this.onvended = null;
  8930. this.logPrefix = '';
  8931. this.log = void 0;
  8932. this.warn = void 0;
  8933. this.playlistType = playlistType;
  8934. this.logPrefix = logPrefix;
  8935. this.log = logger.log.bind(logger, `${logPrefix}:`);
  8936. this.warn = logger.warn.bind(logger, `${logPrefix}:`);
  8937. this.hls = hls;
  8938. this.fragmentLoader = new FragmentLoader(hls.config);
  8939. this.keyLoader = keyLoader;
  8940. this.fragmentTracker = fragmentTracker;
  8941. this.config = hls.config;
  8942. this.decrypter = new Decrypter(hls.config);
  8943. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8944. }
  8945. doTick() {
  8946. this.onTickEnd();
  8947. }
  8948. onTickEnd() {}
  8949. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  8950. startLoad(startPosition) {}
  8951. stopLoad() {
  8952. this.fragmentLoader.abort();
  8953. this.keyLoader.abort(this.playlistType);
  8954. const frag = this.fragCurrent;
  8955. if (frag != null && frag.loader) {
  8956. frag.abortRequests();
  8957. this.fragmentTracker.removeFragment(frag);
  8958. }
  8959. this.resetTransmuxer();
  8960. this.fragCurrent = null;
  8961. this.fragPrevious = null;
  8962. this.clearInterval();
  8963. this.clearNextTick();
  8964. this.state = State.STOPPED;
  8965. }
  8966. _streamEnded(bufferInfo, levelDetails) {
  8967. // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,
  8968. // of nothing loading/loaded return false
  8969. if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) {
  8970. return false;
  8971. }
  8972. const partList = levelDetails.partList;
  8973. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  8974. // check instead if the last part is buffered.
  8975. if (partList != null && partList.length) {
  8976. const lastPart = partList[partList.length - 1];
  8977. // Checking the midpoint of the part for potential margin of error and related issues.
  8978. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  8979. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  8980. // part mismatches for independent audio and video playlists/segments.
  8981. const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  8982. return lastPartBuffered;
  8983. }
  8984. const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  8985. return this.fragmentTracker.isEndListAppended(playlistType);
  8986. }
  8987. getLevelDetails() {
  8988. if (this.levels && this.levelLastLoaded !== null) {
  8989. var _this$levelLastLoaded;
  8990. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  8991. }
  8992. }
  8993. onMediaAttached(event, data) {
  8994. const media = this.media = this.mediaBuffer = data.media;
  8995. this.onvseeking = this.onMediaSeeking.bind(this);
  8996. this.onvended = this.onMediaEnded.bind(this);
  8997. media.addEventListener('seeking', this.onvseeking);
  8998. media.addEventListener('ended', this.onvended);
  8999. const config = this.config;
  9000. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  9001. this.startLoad(config.startPosition);
  9002. }
  9003. }
  9004. onMediaDetaching() {
  9005. const media = this.media;
  9006. if (media != null && media.ended) {
  9007. this.log('MSE detaching and video ended, reset startPosition');
  9008. this.startPosition = this.lastCurrentTime = 0;
  9009. }
  9010. // remove video listeners
  9011. if (media && this.onvseeking && this.onvended) {
  9012. media.removeEventListener('seeking', this.onvseeking);
  9013. media.removeEventListener('ended', this.onvended);
  9014. this.onvseeking = this.onvended = null;
  9015. }
  9016. if (this.keyLoader) {
  9017. this.keyLoader.detach();
  9018. }
  9019. this.media = this.mediaBuffer = null;
  9020. this.loadedmetadata = false;
  9021. this.fragmentTracker.removeAllFragments();
  9022. this.stopLoad();
  9023. }
  9024. onMediaSeeking() {
  9025. const {
  9026. config,
  9027. fragCurrent,
  9028. media,
  9029. mediaBuffer,
  9030. state
  9031. } = this;
  9032. const currentTime = media ? media.currentTime : 0;
  9033. const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  9034. this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`);
  9035. if (this.state === State.ENDED) {
  9036. this.resetLoadingState();
  9037. } else if (fragCurrent) {
  9038. // Seeking while frag load is in progress
  9039. const tolerance = config.maxFragLookUpTolerance;
  9040. const fragStartOffset = fragCurrent.start - tolerance;
  9041. const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  9042. // if seeking out of buffered range or into new one
  9043. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  9044. const pastFragment = currentTime > fragEndOffset;
  9045. // if the seek position is outside the current fragment range
  9046. if (currentTime < fragStartOffset || pastFragment) {
  9047. if (pastFragment && fragCurrent.loader) {
  9048. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  9049. fragCurrent.abortRequests();
  9050. this.resetLoadingState();
  9051. }
  9052. this.fragPrevious = null;
  9053. }
  9054. }
  9055. }
  9056. if (media) {
  9057. // Remove gap fragments
  9058. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  9059. this.lastCurrentTime = currentTime;
  9060. }
  9061. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  9062. if (!this.loadedmetadata && !bufferInfo.len) {
  9063. this.nextLoadPosition = this.startPosition = currentTime;
  9064. }
  9065. // Async tick to speed up processing
  9066. this.tickImmediate();
  9067. }
  9068. onMediaEnded() {
  9069. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  9070. this.startPosition = this.lastCurrentTime = 0;
  9071. }
  9072. onManifestLoaded(event, data) {
  9073. this.startTimeOffset = data.startTimeOffset;
  9074. this.initPTS = [];
  9075. }
  9076. onHandlerDestroying() {
  9077. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9078. this.stopLoad();
  9079. super.onHandlerDestroying();
  9080. // @ts-ignore
  9081. this.hls = null;
  9082. }
  9083. onHandlerDestroyed() {
  9084. this.state = State.STOPPED;
  9085. if (this.fragmentLoader) {
  9086. this.fragmentLoader.destroy();
  9087. }
  9088. if (this.keyLoader) {
  9089. this.keyLoader.destroy();
  9090. }
  9091. if (this.decrypter) {
  9092. this.decrypter.destroy();
  9093. }
  9094. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  9095. super.onHandlerDestroyed();
  9096. }
  9097. loadFragment(frag, level, targetBufferTime) {
  9098. this._loadFragForPlayback(frag, level, targetBufferTime);
  9099. }
  9100. _loadFragForPlayback(frag, level, targetBufferTime) {
  9101. const progressCallback = data => {
  9102. if (this.fragContextChanged(frag)) {
  9103. this.warn(`Fragment ${frag.sn}${data.part ? ' p: ' + data.part.index : ''} of level ${frag.level} was dropped during download.`);
  9104. this.fragmentTracker.removeFragment(frag);
  9105. return;
  9106. }
  9107. frag.stats.chunkCount++;
  9108. this._handleFragmentLoadProgress(data);
  9109. };
  9110. this._doFragLoad(frag, level, targetBufferTime, progressCallback).then(data => {
  9111. if (!data) {
  9112. // if we're here we probably needed to backtrack or are waiting for more parts
  9113. return;
  9114. }
  9115. const state = this.state;
  9116. if (this.fragContextChanged(frag)) {
  9117. if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {
  9118. this.fragmentTracker.removeFragment(frag);
  9119. this.state = State.IDLE;
  9120. }
  9121. return;
  9122. }
  9123. if ('payload' in data) {
  9124. this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);
  9125. this.hls.trigger(Events.FRAG_LOADED, data);
  9126. }
  9127. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  9128. this._handleFragmentLoadComplete(data);
  9129. }).catch(reason => {
  9130. if (this.state === State.STOPPED || this.state === State.ERROR) {
  9131. return;
  9132. }
  9133. this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);
  9134. this.resetFragmentLoading(frag);
  9135. });
  9136. }
  9137. clearTrackerIfNeeded(frag) {
  9138. var _this$mediaBuffer;
  9139. const {
  9140. fragmentTracker
  9141. } = this;
  9142. const fragState = fragmentTracker.getState(frag);
  9143. if (fragState === FragmentState.APPENDING) {
  9144. // Lower the max buffer length and try again
  9145. const playlistType = frag.type;
  9146. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  9147. const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  9148. // If backtracking, always remove from the tracker without reducing max buffer length
  9149. const backtrackFragment = this.backtrackFragment;
  9150. const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  9151. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength)) {
  9152. fragmentTracker.removeFragment(frag);
  9153. }
  9154. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  9155. // Stop gap for bad tracker / buffer flush behavior
  9156. fragmentTracker.removeAllFragments();
  9157. } else if (fragmentTracker.hasParts(frag.type)) {
  9158. // In low latency mode, remove fragments for which only some parts were buffered
  9159. fragmentTracker.detectPartialFragments({
  9160. frag,
  9161. part: null,
  9162. stats: frag.stats,
  9163. id: frag.type
  9164. });
  9165. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  9166. fragmentTracker.removeFragment(frag);
  9167. }
  9168. }
  9169. }
  9170. checkLiveUpdate(details) {
  9171. if (details.updated && !details.live) {
  9172. // Live stream ended, update fragment tracker
  9173. const lastFragment = details.fragments[details.fragments.length - 1];
  9174. this.fragmentTracker.detectPartialFragments({
  9175. frag: lastFragment,
  9176. part: null,
  9177. stats: lastFragment.stats,
  9178. id: lastFragment.type
  9179. });
  9180. }
  9181. if (!details.fragments[0]) {
  9182. details.deltaUpdateFailed = true;
  9183. }
  9184. }
  9185. flushMainBuffer(startOffset, endOffset, type = null) {
  9186. if (!(startOffset - endOffset)) {
  9187. return;
  9188. }
  9189. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  9190. // passing a null type flushes both buffers
  9191. const flushScope = {
  9192. startOffset,
  9193. endOffset,
  9194. type
  9195. };
  9196. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  9197. }
  9198. _loadInitSegment(frag, level) {
  9199. this._doFragLoad(frag, level).then(data => {
  9200. if (!data || this.fragContextChanged(frag) || !this.levels) {
  9201. throw new Error('init load aborted');
  9202. }
  9203. return data;
  9204. }).then(data => {
  9205. const {
  9206. hls
  9207. } = this;
  9208. const {
  9209. payload
  9210. } = data;
  9211. const decryptData = frag.decryptdata;
  9212. // check to see if the payload needs to be decrypted
  9213. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  9214. const startTime = self.performance.now();
  9215. // decrypt init segment data
  9216. return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(err => {
  9217. hls.trigger(Events.ERROR, {
  9218. type: ErrorTypes.MEDIA_ERROR,
  9219. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  9220. fatal: false,
  9221. error: err,
  9222. reason: err.message,
  9223. frag
  9224. });
  9225. throw err;
  9226. }).then(decryptedData => {
  9227. const endTime = self.performance.now();
  9228. hls.trigger(Events.FRAG_DECRYPTED, {
  9229. frag,
  9230. payload: decryptedData,
  9231. stats: {
  9232. tstart: startTime,
  9233. tdecrypt: endTime
  9234. }
  9235. });
  9236. data.payload = decryptedData;
  9237. return this.completeInitSegmentLoad(data);
  9238. });
  9239. }
  9240. return this.completeInitSegmentLoad(data);
  9241. }).catch(reason => {
  9242. if (this.state === State.STOPPED || this.state === State.ERROR) {
  9243. return;
  9244. }
  9245. this.warn(reason);
  9246. this.resetFragmentLoading(frag);
  9247. });
  9248. }
  9249. completeInitSegmentLoad(data) {
  9250. const {
  9251. levels
  9252. } = this;
  9253. if (!levels) {
  9254. throw new Error('init load aborted, missing levels');
  9255. }
  9256. const stats = data.frag.stats;
  9257. this.state = State.IDLE;
  9258. data.frag.data = new Uint8Array(data.payload);
  9259. stats.parsing.start = stats.buffering.start = self.performance.now();
  9260. stats.parsing.end = stats.buffering.end = self.performance.now();
  9261. this.tick();
  9262. }
  9263. fragContextChanged(frag) {
  9264. const {
  9265. fragCurrent
  9266. } = this;
  9267. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  9268. }
  9269. fragBufferedComplete(frag, part) {
  9270. var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious;
  9271. const media = this.mediaBuffer ? this.mediaBuffer : this.media;
  9272. 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)'})`);
  9273. if (frag.sn !== 'initSegment') {
  9274. var _this$levels;
  9275. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  9276. const el = frag.elementaryStreams;
  9277. if (!Object.keys(el).some(type => !!el[type])) {
  9278. // empty segment
  9279. this.state = State.IDLE;
  9280. return;
  9281. }
  9282. }
  9283. const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  9284. if (level != null && level.fragmentError) {
  9285. this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);
  9286. level.fragmentError = 0;
  9287. }
  9288. }
  9289. this.state = State.IDLE;
  9290. if (!media) {
  9291. return;
  9292. }
  9293. 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)) {
  9294. this.loadedmetadata = true;
  9295. this.seekToStartPos();
  9296. }
  9297. this.tick();
  9298. }
  9299. seekToStartPos() {}
  9300. _handleFragmentLoadComplete(fragLoadedEndData) {
  9301. const {
  9302. transmuxer
  9303. } = this;
  9304. if (!transmuxer) {
  9305. return;
  9306. }
  9307. const {
  9308. frag,
  9309. part,
  9310. partsLoaded
  9311. } = fragLoadedEndData;
  9312. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  9313. const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);
  9314. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  9315. transmuxer.flush(chunkMeta);
  9316. }
  9317. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  9318. _handleFragmentLoadProgress(frag) {}
  9319. _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {
  9320. var _frag$decryptdata;
  9321. const details = level == null ? void 0 : level.details;
  9322. if (!this.levels || !details) {
  9323. throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);
  9324. }
  9325. let keyLoadingPromise = null;
  9326. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  9327. this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.logPrefix === '[stream-controller]' ? 'level' : 'track'} ${frag.level}`);
  9328. this.state = State.KEY_LOADING;
  9329. this.fragCurrent = frag;
  9330. keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {
  9331. if (!this.fragContextChanged(keyLoadedData.frag)) {
  9332. this.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  9333. if (this.state === State.KEY_LOADING) {
  9334. this.state = State.IDLE;
  9335. }
  9336. return keyLoadedData;
  9337. }
  9338. });
  9339. this.hls.trigger(Events.KEY_LOADING, {
  9340. frag
  9341. });
  9342. if (this.fragCurrent === null) {
  9343. keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));
  9344. }
  9345. } else if (!frag.encrypted && details.encryptedFragments.length) {
  9346. this.keyLoader.loadClear(frag, details.encryptedFragments);
  9347. }
  9348. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  9349. if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {
  9350. const partList = details.partList;
  9351. if (partList && progressCallback) {
  9352. if (targetBufferTime > frag.end && details.fragmentHint) {
  9353. frag = details.fragmentHint;
  9354. }
  9355. const partIndex = this.getNextPart(partList, frag, targetBufferTime);
  9356. if (partIndex > -1) {
  9357. const part = partList[partIndex];
  9358. 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))}`);
  9359. this.nextLoadPosition = part.start + part.duration;
  9360. this.state = State.FRAG_LOADING;
  9361. let _result;
  9362. if (keyLoadingPromise) {
  9363. _result = keyLoadingPromise.then(keyLoadedData => {
  9364. if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {
  9365. return null;
  9366. }
  9367. return this.doFragPartsLoad(frag, part, level, progressCallback);
  9368. }).catch(error => this.handleFragLoadError(error));
  9369. } else {
  9370. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));
  9371. }
  9372. this.hls.trigger(Events.FRAG_LOADING, {
  9373. frag,
  9374. part,
  9375. targetBufferTime
  9376. });
  9377. if (this.fragCurrent === null) {
  9378. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));
  9379. }
  9380. return _result;
  9381. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  9382. // Fragment hint has no parts
  9383. return Promise.resolve(null);
  9384. }
  9385. }
  9386. }
  9387. 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))}`);
  9388. // Don't update nextLoadPosition for fragments which are not buffered
  9389. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  9390. this.nextLoadPosition = frag.start + frag.duration;
  9391. }
  9392. this.state = State.FRAG_LOADING;
  9393. // Load key before streaming fragment data
  9394. const dataOnProgress = this.config.progressive;
  9395. let result;
  9396. if (dataOnProgress && keyLoadingPromise) {
  9397. result = keyLoadingPromise.then(keyLoadedData => {
  9398. if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  9399. return null;
  9400. }
  9401. return this.fragmentLoader.load(frag, progressCallback);
  9402. }).catch(error => this.handleFragLoadError(error));
  9403. } else {
  9404. // load unencrypted fragment data with progress event,
  9405. // or handle fragment result after key and fragment are finished loading
  9406. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {
  9407. if (!dataOnProgress && fragLoadedData && progressCallback) {
  9408. progressCallback(fragLoadedData);
  9409. }
  9410. return fragLoadedData;
  9411. }).catch(error => this.handleFragLoadError(error));
  9412. }
  9413. this.hls.trigger(Events.FRAG_LOADING, {
  9414. frag,
  9415. targetBufferTime
  9416. });
  9417. if (this.fragCurrent === null) {
  9418. return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));
  9419. }
  9420. return result;
  9421. }
  9422. doFragPartsLoad(frag, fromPart, level, progressCallback) {
  9423. return new Promise((resolve, reject) => {
  9424. var _level$details;
  9425. const partsLoaded = [];
  9426. const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  9427. const loadPart = part => {
  9428. this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {
  9429. partsLoaded[part.index] = partLoadedData;
  9430. const loadedPart = partLoadedData.part;
  9431. this.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  9432. const nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  9433. if (nextPart) {
  9434. loadPart(nextPart);
  9435. } else {
  9436. return resolve({
  9437. frag,
  9438. part: loadedPart,
  9439. partsLoaded
  9440. });
  9441. }
  9442. }).catch(reject);
  9443. };
  9444. loadPart(fromPart);
  9445. });
  9446. }
  9447. handleFragLoadError(error) {
  9448. if ('data' in error) {
  9449. const data = error.data;
  9450. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  9451. this.handleFragLoadAborted(data.frag, data.part);
  9452. } else {
  9453. this.hls.trigger(Events.ERROR, data);
  9454. }
  9455. } else {
  9456. this.hls.trigger(Events.ERROR, {
  9457. type: ErrorTypes.OTHER_ERROR,
  9458. details: ErrorDetails.INTERNAL_EXCEPTION,
  9459. err: error,
  9460. error,
  9461. fatal: true
  9462. });
  9463. }
  9464. return null;
  9465. }
  9466. _handleTransmuxerFlush(chunkMeta) {
  9467. const context = this.getCurrentContext(chunkMeta);
  9468. if (!context || this.state !== State.PARSING) {
  9469. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  9470. this.state = State.IDLE;
  9471. }
  9472. return;
  9473. }
  9474. const {
  9475. frag,
  9476. part,
  9477. level
  9478. } = context;
  9479. const now = self.performance.now();
  9480. frag.stats.parsing.end = now;
  9481. if (part) {
  9482. part.stats.parsing.end = now;
  9483. }
  9484. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  9485. }
  9486. getCurrentContext(chunkMeta) {
  9487. const {
  9488. levels,
  9489. fragCurrent
  9490. } = this;
  9491. const {
  9492. level: levelIndex,
  9493. sn,
  9494. part: partIndex
  9495. } = chunkMeta;
  9496. if (!(levels != null && levels[levelIndex])) {
  9497. this.warn(`Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`);
  9498. return null;
  9499. }
  9500. const level = levels[levelIndex];
  9501. const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  9502. const frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent);
  9503. if (!frag) {
  9504. return null;
  9505. }
  9506. if (fragCurrent && fragCurrent !== frag) {
  9507. frag.stats = fragCurrent.stats;
  9508. }
  9509. return {
  9510. frag,
  9511. part,
  9512. level
  9513. };
  9514. }
  9515. bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  9516. var _buffer;
  9517. if (!data || this.state !== State.PARSING) {
  9518. return;
  9519. }
  9520. const {
  9521. data1,
  9522. data2
  9523. } = data;
  9524. let buffer = data1;
  9525. if (data1 && data2) {
  9526. // Combine the moof + mdat so that we buffer with a single append
  9527. buffer = appendUint8Array(data1, data2);
  9528. }
  9529. if (!((_buffer = buffer) != null && _buffer.length)) {
  9530. return;
  9531. }
  9532. const segment = {
  9533. type: data.type,
  9534. frag,
  9535. part,
  9536. chunkMeta,
  9537. parent: frag.type,
  9538. data: buffer
  9539. };
  9540. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  9541. if (data.dropped && data.independent && !part) {
  9542. if (noBacktracking) {
  9543. return;
  9544. }
  9545. // Clear buffer so that we reload previous segments sequentially if required
  9546. this.flushBufferGap(frag);
  9547. }
  9548. }
  9549. flushBufferGap(frag) {
  9550. const media = this.media;
  9551. if (!media) {
  9552. return;
  9553. }
  9554. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  9555. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  9556. this.flushMainBuffer(0, frag.start);
  9557. return;
  9558. }
  9559. // Remove back-buffer without interrupting playback to allow back tracking
  9560. const currentTime = media.currentTime;
  9561. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  9562. const fragDuration = frag.duration;
  9563. const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  9564. const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  9565. if (frag.start - start > segmentFraction) {
  9566. this.flushMainBuffer(start, frag.start);
  9567. }
  9568. }
  9569. getFwdBufferInfo(bufferable, type) {
  9570. const pos = this.getLoadPosition();
  9571. if (!isFiniteNumber(pos)) {
  9572. return null;
  9573. }
  9574. return this.getFwdBufferInfoAtPos(bufferable, pos, type);
  9575. }
  9576. getFwdBufferInfoAtPos(bufferable, pos, type) {
  9577. const {
  9578. config: {
  9579. maxBufferHole
  9580. }
  9581. } = this;
  9582. const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  9583. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  9584. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  9585. const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  9586. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  9587. return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole));
  9588. }
  9589. }
  9590. return bufferInfo;
  9591. }
  9592. getMaxBufferLength(levelBitrate) {
  9593. const {
  9594. config
  9595. } = this;
  9596. let maxBufLen;
  9597. if (levelBitrate) {
  9598. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  9599. } else {
  9600. maxBufLen = config.maxBufferLength;
  9601. }
  9602. return Math.min(maxBufLen, config.maxMaxBufferLength);
  9603. }
  9604. reduceMaxBufferLength(threshold) {
  9605. const config = this.config;
  9606. const minLength = threshold || config.maxBufferLength;
  9607. const reducedLength = config.maxMaxBufferLength / 2;
  9608. if (reducedLength >= minLength) {
  9609. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  9610. config.maxMaxBufferLength = reducedLength;
  9611. this.warn(`Reduce max buffer length to ${reducedLength}s`);
  9612. return true;
  9613. }
  9614. return false;
  9615. }
  9616. getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {
  9617. const fragOrPart = this.fragmentTracker.getAppendedFrag(position, PlaylistLevelType.MAIN);
  9618. if (fragOrPart && 'fragment' in fragOrPart) {
  9619. return fragOrPart.fragment;
  9620. }
  9621. return fragOrPart;
  9622. }
  9623. getNextFragment(pos, levelDetails) {
  9624. const fragments = levelDetails.fragments;
  9625. const fragLen = fragments.length;
  9626. if (!fragLen) {
  9627. return null;
  9628. }
  9629. // find fragment index, contiguous with end of buffer position
  9630. const {
  9631. config
  9632. } = this;
  9633. const start = fragments[0].start;
  9634. let frag;
  9635. if (levelDetails.live) {
  9636. const initialLiveManifestSize = config.initialLiveManifestSize;
  9637. if (fragLen < initialLiveManifestSize) {
  9638. this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);
  9639. return null;
  9640. }
  9641. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  9642. // In order to discover the range, we load the best matching fragment for that level and demux it.
  9643. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  9644. // we get the fragment matching that start time
  9645. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  9646. frag = this.getInitialLiveFragment(levelDetails, fragments);
  9647. this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  9648. }
  9649. } else if (pos <= start) {
  9650. // VoD playlist: if loadPosition before start of playlist, load first fragment
  9651. frag = fragments[0];
  9652. }
  9653. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  9654. if (!frag) {
  9655. const end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  9656. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  9657. }
  9658. return this.mapToInitFragWhenRequired(frag);
  9659. }
  9660. isLoopLoading(frag, targetBufferTime) {
  9661. const trackerState = this.fragmentTracker.getState(frag);
  9662. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  9663. }
  9664. getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  9665. const gapStart = frag.gap;
  9666. const nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  9667. if (nextFragment === null) {
  9668. return nextFragment;
  9669. }
  9670. frag = nextFragment;
  9671. if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {
  9672. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  9673. const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType);
  9674. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  9675. // Returning here might result in not finding an audio and video candiate to skip to
  9676. this.log(`buffer full after gaps in "${playlistType}" playlist starting at sn: ${frag.sn}`);
  9677. return null;
  9678. }
  9679. }
  9680. return frag;
  9681. }
  9682. mapToInitFragWhenRequired(frag) {
  9683. // If an initSegment is present, it must be buffered first
  9684. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  9685. return frag.initSegment;
  9686. }
  9687. return frag;
  9688. }
  9689. getNextPart(partList, frag, targetBufferTime) {
  9690. let nextPart = -1;
  9691. let contiguous = false;
  9692. let independentAttrOmitted = true;
  9693. for (let i = 0, len = partList.length; i < len; i++) {
  9694. const part = partList[i];
  9695. independentAttrOmitted = independentAttrOmitted && !part.independent;
  9696. if (nextPart > -1 && targetBufferTime < part.start) {
  9697. break;
  9698. }
  9699. const loaded = part.loaded;
  9700. if (loaded) {
  9701. nextPart = -1;
  9702. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  9703. nextPart = i;
  9704. }
  9705. contiguous = loaded;
  9706. }
  9707. return nextPart;
  9708. }
  9709. loadedEndOfParts(partList, targetBufferTime) {
  9710. const lastPart = partList[partList.length - 1];
  9711. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  9712. }
  9713. /*
  9714. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  9715. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  9716. start and end times for each fragment in the playlist (after which this method will not need to be called).
  9717. */
  9718. getInitialLiveFragment(levelDetails, fragments) {
  9719. const fragPrevious = this.fragPrevious;
  9720. let frag = null;
  9721. if (fragPrevious) {
  9722. if (levelDetails.hasProgramDateTime) {
  9723. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  9724. this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);
  9725. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  9726. }
  9727. if (!frag) {
  9728. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  9729. const targetSN = fragPrevious.sn + 1;
  9730. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  9731. const fragNext = fragments[targetSN - levelDetails.startSN];
  9732. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  9733. if (fragPrevious.cc === fragNext.cc) {
  9734. frag = fragNext;
  9735. this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);
  9736. }
  9737. }
  9738. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  9739. // will have the wrong start times
  9740. if (!frag) {
  9741. frag = findFragWithCC(fragments, fragPrevious.cc);
  9742. if (frag) {
  9743. this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);
  9744. }
  9745. }
  9746. }
  9747. } else {
  9748. // Find a new start fragment when fragPrevious is null
  9749. const liveStart = this.hls.liveSyncPosition;
  9750. if (liveStart !== null) {
  9751. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  9752. }
  9753. }
  9754. return frag;
  9755. }
  9756. /*
  9757. This method finds the best matching fragment given the provided position.
  9758. */
  9759. getFragmentAtPosition(bufferEnd, end, levelDetails) {
  9760. const {
  9761. config
  9762. } = this;
  9763. let {
  9764. fragPrevious
  9765. } = this;
  9766. let {
  9767. fragments,
  9768. endSN
  9769. } = levelDetails;
  9770. const {
  9771. fragmentHint
  9772. } = levelDetails;
  9773. const {
  9774. maxFragLookUpTolerance
  9775. } = config;
  9776. const partList = levelDetails.partList;
  9777. const loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint);
  9778. if (loadingParts && fragmentHint && !this.bitrateTest) {
  9779. // Include incomplete fragment with parts at end
  9780. fragments = fragments.concat(fragmentHint);
  9781. endSN = fragmentHint.sn;
  9782. }
  9783. let frag;
  9784. if (bufferEnd < end) {
  9785. const lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;
  9786. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  9787. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  9788. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  9789. } else {
  9790. // reach end of playlist
  9791. frag = fragments[fragments.length - 1];
  9792. }
  9793. if (frag) {
  9794. const curSNIdx = frag.sn - levelDetails.startSN;
  9795. // Move fragPrevious forward to support forcing the next fragment to load
  9796. // when the buffer catches up to a previously buffered range.
  9797. const fragState = this.fragmentTracker.getState(frag);
  9798. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  9799. fragPrevious = frag;
  9800. }
  9801. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) {
  9802. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  9803. // non-uniform fragment durations
  9804. const sameLevel = fragPrevious && frag.level === fragPrevious.level;
  9805. if (sameLevel) {
  9806. const nextFrag = fragments[curSNIdx + 1];
  9807. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  9808. frag = nextFrag;
  9809. } else {
  9810. frag = null;
  9811. }
  9812. }
  9813. }
  9814. }
  9815. return frag;
  9816. }
  9817. synchronizeToLiveEdge(levelDetails) {
  9818. const {
  9819. config,
  9820. media
  9821. } = this;
  9822. if (!media) {
  9823. return;
  9824. }
  9825. const liveSyncPosition = this.hls.liveSyncPosition;
  9826. const currentTime = media.currentTime;
  9827. const start = levelDetails.fragments[0].start;
  9828. const end = levelDetails.edge;
  9829. const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  9830. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  9831. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  9832. // Continue if buffer is starving or if current time is behind max latency
  9833. const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  9834. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  9835. if (!this.loadedmetadata) {
  9836. this.nextLoadPosition = liveSyncPosition;
  9837. }
  9838. // Only seek if ready and there is not a significant forward buffer available for playback
  9839. if (media.readyState) {
  9840. this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);
  9841. media.currentTime = liveSyncPosition;
  9842. }
  9843. }
  9844. }
  9845. }
  9846. alignPlaylists(details, previousDetails, switchDetails) {
  9847. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  9848. // this could all go in level-helper mergeDetails()
  9849. const length = details.fragments.length;
  9850. if (!length) {
  9851. this.warn(`No fragments in live playlist`);
  9852. return 0;
  9853. }
  9854. const slidingStart = details.fragments[0].start;
  9855. const firstLevelLoad = !previousDetails;
  9856. const aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  9857. if (firstLevelLoad || !aligned && !slidingStart) {
  9858. const {
  9859. fragPrevious
  9860. } = this;
  9861. alignStream(fragPrevious, switchDetails, details);
  9862. const alignedSlidingStart = details.fragments[0].start;
  9863. this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} prev-sn: ${fragPrevious ? fragPrevious.sn : 'na'} fragments: ${length}`);
  9864. return alignedSlidingStart;
  9865. }
  9866. return slidingStart;
  9867. }
  9868. waitForCdnTuneIn(details) {
  9869. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  9870. const advancePartLimit = 3;
  9871. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  9872. }
  9873. setStartPosition(details, sliding) {
  9874. // compute start position if set to -1. use it straight away if value is defined
  9875. let startPosition = this.startPosition;
  9876. if (startPosition < sliding) {
  9877. startPosition = -1;
  9878. }
  9879. if (startPosition === -1 || this.lastCurrentTime === -1) {
  9880. // Use Playlist EXT-X-START:TIME-OFFSET when set
  9881. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  9882. const offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  9883. const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  9884. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  9885. startPosition = sliding + startTimeOffset;
  9886. if (startTimeOffset < 0) {
  9887. startPosition += details.totalduration;
  9888. }
  9889. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  9890. this.log(`Start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist, adjust startPosition to ${startPosition}`);
  9891. this.startPosition = startPosition;
  9892. } else if (details.live) {
  9893. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  9894. // not been specified via the config or an as an argument to startLoad (#3736).
  9895. startPosition = this.hls.liveSyncPosition || sliding;
  9896. } else {
  9897. this.startPosition = startPosition = 0;
  9898. }
  9899. this.lastCurrentTime = startPosition;
  9900. }
  9901. this.nextLoadPosition = startPosition;
  9902. }
  9903. getLoadPosition() {
  9904. const {
  9905. media
  9906. } = this;
  9907. // if we have not yet loaded any fragment, start loading from start position
  9908. let pos = 0;
  9909. if (this.loadedmetadata && media) {
  9910. pos = media.currentTime;
  9911. } else if (this.nextLoadPosition) {
  9912. pos = this.nextLoadPosition;
  9913. }
  9914. return pos;
  9915. }
  9916. handleFragLoadAborted(frag, part) {
  9917. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  9918. this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${frag.level} was aborted`);
  9919. this.resetFragmentLoading(frag);
  9920. }
  9921. }
  9922. resetFragmentLoading(frag) {
  9923. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  9924. this.state = State.IDLE;
  9925. }
  9926. }
  9927. onFragmentOrKeyLoadError(filterType, data) {
  9928. if (data.chunkMeta && !data.frag) {
  9929. const context = this.getCurrentContext(data.chunkMeta);
  9930. if (context) {
  9931. data.frag = context.frag;
  9932. }
  9933. }
  9934. const frag = data.frag;
  9935. // Handle frag error related to caller's filterType
  9936. if (!frag || frag.type !== filterType || !this.levels) {
  9937. return;
  9938. }
  9939. if (this.fragContextChanged(frag)) {
  9940. var _this$fragCurrent2;
  9941. this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url}`);
  9942. return;
  9943. }
  9944. const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  9945. if (gapTagEncountered) {
  9946. this.fragmentTracker.fragBuffered(frag, true);
  9947. }
  9948. // keep retrying until the limit will be reached
  9949. const errorAction = data.errorAction;
  9950. const {
  9951. action,
  9952. retryCount = 0,
  9953. retryConfig
  9954. } = errorAction || {};
  9955. if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) {
  9956. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  9957. const delay = getRetryDelay(retryConfig, retryCount);
  9958. this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);
  9959. errorAction.resolved = true;
  9960. this.retryDate = self.performance.now() + delay;
  9961. this.state = State.FRAG_LOADING_WAITING_RETRY;
  9962. } else if (retryConfig && errorAction) {
  9963. this.resetFragmentErrors(filterType);
  9964. if (retryCount < retryConfig.maxNumRetry) {
  9965. // Network retry is skipped when level switch is preferred
  9966. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  9967. errorAction.resolved = true;
  9968. }
  9969. } else {
  9970. logger.warn(`${data.details} reached or exceeded max retry (${retryCount})`);
  9971. return;
  9972. }
  9973. } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) {
  9974. this.state = State.WAITING_LEVEL;
  9975. } else {
  9976. this.state = State.ERROR;
  9977. }
  9978. // Perform next async tick sooner to speed up error action resolution
  9979. this.tickImmediate();
  9980. }
  9981. reduceLengthAndFlushBuffer(data) {
  9982. // if in appending state
  9983. if (this.state === State.PARSING || this.state === State.PARSED) {
  9984. const playlistType = data.parent;
  9985. const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  9986. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  9987. // reduce max buf len if current position is buffered
  9988. const buffered = bufferedInfo && bufferedInfo.len > 0.5;
  9989. if (buffered) {
  9990. this.reduceMaxBufferLength(bufferedInfo.len);
  9991. }
  9992. const flushBuffer = !buffered;
  9993. if (flushBuffer) {
  9994. // current position is not buffered, but browser is still complaining about buffer full error
  9995. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  9996. // in that case flush the whole audio buffer to recover
  9997. this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);
  9998. }
  9999. if (data.frag) {
  10000. this.fragmentTracker.removeFragment(data.frag);
  10001. this.nextLoadPosition = data.frag.start;
  10002. }
  10003. this.resetLoadingState();
  10004. return flushBuffer;
  10005. }
  10006. return false;
  10007. }
  10008. resetFragmentErrors(filterType) {
  10009. if (filterType === PlaylistLevelType.AUDIO) {
  10010. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  10011. this.fragCurrent = null;
  10012. }
  10013. // Fragment errors that result in a level switch or redundant fail-over
  10014. // should reset the stream controller state to idle
  10015. if (!this.loadedmetadata) {
  10016. this.startFragRequested = false;
  10017. }
  10018. if (this.state !== State.STOPPED) {
  10019. this.state = State.IDLE;
  10020. }
  10021. }
  10022. afterBufferFlushed(media, bufferType, playlistType) {
  10023. if (!media) {
  10024. return;
  10025. }
  10026. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  10027. // (so that we will check against video.buffered ranges in case of alt audio track)
  10028. const bufferedTimeRanges = BufferHelper.getBuffered(media);
  10029. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  10030. if (this.state === State.ENDED) {
  10031. this.resetLoadingState();
  10032. }
  10033. }
  10034. resetLoadingState() {
  10035. this.log('Reset loading state');
  10036. this.fragCurrent = null;
  10037. this.fragPrevious = null;
  10038. this.state = State.IDLE;
  10039. }
  10040. resetStartWhenNotLoaded(level) {
  10041. // if loadedmetadata is not set, it means that first frag request failed
  10042. // in that case, reset startFragRequested flag
  10043. if (!this.loadedmetadata) {
  10044. this.startFragRequested = false;
  10045. const details = level ? level.details : null;
  10046. if (details != null && details.live) {
  10047. // Update the start position and return to IDLE to recover live start
  10048. this.startPosition = -1;
  10049. this.setStartPosition(details, 0);
  10050. this.resetLoadingState();
  10051. } else {
  10052. this.nextLoadPosition = this.startPosition;
  10053. }
  10054. }
  10055. }
  10056. resetWhenMissingContext(chunkMeta) {
  10057. this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`);
  10058. this.removeUnbufferedFrags();
  10059. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10060. this.resetLoadingState();
  10061. }
  10062. removeUnbufferedFrags(start = 0) {
  10063. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  10064. }
  10065. updateLevelTiming(frag, part, level, partial) {
  10066. var _this$transmuxer;
  10067. const details = level.details;
  10068. if (!details) {
  10069. this.warn('level.details undefined');
  10070. return;
  10071. }
  10072. const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {
  10073. const info = frag.elementaryStreams[type];
  10074. if (info) {
  10075. const parsedDuration = info.endPTS - info.startPTS;
  10076. if (parsedDuration <= 0) {
  10077. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  10078. // The new transmuxer will be configured with a time offset matching the next fragment start,
  10079. // preventing the timeline from shifting.
  10080. this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);
  10081. return result || false;
  10082. }
  10083. const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  10084. this.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  10085. details,
  10086. level,
  10087. drift,
  10088. type,
  10089. frag,
  10090. start: info.startPTS,
  10091. end: info.endPTS
  10092. });
  10093. return true;
  10094. }
  10095. return result;
  10096. }, false);
  10097. if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  10098. const error = new Error(`Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`);
  10099. if (level.fragmentError === 0) {
  10100. // Mark and track the odd empty segment as a gap to avoid reloading
  10101. level.fragmentError++;
  10102. frag.gap = true;
  10103. this.fragmentTracker.removeFragment(frag);
  10104. this.fragmentTracker.fragBuffered(frag, true);
  10105. }
  10106. this.warn(error.message);
  10107. this.hls.trigger(Events.ERROR, {
  10108. type: ErrorTypes.MEDIA_ERROR,
  10109. details: ErrorDetails.FRAG_PARSING_ERROR,
  10110. fatal: false,
  10111. error,
  10112. frag,
  10113. reason: `Found no media in msn ${frag.sn} of level "${level.url}"`
  10114. });
  10115. if (!this.hls) {
  10116. return;
  10117. }
  10118. this.resetTransmuxer();
  10119. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  10120. }
  10121. this.state = State.PARSED;
  10122. this.hls.trigger(Events.FRAG_PARSED, {
  10123. frag,
  10124. part
  10125. });
  10126. }
  10127. resetTransmuxer() {
  10128. if (this.transmuxer) {
  10129. this.transmuxer.destroy();
  10130. this.transmuxer = null;
  10131. }
  10132. }
  10133. recoverWorkerError(data) {
  10134. if (data.event === 'demuxerWorker') {
  10135. this.fragmentTracker.removeAllFragments();
  10136. this.resetTransmuxer();
  10137. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10138. this.resetLoadingState();
  10139. }
  10140. }
  10141. set state(nextState) {
  10142. const previousState = this._state;
  10143. if (previousState !== nextState) {
  10144. this._state = nextState;
  10145. this.log(`${previousState}->${nextState}`);
  10146. }
  10147. }
  10148. get state() {
  10149. return this._state;
  10150. }
  10151. }
  10152. class ChunkCache {
  10153. constructor() {
  10154. this.chunks = [];
  10155. this.dataLength = 0;
  10156. }
  10157. push(chunk) {
  10158. this.chunks.push(chunk);
  10159. this.dataLength += chunk.length;
  10160. }
  10161. flush() {
  10162. const {
  10163. chunks,
  10164. dataLength
  10165. } = this;
  10166. let result;
  10167. if (!chunks.length) {
  10168. return new Uint8Array(0);
  10169. } else if (chunks.length === 1) {
  10170. result = chunks[0];
  10171. } else {
  10172. result = concatUint8Arrays(chunks, dataLength);
  10173. }
  10174. this.reset();
  10175. return result;
  10176. }
  10177. reset() {
  10178. this.chunks.length = 0;
  10179. this.dataLength = 0;
  10180. }
  10181. }
  10182. function concatUint8Arrays(chunks, dataLength) {
  10183. const result = new Uint8Array(dataLength);
  10184. let offset = 0;
  10185. for (let i = 0; i < chunks.length; i++) {
  10186. const chunk = chunks[i];
  10187. result.set(chunk, offset);
  10188. offset += chunk.length;
  10189. }
  10190. return result;
  10191. }
  10192. // ensure the worker ends up in the bundle
  10193. // If the worker should not be included this gets aliased to empty.js
  10194. function hasUMDWorker() {
  10195. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  10196. }
  10197. function injectWorker() {
  10198. const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {
  10199. type: 'text/javascript'
  10200. });
  10201. const objectURL = self.URL.createObjectURL(blob);
  10202. const worker = new self.Worker(objectURL);
  10203. return {
  10204. worker,
  10205. objectURL
  10206. };
  10207. }
  10208. function loadWorker(path) {
  10209. const scriptURL = new self.URL(path, self.location.href).href;
  10210. const worker = new self.Worker(scriptURL);
  10211. return {
  10212. worker,
  10213. scriptURL
  10214. };
  10215. }
  10216. function dummyTrack(type = '', inputTimeScale = 90000) {
  10217. return {
  10218. type,
  10219. id: -1,
  10220. pid: -1,
  10221. inputTimeScale,
  10222. sequenceNumber: -1,
  10223. samples: [],
  10224. dropped: 0
  10225. };
  10226. }
  10227. class BaseAudioDemuxer {
  10228. constructor() {
  10229. this._audioTrack = void 0;
  10230. this._id3Track = void 0;
  10231. this.frameIndex = 0;
  10232. this.cachedData = null;
  10233. this.basePTS = null;
  10234. this.initPTS = null;
  10235. this.lastPTS = null;
  10236. }
  10237. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10238. this._id3Track = {
  10239. type: 'id3',
  10240. id: 3,
  10241. pid: -1,
  10242. inputTimeScale: 90000,
  10243. sequenceNumber: 0,
  10244. samples: [],
  10245. dropped: 0
  10246. };
  10247. }
  10248. resetTimeStamp(deaultTimestamp) {
  10249. this.initPTS = deaultTimestamp;
  10250. this.resetContiguity();
  10251. }
  10252. resetContiguity() {
  10253. this.basePTS = null;
  10254. this.lastPTS = null;
  10255. this.frameIndex = 0;
  10256. }
  10257. canParse(data, offset) {
  10258. return false;
  10259. }
  10260. appendFrame(track, data, offset) {}
  10261. // feed incoming data to the front of the parsing pipeline
  10262. demux(data, timeOffset) {
  10263. if (this.cachedData) {
  10264. data = appendUint8Array(this.cachedData, data);
  10265. this.cachedData = null;
  10266. }
  10267. let id3Data = getID3Data(data, 0);
  10268. let offset = id3Data ? id3Data.length : 0;
  10269. let lastDataIndex;
  10270. const track = this._audioTrack;
  10271. const id3Track = this._id3Track;
  10272. const timestamp = id3Data ? getTimeStamp(id3Data) : undefined;
  10273. const length = data.length;
  10274. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  10275. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  10276. this.lastPTS = this.basePTS;
  10277. }
  10278. if (this.lastPTS === null) {
  10279. this.lastPTS = this.basePTS;
  10280. }
  10281. // more expressive than alternative: id3Data?.length
  10282. if (id3Data && id3Data.length > 0) {
  10283. id3Track.samples.push({
  10284. pts: this.lastPTS,
  10285. dts: this.lastPTS,
  10286. data: id3Data,
  10287. type: MetadataSchema.audioId3,
  10288. duration: Number.POSITIVE_INFINITY
  10289. });
  10290. }
  10291. while (offset < length) {
  10292. if (this.canParse(data, offset)) {
  10293. const frame = this.appendFrame(track, data, offset);
  10294. if (frame) {
  10295. this.frameIndex++;
  10296. this.lastPTS = frame.sample.pts;
  10297. offset += frame.length;
  10298. lastDataIndex = offset;
  10299. } else {
  10300. offset = length;
  10301. }
  10302. } else if (canParse$2(data, offset)) {
  10303. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  10304. id3Data = getID3Data(data, offset);
  10305. id3Track.samples.push({
  10306. pts: this.lastPTS,
  10307. dts: this.lastPTS,
  10308. data: id3Data,
  10309. type: MetadataSchema.audioId3,
  10310. duration: Number.POSITIVE_INFINITY
  10311. });
  10312. offset += id3Data.length;
  10313. lastDataIndex = offset;
  10314. } else {
  10315. offset++;
  10316. }
  10317. if (offset === length && lastDataIndex !== length) {
  10318. const partialData = sliceUint8(data, lastDataIndex);
  10319. if (this.cachedData) {
  10320. this.cachedData = appendUint8Array(this.cachedData, partialData);
  10321. } else {
  10322. this.cachedData = partialData;
  10323. }
  10324. }
  10325. }
  10326. return {
  10327. audioTrack: track,
  10328. videoTrack: dummyTrack(),
  10329. id3Track,
  10330. textTrack: dummyTrack()
  10331. };
  10332. }
  10333. demuxSampleAes(data, keyData, timeOffset) {
  10334. return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));
  10335. }
  10336. flush(timeOffset) {
  10337. // Parse cache in case of remaining frames.
  10338. const cachedData = this.cachedData;
  10339. if (cachedData) {
  10340. this.cachedData = null;
  10341. this.demux(cachedData, 0);
  10342. }
  10343. return {
  10344. audioTrack: this._audioTrack,
  10345. videoTrack: dummyTrack(),
  10346. id3Track: this._id3Track,
  10347. textTrack: dummyTrack()
  10348. };
  10349. }
  10350. destroy() {}
  10351. }
  10352. /**
  10353. * Initialize PTS
  10354. * <p>
  10355. * use timestamp unless it is undefined, NaN or Infinity
  10356. * </p>
  10357. */
  10358. const initPTSFn = (timestamp, timeOffset, initPTS) => {
  10359. if (isFiniteNumber(timestamp)) {
  10360. return timestamp * 90;
  10361. }
  10362. const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  10363. return timeOffset * 90000 + init90kHz;
  10364. };
  10365. /**
  10366. * ADTS parser helper
  10367. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  10368. */
  10369. function getAudioConfig(observer, data, offset, audioCodec) {
  10370. let adtsObjectType;
  10371. let adtsExtensionSamplingIndex;
  10372. let adtsChannelConfig;
  10373. let config;
  10374. const userAgent = navigator.userAgent.toLowerCase();
  10375. const manifestCodec = audioCodec;
  10376. const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  10377. // byte 2
  10378. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  10379. const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  10380. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  10381. const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);
  10382. observer.emit(Events.ERROR, Events.ERROR, {
  10383. type: ErrorTypes.MEDIA_ERROR,
  10384. details: ErrorDetails.FRAG_PARSING_ERROR,
  10385. fatal: true,
  10386. error,
  10387. reason: error.message
  10388. });
  10389. return;
  10390. }
  10391. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  10392. // byte 3
  10393. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  10394. logger.log(`manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`);
  10395. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  10396. if (/firefox/i.test(userAgent)) {
  10397. if (adtsSamplingIndex >= 6) {
  10398. adtsObjectType = 5;
  10399. config = new Array(4);
  10400. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10401. // there is a factor 2 between frame sample rate and output sample rate
  10402. // multiply frequency by 2 (see table below, equivalent to substract 3)
  10403. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  10404. } else {
  10405. adtsObjectType = 2;
  10406. config = new Array(2);
  10407. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10408. }
  10409. // Android : always use AAC
  10410. } else if (userAgent.indexOf('android') !== -1) {
  10411. adtsObjectType = 2;
  10412. config = new Array(2);
  10413. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10414. } else {
  10415. /* for other browsers (Chrome/Vivaldi/Opera ...)
  10416. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  10417. */
  10418. adtsObjectType = 5;
  10419. config = new Array(4);
  10420. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  10421. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  10422. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10423. // there is a factor 2 between frame sample rate and output sample rate
  10424. // multiply frequency by 2 (see table below, equivalent to substract 3)
  10425. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  10426. } else {
  10427. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  10428. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  10429. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  10430. adtsObjectType = 2;
  10431. config = new Array(2);
  10432. }
  10433. adtsExtensionSamplingIndex = adtsSamplingIndex;
  10434. }
  10435. }
  10436. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  10437. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  10438. Audio Profile / Audio Object Type
  10439. 0: Null
  10440. 1: AAC Main
  10441. 2: AAC LC (Low Complexity)
  10442. 3: AAC SSR (Scalable Sample Rate)
  10443. 4: AAC LTP (Long Term Prediction)
  10444. 5: SBR (Spectral Band Replication)
  10445. 6: AAC Scalable
  10446. sampling freq
  10447. 0: 96000 Hz
  10448. 1: 88200 Hz
  10449. 2: 64000 Hz
  10450. 3: 48000 Hz
  10451. 4: 44100 Hz
  10452. 5: 32000 Hz
  10453. 6: 24000 Hz
  10454. 7: 22050 Hz
  10455. 8: 16000 Hz
  10456. 9: 12000 Hz
  10457. 10: 11025 Hz
  10458. 11: 8000 Hz
  10459. 12: 7350 Hz
  10460. 13: Reserved
  10461. 14: Reserved
  10462. 15: frequency is written explictly
  10463. Channel Configurations
  10464. These are the channel configurations:
  10465. 0: Defined in AOT Specifc Config
  10466. 1: 1 channel: front-center
  10467. 2: 2 channels: front-left, front-right
  10468. */
  10469. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  10470. config[0] = adtsObjectType << 3;
  10471. // samplingFrequencyIndex
  10472. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  10473. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  10474. // channelConfiguration
  10475. config[1] |= adtsChannelConfig << 3;
  10476. if (adtsObjectType === 5) {
  10477. // adtsExtensionSamplingIndex
  10478. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  10479. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  10480. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  10481. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  10482. config[2] |= 2 << 2;
  10483. config[3] = 0;
  10484. }
  10485. return {
  10486. config,
  10487. samplerate: adtsSamplingRates[adtsSamplingIndex],
  10488. channelCount: adtsChannelConfig,
  10489. codec: 'mp4a.40.' + adtsObjectType,
  10490. manifestCodec
  10491. };
  10492. }
  10493. function isHeaderPattern$1(data, offset) {
  10494. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  10495. }
  10496. function getHeaderLength(data, offset) {
  10497. return data[offset + 1] & 0x01 ? 7 : 9;
  10498. }
  10499. function getFullFrameLength(data, offset) {
  10500. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  10501. }
  10502. function canGetFrameLength(data, offset) {
  10503. return offset + 5 < data.length;
  10504. }
  10505. function isHeader$1(data, offset) {
  10506. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10507. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10508. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10509. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  10510. }
  10511. function canParse$1(data, offset) {
  10512. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  10513. }
  10514. function probe$1(data, offset) {
  10515. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  10516. // or end of data is reached
  10517. if (isHeader$1(data, offset)) {
  10518. // ADTS header Length
  10519. const headerLength = getHeaderLength(data, offset);
  10520. if (offset + headerLength >= data.length) {
  10521. return false;
  10522. }
  10523. // ADTS frame Length
  10524. const frameLength = getFullFrameLength(data, offset);
  10525. if (frameLength <= headerLength) {
  10526. return false;
  10527. }
  10528. const newOffset = offset + frameLength;
  10529. return newOffset === data.length || isHeader$1(data, newOffset);
  10530. }
  10531. return false;
  10532. }
  10533. function initTrackConfig(track, observer, data, offset, audioCodec) {
  10534. if (!track.samplerate) {
  10535. const config = getAudioConfig(observer, data, offset, audioCodec);
  10536. if (!config) {
  10537. return;
  10538. }
  10539. track.config = config.config;
  10540. track.samplerate = config.samplerate;
  10541. track.channelCount = config.channelCount;
  10542. track.codec = config.codec;
  10543. track.manifestCodec = config.manifestCodec;
  10544. logger.log(`parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`);
  10545. }
  10546. }
  10547. function getFrameDuration(samplerate) {
  10548. return 1024 * 90000 / samplerate;
  10549. }
  10550. function parseFrameHeader(data, offset) {
  10551. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  10552. const headerLength = getHeaderLength(data, offset);
  10553. if (offset + headerLength <= data.length) {
  10554. // retrieve frame size
  10555. const frameLength = getFullFrameLength(data, offset) - headerLength;
  10556. if (frameLength > 0) {
  10557. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  10558. return {
  10559. headerLength,
  10560. frameLength
  10561. };
  10562. }
  10563. }
  10564. }
  10565. function appendFrame$2(track, data, offset, pts, frameIndex) {
  10566. const frameDuration = getFrameDuration(track.samplerate);
  10567. const stamp = pts + frameIndex * frameDuration;
  10568. const header = parseFrameHeader(data, offset);
  10569. let unit;
  10570. if (header) {
  10571. const {
  10572. frameLength,
  10573. headerLength
  10574. } = header;
  10575. const _length = headerLength + frameLength;
  10576. const missing = Math.max(0, offset + _length - data.length);
  10577. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  10578. if (missing) {
  10579. unit = new Uint8Array(_length - headerLength);
  10580. unit.set(data.subarray(offset + headerLength, data.length), 0);
  10581. } else {
  10582. unit = data.subarray(offset + headerLength, offset + _length);
  10583. }
  10584. const _sample = {
  10585. unit,
  10586. pts: stamp
  10587. };
  10588. if (!missing) {
  10589. track.samples.push(_sample);
  10590. }
  10591. return {
  10592. sample: _sample,
  10593. length: _length,
  10594. missing
  10595. };
  10596. }
  10597. // overflow incomplete header
  10598. const length = data.length - offset;
  10599. unit = new Uint8Array(length);
  10600. unit.set(data.subarray(offset, data.length), 0);
  10601. const sample = {
  10602. unit,
  10603. pts: stamp
  10604. };
  10605. return {
  10606. sample,
  10607. length,
  10608. missing: -1
  10609. };
  10610. }
  10611. /**
  10612. * MPEG parser helper
  10613. */
  10614. let chromeVersion$1 = null;
  10615. 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];
  10616. const SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  10617. const SamplesCoefficients = [
  10618. // MPEG 2.5
  10619. [0,
  10620. // Reserved
  10621. 72,
  10622. // Layer3
  10623. 144,
  10624. // Layer2
  10625. 12 // Layer1
  10626. ],
  10627. // Reserved
  10628. [0,
  10629. // Reserved
  10630. 0,
  10631. // Layer3
  10632. 0,
  10633. // Layer2
  10634. 0 // Layer1
  10635. ],
  10636. // MPEG 2
  10637. [0,
  10638. // Reserved
  10639. 72,
  10640. // Layer3
  10641. 144,
  10642. // Layer2
  10643. 12 // Layer1
  10644. ],
  10645. // MPEG 1
  10646. [0,
  10647. // Reserved
  10648. 144,
  10649. // Layer3
  10650. 144,
  10651. // Layer2
  10652. 12 // Layer1
  10653. ]];
  10654. const BytesInSlot = [0,
  10655. // Reserved
  10656. 1,
  10657. // Layer3
  10658. 1,
  10659. // Layer2
  10660. 4 // Layer1
  10661. ];
  10662. function appendFrame$1(track, data, offset, pts, frameIndex) {
  10663. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  10664. if (offset + 24 > data.length) {
  10665. return;
  10666. }
  10667. const header = parseHeader(data, offset);
  10668. if (header && offset + header.frameLength <= data.length) {
  10669. const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  10670. const stamp = pts + frameIndex * frameDuration;
  10671. const sample = {
  10672. unit: data.subarray(offset, offset + header.frameLength),
  10673. pts: stamp,
  10674. dts: stamp
  10675. };
  10676. track.config = [];
  10677. track.channelCount = header.channelCount;
  10678. track.samplerate = header.sampleRate;
  10679. track.samples.push(sample);
  10680. return {
  10681. sample,
  10682. length: header.frameLength,
  10683. missing: 0
  10684. };
  10685. }
  10686. }
  10687. function parseHeader(data, offset) {
  10688. const mpegVersion = data[offset + 1] >> 3 & 3;
  10689. const mpegLayer = data[offset + 1] >> 1 & 3;
  10690. const bitRateIndex = data[offset + 2] >> 4 & 15;
  10691. const sampleRateIndex = data[offset + 2] >> 2 & 3;
  10692. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  10693. const paddingBit = data[offset + 2] >> 1 & 1;
  10694. const channelMode = data[offset + 3] >> 6;
  10695. const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  10696. const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  10697. const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  10698. const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  10699. const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  10700. const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  10701. const bytesInSlot = BytesInSlot[mpegLayer];
  10702. const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  10703. const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  10704. if (chromeVersion$1 === null) {
  10705. const userAgent = navigator.userAgent || '';
  10706. const result = userAgent.match(/Chrome\/(\d+)/i);
  10707. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  10708. }
  10709. const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  10710. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  10711. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  10712. data[offset + 3] = data[offset + 3] | 0x80;
  10713. }
  10714. return {
  10715. sampleRate,
  10716. channelCount,
  10717. frameLength,
  10718. samplesPerFrame
  10719. };
  10720. }
  10721. }
  10722. function isHeaderPattern(data, offset) {
  10723. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  10724. }
  10725. function isHeader(data, offset) {
  10726. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10727. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10728. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10729. return offset + 1 < data.length && isHeaderPattern(data, offset);
  10730. }
  10731. function canParse(data, offset) {
  10732. const headerSize = 4;
  10733. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  10734. }
  10735. function probe(data, offset) {
  10736. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  10737. // or end of data is reached
  10738. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  10739. // MPEG header Length
  10740. const headerLength = 4;
  10741. // MPEG frame Length
  10742. const header = parseHeader(data, offset);
  10743. let frameLength = headerLength;
  10744. if (header != null && header.frameLength) {
  10745. frameLength = header.frameLength;
  10746. }
  10747. const newOffset = offset + frameLength;
  10748. return newOffset === data.length || isHeader(data, newOffset);
  10749. }
  10750. return false;
  10751. }
  10752. /**
  10753. * AAC demuxer
  10754. */
  10755. class AACDemuxer extends BaseAudioDemuxer {
  10756. constructor(observer, config) {
  10757. super();
  10758. this.observer = void 0;
  10759. this.config = void 0;
  10760. this.observer = observer;
  10761. this.config = config;
  10762. }
  10763. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10764. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10765. this._audioTrack = {
  10766. container: 'audio/adts',
  10767. type: 'audio',
  10768. id: 2,
  10769. pid: -1,
  10770. sequenceNumber: 0,
  10771. segmentCodec: 'aac',
  10772. samples: [],
  10773. manifestCodec: audioCodec,
  10774. duration: trackDuration,
  10775. inputTimeScale: 90000,
  10776. dropped: 0
  10777. };
  10778. }
  10779. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  10780. static probe(data) {
  10781. if (!data) {
  10782. return false;
  10783. }
  10784. // Check for the ADTS sync word
  10785. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10786. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10787. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10788. const id3Data = getID3Data(data, 0);
  10789. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10790. if (probe(data, offset)) {
  10791. return false;
  10792. }
  10793. for (let length = data.length; offset < length; offset++) {
  10794. if (probe$1(data, offset)) {
  10795. logger.log('ADTS sync word found !');
  10796. return true;
  10797. }
  10798. }
  10799. return false;
  10800. }
  10801. canParse(data, offset) {
  10802. return canParse$1(data, offset);
  10803. }
  10804. appendFrame(track, data, offset) {
  10805. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  10806. const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);
  10807. if (frame && frame.missing === 0) {
  10808. return frame;
  10809. }
  10810. }
  10811. }
  10812. const emsgSchemePattern = /\/emsg[-/]ID3/i;
  10813. class MP4Demuxer {
  10814. constructor(observer, config) {
  10815. this.remainderData = null;
  10816. this.timeOffset = 0;
  10817. this.config = void 0;
  10818. this.videoTrack = void 0;
  10819. this.audioTrack = void 0;
  10820. this.id3Track = void 0;
  10821. this.txtTrack = void 0;
  10822. this.config = config;
  10823. }
  10824. resetTimeStamp() {}
  10825. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10826. const videoTrack = this.videoTrack = dummyTrack('video', 1);
  10827. const audioTrack = this.audioTrack = dummyTrack('audio', 1);
  10828. const captionTrack = this.txtTrack = dummyTrack('text', 1);
  10829. this.id3Track = dummyTrack('id3', 1);
  10830. this.timeOffset = 0;
  10831. if (!(initSegment != null && initSegment.byteLength)) {
  10832. return;
  10833. }
  10834. const initData = parseInitSegment(initSegment);
  10835. if (initData.video) {
  10836. const {
  10837. id,
  10838. timescale,
  10839. codec
  10840. } = initData.video;
  10841. videoTrack.id = id;
  10842. videoTrack.timescale = captionTrack.timescale = timescale;
  10843. videoTrack.codec = codec;
  10844. }
  10845. if (initData.audio) {
  10846. const {
  10847. id,
  10848. timescale,
  10849. codec
  10850. } = initData.audio;
  10851. audioTrack.id = id;
  10852. audioTrack.timescale = timescale;
  10853. audioTrack.codec = codec;
  10854. }
  10855. captionTrack.id = RemuxerTrackIdConfig.text;
  10856. videoTrack.sampleDuration = 0;
  10857. videoTrack.duration = audioTrack.duration = trackDuration;
  10858. }
  10859. resetContiguity() {
  10860. this.remainderData = null;
  10861. }
  10862. static probe(data) {
  10863. return hasMoofData(data);
  10864. }
  10865. demux(data, timeOffset) {
  10866. this.timeOffset = timeOffset;
  10867. // 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
  10868. let videoSamples = data;
  10869. const videoTrack = this.videoTrack;
  10870. const textTrack = this.txtTrack;
  10871. if (this.config.progressive) {
  10872. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  10873. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  10874. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  10875. if (this.remainderData) {
  10876. videoSamples = appendUint8Array(this.remainderData, data);
  10877. }
  10878. const segmentedData = segmentValidRange(videoSamples);
  10879. this.remainderData = segmentedData.remainder;
  10880. videoTrack.samples = segmentedData.valid || new Uint8Array();
  10881. } else {
  10882. videoTrack.samples = videoSamples;
  10883. }
  10884. const id3Track = this.extractID3Track(videoTrack, timeOffset);
  10885. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10886. return {
  10887. videoTrack,
  10888. audioTrack: this.audioTrack,
  10889. id3Track,
  10890. textTrack: this.txtTrack
  10891. };
  10892. }
  10893. flush() {
  10894. const timeOffset = this.timeOffset;
  10895. const videoTrack = this.videoTrack;
  10896. const textTrack = this.txtTrack;
  10897. videoTrack.samples = this.remainderData || new Uint8Array();
  10898. this.remainderData = null;
  10899. const id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  10900. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10901. return {
  10902. videoTrack,
  10903. audioTrack: dummyTrack(),
  10904. id3Track,
  10905. textTrack: dummyTrack()
  10906. };
  10907. }
  10908. extractID3Track(videoTrack, timeOffset) {
  10909. const id3Track = this.id3Track;
  10910. if (videoTrack.samples.length) {
  10911. const emsgs = findBox(videoTrack.samples, ['emsg']);
  10912. if (emsgs) {
  10913. emsgs.forEach(data => {
  10914. const emsgInfo = parseEmsg(data);
  10915. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  10916. const pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  10917. let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  10918. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  10919. if (duration <= 0.001) {
  10920. duration = Number.POSITIVE_INFINITY;
  10921. }
  10922. const payload = emsgInfo.payload;
  10923. id3Track.samples.push({
  10924. data: payload,
  10925. len: payload.byteLength,
  10926. dts: pts,
  10927. pts: pts,
  10928. type: MetadataSchema.emsg,
  10929. duration: duration
  10930. });
  10931. }
  10932. });
  10933. }
  10934. }
  10935. return id3Track;
  10936. }
  10937. demuxSampleAes(data, keyData, timeOffset) {
  10938. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  10939. }
  10940. destroy() {}
  10941. }
  10942. const getAudioBSID = (data, offset) => {
  10943. // check the bsid to confirm ac-3 | ec-3
  10944. let bsid = 0;
  10945. let numBits = 5;
  10946. offset += numBits;
  10947. const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  10948. const mask = new Uint32Array(1); // unsigned 32 bit mask value
  10949. const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  10950. while (numBits > 0) {
  10951. byte[0] = data[offset];
  10952. // read remaining bits, upto 8 bits at a time
  10953. const bits = Math.min(numBits, 8);
  10954. const shift = 8 - bits;
  10955. mask[0] = 0xff000000 >>> 24 + shift << shift;
  10956. temp[0] = (byte[0] & mask[0]) >> shift;
  10957. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  10958. offset += 1;
  10959. numBits -= bits;
  10960. }
  10961. return bsid;
  10962. };
  10963. class AC3Demuxer extends BaseAudioDemuxer {
  10964. constructor(observer) {
  10965. super();
  10966. this.observer = void 0;
  10967. this.observer = observer;
  10968. }
  10969. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10970. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  10971. this._audioTrack = {
  10972. container: 'audio/ac-3',
  10973. type: 'audio',
  10974. id: 2,
  10975. pid: -1,
  10976. sequenceNumber: 0,
  10977. segmentCodec: 'ac3',
  10978. samples: [],
  10979. manifestCodec: audioCodec,
  10980. duration: trackDuration,
  10981. inputTimeScale: 90000,
  10982. dropped: 0
  10983. };
  10984. }
  10985. canParse(data, offset) {
  10986. return offset + 64 < data.length;
  10987. }
  10988. appendFrame(track, data, offset) {
  10989. const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  10990. if (frameLength !== -1) {
  10991. const sample = track.samples[track.samples.length - 1];
  10992. return {
  10993. sample,
  10994. length: frameLength,
  10995. missing: 0
  10996. };
  10997. }
  10998. }
  10999. static probe(data) {
  11000. if (!data) {
  11001. return false;
  11002. }
  11003. const id3Data = getID3Data(data, 0);
  11004. if (!id3Data) {
  11005. return false;
  11006. }
  11007. // look for the ac-3 sync bytes
  11008. const offset = id3Data.length;
  11009. if (data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  11010. // check the bsid to confirm ac-3
  11011. getAudioBSID(data, offset) < 16) {
  11012. return true;
  11013. }
  11014. return false;
  11015. }
  11016. }
  11017. function appendFrame(track, data, start, pts, frameIndex) {
  11018. if (start + 8 > data.length) {
  11019. return -1; // not enough bytes left
  11020. }
  11021. if (data[start] !== 0x0b || data[start + 1] !== 0x77) {
  11022. return -1; // invalid magic
  11023. }
  11024. // get sample rate
  11025. const samplingRateCode = data[start + 4] >> 6;
  11026. if (samplingRateCode >= 3) {
  11027. return -1; // invalid sampling rate
  11028. }
  11029. const samplingRateMap = [48000, 44100, 32000];
  11030. const sampleRate = samplingRateMap[samplingRateCode];
  11031. // get frame size
  11032. const frameSizeCode = data[start + 4] & 0x3f;
  11033. 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];
  11034. const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  11035. if (start + frameLength > data.length) {
  11036. return -1;
  11037. }
  11038. // get channel count
  11039. const channelMode = data[start + 6] >> 5;
  11040. let skipCount = 0;
  11041. if (channelMode === 2) {
  11042. skipCount += 2;
  11043. } else {
  11044. if (channelMode & 1 && channelMode !== 1) {
  11045. skipCount += 2;
  11046. }
  11047. if (channelMode & 4) {
  11048. skipCount += 2;
  11049. }
  11050. }
  11051. const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  11052. const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  11053. const channelCount = channelsMap[channelMode] + lfeon;
  11054. // build dac3 box
  11055. const bsid = data[start + 5] >> 3;
  11056. const bsmod = data[start + 5] & 7;
  11057. const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 0xe0]);
  11058. const frameDuration = 1536 / sampleRate * 90000;
  11059. const stamp = pts + frameIndex * frameDuration;
  11060. const unit = data.subarray(start, start + frameLength);
  11061. track.config = config;
  11062. track.channelCount = channelCount;
  11063. track.samplerate = sampleRate;
  11064. track.samples.push({
  11065. unit,
  11066. pts: stamp
  11067. });
  11068. return frameLength;
  11069. }
  11070. class BaseVideoParser {
  11071. constructor() {
  11072. this.VideoSample = null;
  11073. }
  11074. createVideoSample(key, pts, dts, debug) {
  11075. return {
  11076. key,
  11077. frame: false,
  11078. pts,
  11079. dts,
  11080. units: [],
  11081. debug,
  11082. length: 0
  11083. };
  11084. }
  11085. getLastNalUnit(samples) {
  11086. var _VideoSample;
  11087. let VideoSample = this.VideoSample;
  11088. let lastUnit;
  11089. // try to fallback to previous sample if current one is empty
  11090. if (!VideoSample || VideoSample.units.length === 0) {
  11091. VideoSample = samples[samples.length - 1];
  11092. }
  11093. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  11094. const units = VideoSample.units;
  11095. lastUnit = units[units.length - 1];
  11096. }
  11097. return lastUnit;
  11098. }
  11099. pushAccessUnit(VideoSample, videoTrack) {
  11100. if (VideoSample.units.length && VideoSample.frame) {
  11101. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  11102. if (VideoSample.pts === undefined) {
  11103. const samples = videoTrack.samples;
  11104. const nbSamples = samples.length;
  11105. if (nbSamples) {
  11106. const lastSample = samples[nbSamples - 1];
  11107. VideoSample.pts = lastSample.pts;
  11108. VideoSample.dts = lastSample.dts;
  11109. } else {
  11110. // dropping samples, no timestamp found
  11111. videoTrack.dropped++;
  11112. return;
  11113. }
  11114. }
  11115. videoTrack.samples.push(VideoSample);
  11116. }
  11117. if (VideoSample.debug.length) {
  11118. logger.log(VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug);
  11119. }
  11120. }
  11121. }
  11122. /**
  11123. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  11124. */
  11125. class ExpGolomb {
  11126. constructor(data) {
  11127. this.data = void 0;
  11128. this.bytesAvailable = void 0;
  11129. this.word = void 0;
  11130. this.bitsAvailable = void 0;
  11131. this.data = data;
  11132. // the number of bytes left to examine in this.data
  11133. this.bytesAvailable = data.byteLength;
  11134. // the current word being examined
  11135. this.word = 0; // :uint
  11136. // the number of bits left to examine in the current word
  11137. this.bitsAvailable = 0; // :uint
  11138. }
  11139. // ():void
  11140. loadWord() {
  11141. const data = this.data;
  11142. const bytesAvailable = this.bytesAvailable;
  11143. const position = data.byteLength - bytesAvailable;
  11144. const workingBytes = new Uint8Array(4);
  11145. const availableBytes = Math.min(4, bytesAvailable);
  11146. if (availableBytes === 0) {
  11147. throw new Error('no bytes available');
  11148. }
  11149. workingBytes.set(data.subarray(position, position + availableBytes));
  11150. this.word = new DataView(workingBytes.buffer).getUint32(0);
  11151. // track the amount of this.data that has been processed
  11152. this.bitsAvailable = availableBytes * 8;
  11153. this.bytesAvailable -= availableBytes;
  11154. }
  11155. // (count:int):void
  11156. skipBits(count) {
  11157. let skipBytes; // :int
  11158. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  11159. if (this.bitsAvailable > count) {
  11160. this.word <<= count;
  11161. this.bitsAvailable -= count;
  11162. } else {
  11163. count -= this.bitsAvailable;
  11164. skipBytes = count >> 3;
  11165. count -= skipBytes << 3;
  11166. this.bytesAvailable -= skipBytes;
  11167. this.loadWord();
  11168. this.word <<= count;
  11169. this.bitsAvailable -= count;
  11170. }
  11171. }
  11172. // (size:int):uint
  11173. readBits(size) {
  11174. let bits = Math.min(this.bitsAvailable, size); // :uint
  11175. const valu = this.word >>> 32 - bits; // :uint
  11176. if (size > 32) {
  11177. logger.error('Cannot read more than 32 bits at a time');
  11178. }
  11179. this.bitsAvailable -= bits;
  11180. if (this.bitsAvailable > 0) {
  11181. this.word <<= bits;
  11182. } else if (this.bytesAvailable > 0) {
  11183. this.loadWord();
  11184. } else {
  11185. throw new Error('no bits available');
  11186. }
  11187. bits = size - bits;
  11188. if (bits > 0 && this.bitsAvailable) {
  11189. return valu << bits | this.readBits(bits);
  11190. } else {
  11191. return valu;
  11192. }
  11193. }
  11194. // ():uint
  11195. skipLZ() {
  11196. let leadingZeroCount; // :uint
  11197. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  11198. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  11199. // the first bit of working word is 1
  11200. this.word <<= leadingZeroCount;
  11201. this.bitsAvailable -= leadingZeroCount;
  11202. return leadingZeroCount;
  11203. }
  11204. }
  11205. // we exhausted word and still have not found a 1
  11206. this.loadWord();
  11207. return leadingZeroCount + this.skipLZ();
  11208. }
  11209. // ():void
  11210. skipUEG() {
  11211. this.skipBits(1 + this.skipLZ());
  11212. }
  11213. // ():void
  11214. skipEG() {
  11215. this.skipBits(1 + this.skipLZ());
  11216. }
  11217. // ():uint
  11218. readUEG() {
  11219. const clz = this.skipLZ(); // :uint
  11220. return this.readBits(clz + 1) - 1;
  11221. }
  11222. // ():int
  11223. readEG() {
  11224. const valu = this.readUEG(); // :int
  11225. if (0x01 & valu) {
  11226. // the number is odd if the low order bit is set
  11227. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  11228. } else {
  11229. return -1 * (valu >>> 1); // divide by two then make it negative
  11230. }
  11231. }
  11232. // Some convenience functions
  11233. // :Boolean
  11234. readBoolean() {
  11235. return this.readBits(1) === 1;
  11236. }
  11237. // ():int
  11238. readUByte() {
  11239. return this.readBits(8);
  11240. }
  11241. // ():int
  11242. readUShort() {
  11243. return this.readBits(16);
  11244. }
  11245. // ():int
  11246. readUInt() {
  11247. return this.readBits(32);
  11248. }
  11249. /**
  11250. * Advance the ExpGolomb decoder past a scaling list. The scaling
  11251. * list is optionally transmitted as part of a sequence parameter
  11252. * set and is not relevant to transmuxing.
  11253. * @param count the number of entries in this scaling list
  11254. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  11255. */
  11256. skipScalingList(count) {
  11257. let lastScale = 8;
  11258. let nextScale = 8;
  11259. let deltaScale;
  11260. for (let j = 0; j < count; j++) {
  11261. if (nextScale !== 0) {
  11262. deltaScale = this.readEG();
  11263. nextScale = (lastScale + deltaScale + 256) % 256;
  11264. }
  11265. lastScale = nextScale === 0 ? lastScale : nextScale;
  11266. }
  11267. }
  11268. /**
  11269. * Read a sequence parameter set and return some interesting video
  11270. * properties. A sequence parameter set is the H264 metadata that
  11271. * describes the properties of upcoming video frames.
  11272. * @returns an object with configuration parsed from the
  11273. * sequence parameter set, including the dimensions of the
  11274. * associated video frames.
  11275. */
  11276. readSPS() {
  11277. let frameCropLeftOffset = 0;
  11278. let frameCropRightOffset = 0;
  11279. let frameCropTopOffset = 0;
  11280. let frameCropBottomOffset = 0;
  11281. let numRefFramesInPicOrderCntCycle;
  11282. let scalingListCount;
  11283. let i;
  11284. const readUByte = this.readUByte.bind(this);
  11285. const readBits = this.readBits.bind(this);
  11286. const readUEG = this.readUEG.bind(this);
  11287. const readBoolean = this.readBoolean.bind(this);
  11288. const skipBits = this.skipBits.bind(this);
  11289. const skipEG = this.skipEG.bind(this);
  11290. const skipUEG = this.skipUEG.bind(this);
  11291. const skipScalingList = this.skipScalingList.bind(this);
  11292. readUByte();
  11293. const profileIdc = readUByte(); // profile_idc
  11294. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  11295. skipBits(3); // reserved_zero_3bits u(3),
  11296. readUByte(); // level_idc u(8)
  11297. skipUEG(); // seq_parameter_set_id
  11298. // some profiles have more optional data we don't need
  11299. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  11300. const chromaFormatIdc = readUEG();
  11301. if (chromaFormatIdc === 3) {
  11302. skipBits(1);
  11303. } // separate_colour_plane_flag
  11304. skipUEG(); // bit_depth_luma_minus8
  11305. skipUEG(); // bit_depth_chroma_minus8
  11306. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  11307. if (readBoolean()) {
  11308. // seq_scaling_matrix_present_flag
  11309. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  11310. for (i = 0; i < scalingListCount; i++) {
  11311. if (readBoolean()) {
  11312. // seq_scaling_list_present_flag[ i ]
  11313. if (i < 6) {
  11314. skipScalingList(16);
  11315. } else {
  11316. skipScalingList(64);
  11317. }
  11318. }
  11319. }
  11320. }
  11321. }
  11322. skipUEG(); // log2_max_frame_num_minus4
  11323. const picOrderCntType = readUEG();
  11324. if (picOrderCntType === 0) {
  11325. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  11326. } else if (picOrderCntType === 1) {
  11327. skipBits(1); // delta_pic_order_always_zero_flag
  11328. skipEG(); // offset_for_non_ref_pic
  11329. skipEG(); // offset_for_top_to_bottom_field
  11330. numRefFramesInPicOrderCntCycle = readUEG();
  11331. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  11332. skipEG();
  11333. } // offset_for_ref_frame[ i ]
  11334. }
  11335. skipUEG(); // max_num_ref_frames
  11336. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  11337. const picWidthInMbsMinus1 = readUEG();
  11338. const picHeightInMapUnitsMinus1 = readUEG();
  11339. const frameMbsOnlyFlag = readBits(1);
  11340. if (frameMbsOnlyFlag === 0) {
  11341. skipBits(1);
  11342. } // mb_adaptive_frame_field_flag
  11343. skipBits(1); // direct_8x8_inference_flag
  11344. if (readBoolean()) {
  11345. // frame_cropping_flag
  11346. frameCropLeftOffset = readUEG();
  11347. frameCropRightOffset = readUEG();
  11348. frameCropTopOffset = readUEG();
  11349. frameCropBottomOffset = readUEG();
  11350. }
  11351. let pixelRatio = [1, 1];
  11352. if (readBoolean()) {
  11353. // vui_parameters_present_flag
  11354. if (readBoolean()) {
  11355. // aspect_ratio_info_present_flag
  11356. const aspectRatioIdc = readUByte();
  11357. switch (aspectRatioIdc) {
  11358. case 1:
  11359. pixelRatio = [1, 1];
  11360. break;
  11361. case 2:
  11362. pixelRatio = [12, 11];
  11363. break;
  11364. case 3:
  11365. pixelRatio = [10, 11];
  11366. break;
  11367. case 4:
  11368. pixelRatio = [16, 11];
  11369. break;
  11370. case 5:
  11371. pixelRatio = [40, 33];
  11372. break;
  11373. case 6:
  11374. pixelRatio = [24, 11];
  11375. break;
  11376. case 7:
  11377. pixelRatio = [20, 11];
  11378. break;
  11379. case 8:
  11380. pixelRatio = [32, 11];
  11381. break;
  11382. case 9:
  11383. pixelRatio = [80, 33];
  11384. break;
  11385. case 10:
  11386. pixelRatio = [18, 11];
  11387. break;
  11388. case 11:
  11389. pixelRatio = [15, 11];
  11390. break;
  11391. case 12:
  11392. pixelRatio = [64, 33];
  11393. break;
  11394. case 13:
  11395. pixelRatio = [160, 99];
  11396. break;
  11397. case 14:
  11398. pixelRatio = [4, 3];
  11399. break;
  11400. case 15:
  11401. pixelRatio = [3, 2];
  11402. break;
  11403. case 16:
  11404. pixelRatio = [2, 1];
  11405. break;
  11406. case 255:
  11407. {
  11408. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  11409. break;
  11410. }
  11411. }
  11412. }
  11413. }
  11414. return {
  11415. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  11416. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  11417. pixelRatio: pixelRatio
  11418. };
  11419. }
  11420. readSliceType() {
  11421. // skip NALu type
  11422. this.readUByte();
  11423. // discard first_mb_in_slice
  11424. this.readUEG();
  11425. // return slice_type
  11426. return this.readUEG();
  11427. }
  11428. }
  11429. class AvcVideoParser extends BaseVideoParser {
  11430. parseAVCPES(track, textTrack, pes, last, duration) {
  11431. const units = this.parseAVCNALu(track, pes.data);
  11432. let VideoSample = this.VideoSample;
  11433. let push;
  11434. let spsfound = false;
  11435. // free pes.data to save up some memory
  11436. pes.data = null;
  11437. // if new NAL units found and last sample still there, let's push ...
  11438. // this helps parsing streams with missing AUD (only do this if AUD never found)
  11439. if (VideoSample && units.length && !track.audFound) {
  11440. this.pushAccessUnit(VideoSample, track);
  11441. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  11442. }
  11443. units.forEach(unit => {
  11444. var _VideoSample2;
  11445. switch (unit.type) {
  11446. // NDR
  11447. case 1:
  11448. {
  11449. let iskey = false;
  11450. push = true;
  11451. const data = unit.data;
  11452. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  11453. if (spsfound && data.length > 4) {
  11454. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  11455. const sliceType = new ExpGolomb(data).readSliceType();
  11456. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  11457. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  11458. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  11459. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  11460. // if (sliceType === 2 || sliceType === 7) {
  11461. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  11462. iskey = true;
  11463. }
  11464. }
  11465. if (iskey) {
  11466. var _VideoSample;
  11467. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  11468. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  11469. this.pushAccessUnit(VideoSample, track);
  11470. VideoSample = this.VideoSample = null;
  11471. }
  11472. }
  11473. if (!VideoSample) {
  11474. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  11475. }
  11476. VideoSample.frame = true;
  11477. VideoSample.key = iskey;
  11478. break;
  11479. // IDR
  11480. }
  11481. case 5:
  11482. push = true;
  11483. // handle PES not starting with AUD
  11484. // if we have frame data already, that cannot belong to the same frame, so force a push
  11485. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  11486. this.pushAccessUnit(VideoSample, track);
  11487. VideoSample = this.VideoSample = null;
  11488. }
  11489. if (!VideoSample) {
  11490. VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts, '');
  11491. }
  11492. VideoSample.key = true;
  11493. VideoSample.frame = true;
  11494. break;
  11495. // SEI
  11496. case 6:
  11497. {
  11498. push = true;
  11499. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  11500. break;
  11501. // SPS
  11502. }
  11503. case 7:
  11504. {
  11505. var _track$pixelRatio, _track$pixelRatio2;
  11506. push = true;
  11507. spsfound = true;
  11508. const sps = unit.data;
  11509. const expGolombDecoder = new ExpGolomb(sps);
  11510. const config = expGolombDecoder.readSPS();
  11511. 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]) {
  11512. track.width = config.width;
  11513. track.height = config.height;
  11514. track.pixelRatio = config.pixelRatio;
  11515. track.sps = [sps];
  11516. track.duration = duration;
  11517. const codecarray = sps.subarray(1, 4);
  11518. let codecstring = 'avc1.';
  11519. for (let i = 0; i < 3; i++) {
  11520. let h = codecarray[i].toString(16);
  11521. if (h.length < 2) {
  11522. h = '0' + h;
  11523. }
  11524. codecstring += h;
  11525. }
  11526. track.codec = codecstring;
  11527. }
  11528. break;
  11529. }
  11530. // PPS
  11531. case 8:
  11532. push = true;
  11533. track.pps = [unit.data];
  11534. break;
  11535. // AUD
  11536. case 9:
  11537. push = true;
  11538. track.audFound = true;
  11539. if (VideoSample) {
  11540. this.pushAccessUnit(VideoSample, track);
  11541. }
  11542. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  11543. break;
  11544. // Filler Data
  11545. case 12:
  11546. push = true;
  11547. break;
  11548. default:
  11549. push = false;
  11550. if (VideoSample) {
  11551. VideoSample.debug += 'unknown NAL ' + unit.type + ' ';
  11552. }
  11553. break;
  11554. }
  11555. if (VideoSample && push) {
  11556. const units = VideoSample.units;
  11557. units.push(unit);
  11558. }
  11559. });
  11560. // if last PES packet, push samples
  11561. if (last && VideoSample) {
  11562. this.pushAccessUnit(VideoSample, track);
  11563. this.VideoSample = null;
  11564. }
  11565. }
  11566. parseAVCNALu(track, array) {
  11567. const len = array.byteLength;
  11568. let state = track.naluState || 0;
  11569. const lastState = state;
  11570. const units = [];
  11571. let i = 0;
  11572. let value;
  11573. let overflow;
  11574. let unitType;
  11575. let lastUnitStart = -1;
  11576. let lastUnitType = 0;
  11577. // logger.log('PES:' + Hex.hexDump(array));
  11578. if (state === -1) {
  11579. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  11580. lastUnitStart = 0;
  11581. // NALu type is value read from offset 0
  11582. lastUnitType = array[0] & 0x1f;
  11583. state = 0;
  11584. i = 1;
  11585. }
  11586. while (i < len) {
  11587. value = array[i++];
  11588. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  11589. if (!state) {
  11590. state = value ? 0 : 1;
  11591. continue;
  11592. }
  11593. if (state === 1) {
  11594. state = value ? 0 : 2;
  11595. continue;
  11596. }
  11597. // here we have state either equal to 2 or 3
  11598. if (!value) {
  11599. state = 3;
  11600. } else if (value === 1) {
  11601. overflow = i - state - 1;
  11602. if (lastUnitStart >= 0) {
  11603. const unit = {
  11604. data: array.subarray(lastUnitStart, overflow),
  11605. type: lastUnitType
  11606. };
  11607. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  11608. units.push(unit);
  11609. } else {
  11610. // lastUnitStart is undefined => this is the first start code found in this PES packet
  11611. // first check if start code delimiter is overlapping between 2 PES packets,
  11612. // ie it started in last packet (lastState not zero)
  11613. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  11614. const lastUnit = this.getLastNalUnit(track.samples);
  11615. if (lastUnit) {
  11616. if (lastState && i <= 4 - lastState) {
  11617. // start delimiter overlapping between PES packets
  11618. // strip start delimiter bytes from the end of last NAL unit
  11619. // check if lastUnit had a state different from zero
  11620. if (lastUnit.state) {
  11621. // strip last bytes
  11622. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  11623. }
  11624. }
  11625. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  11626. if (overflow > 0) {
  11627. // logger.log('first NALU found with overflow:' + overflow);
  11628. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  11629. lastUnit.state = 0;
  11630. }
  11631. }
  11632. }
  11633. // check if we can read unit type
  11634. if (i < len) {
  11635. unitType = array[i] & 0x1f;
  11636. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  11637. lastUnitStart = i;
  11638. lastUnitType = unitType;
  11639. state = 0;
  11640. } else {
  11641. // not enough byte to read unit type. let's read it on next PES parsing
  11642. state = -1;
  11643. }
  11644. } else {
  11645. state = 0;
  11646. }
  11647. }
  11648. if (lastUnitStart >= 0 && state >= 0) {
  11649. const unit = {
  11650. data: array.subarray(lastUnitStart, len),
  11651. type: lastUnitType,
  11652. state: state
  11653. };
  11654. units.push(unit);
  11655. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  11656. }
  11657. // no NALu found
  11658. if (units.length === 0) {
  11659. // append pes.data to previous NAL unit
  11660. const lastUnit = this.getLastNalUnit(track.samples);
  11661. if (lastUnit) {
  11662. lastUnit.data = appendUint8Array(lastUnit.data, array);
  11663. }
  11664. }
  11665. track.naluState = state;
  11666. return units;
  11667. }
  11668. }
  11669. /**
  11670. * SAMPLE-AES decrypter
  11671. */
  11672. class SampleAesDecrypter {
  11673. constructor(observer, config, keyData) {
  11674. this.keyData = void 0;
  11675. this.decrypter = void 0;
  11676. this.keyData = keyData;
  11677. this.decrypter = new Decrypter(config, {
  11678. removePKCS7Padding: false
  11679. });
  11680. }
  11681. decryptBuffer(encryptedData) {
  11682. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  11683. }
  11684. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  11685. decryptAacSample(samples, sampleIndex, callback) {
  11686. const curUnit = samples[sampleIndex].unit;
  11687. if (curUnit.length <= 16) {
  11688. // No encrypted portion in this sample (first 16 bytes is not
  11689. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  11690. return;
  11691. }
  11692. const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  11693. const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  11694. this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {
  11695. const decryptedData = new Uint8Array(decryptedBuffer);
  11696. curUnit.set(decryptedData, 16);
  11697. if (!this.decrypter.isSync()) {
  11698. this.decryptAacSamples(samples, sampleIndex + 1, callback);
  11699. }
  11700. });
  11701. }
  11702. decryptAacSamples(samples, sampleIndex, callback) {
  11703. for (;; sampleIndex++) {
  11704. if (sampleIndex >= samples.length) {
  11705. callback();
  11706. return;
  11707. }
  11708. if (samples[sampleIndex].unit.length < 32) {
  11709. continue;
  11710. }
  11711. this.decryptAacSample(samples, sampleIndex, callback);
  11712. if (!this.decrypter.isSync()) {
  11713. return;
  11714. }
  11715. }
  11716. }
  11717. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  11718. getAvcEncryptedData(decodedData) {
  11719. const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  11720. const encryptedData = new Int8Array(encryptedDataLen);
  11721. let outputPos = 0;
  11722. for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  11723. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  11724. }
  11725. return encryptedData;
  11726. }
  11727. getAvcDecryptedUnit(decodedData, decryptedData) {
  11728. const uint8DecryptedData = new Uint8Array(decryptedData);
  11729. let inputPos = 0;
  11730. for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  11731. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  11732. }
  11733. return decodedData;
  11734. }
  11735. decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  11736. const decodedData = discardEPB(curUnit.data);
  11737. const encryptedData = this.getAvcEncryptedData(decodedData);
  11738. this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {
  11739. curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  11740. if (!this.decrypter.isSync()) {
  11741. this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  11742. }
  11743. });
  11744. }
  11745. decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  11746. if (samples instanceof Uint8Array) {
  11747. throw new Error('Cannot decrypt samples of type Uint8Array');
  11748. }
  11749. for (;; sampleIndex++, unitIndex = 0) {
  11750. if (sampleIndex >= samples.length) {
  11751. callback();
  11752. return;
  11753. }
  11754. const curUnits = samples[sampleIndex].units;
  11755. for (;; unitIndex++) {
  11756. if (unitIndex >= curUnits.length) {
  11757. break;
  11758. }
  11759. const curUnit = curUnits[unitIndex];
  11760. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  11761. continue;
  11762. }
  11763. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  11764. if (!this.decrypter.isSync()) {
  11765. return;
  11766. }
  11767. }
  11768. }
  11769. }
  11770. }
  11771. const PACKET_LENGTH = 188;
  11772. class TSDemuxer {
  11773. constructor(observer, config, typeSupported) {
  11774. this.observer = void 0;
  11775. this.config = void 0;
  11776. this.typeSupported = void 0;
  11777. this.sampleAes = null;
  11778. this.pmtParsed = false;
  11779. this.audioCodec = void 0;
  11780. this.videoCodec = void 0;
  11781. this._duration = 0;
  11782. this._pmtId = -1;
  11783. this._videoTrack = void 0;
  11784. this._audioTrack = void 0;
  11785. this._id3Track = void 0;
  11786. this._txtTrack = void 0;
  11787. this.aacOverFlow = null;
  11788. this.remainderData = null;
  11789. this.videoParser = void 0;
  11790. this.observer = observer;
  11791. this.config = config;
  11792. this.typeSupported = typeSupported;
  11793. this.videoParser = new AvcVideoParser();
  11794. }
  11795. static probe(data) {
  11796. const syncOffset = TSDemuxer.syncOffset(data);
  11797. if (syncOffset > 0) {
  11798. logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);
  11799. }
  11800. return syncOffset !== -1;
  11801. }
  11802. static syncOffset(data) {
  11803. const length = data.length;
  11804. let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11805. let i = 0;
  11806. while (i < scanwindow) {
  11807. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  11808. let foundPat = false;
  11809. let packetStart = -1;
  11810. let tsPackets = 0;
  11811. for (let j = i; j < length; j += PACKET_LENGTH) {
  11812. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  11813. tsPackets++;
  11814. if (packetStart === -1) {
  11815. packetStart = j;
  11816. // First sync word found at offset, increase scan length (#5251)
  11817. if (packetStart !== 0) {
  11818. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11819. }
  11820. }
  11821. if (!foundPat) {
  11822. foundPat = parsePID(data, j) === 0;
  11823. }
  11824. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  11825. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11826. return packetStart;
  11827. }
  11828. } else if (tsPackets) {
  11829. // Exit if sync word found, but does not contain contiguous packets
  11830. return -1;
  11831. } else {
  11832. break;
  11833. }
  11834. }
  11835. i++;
  11836. }
  11837. return -1;
  11838. }
  11839. /**
  11840. * Creates a track model internal to demuxer used to drive remuxing input
  11841. */
  11842. static createTrack(type, duration) {
  11843. return {
  11844. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  11845. type,
  11846. id: RemuxerTrackIdConfig[type],
  11847. pid: -1,
  11848. inputTimeScale: 90000,
  11849. sequenceNumber: 0,
  11850. samples: [],
  11851. dropped: 0,
  11852. duration: type === 'audio' ? duration : undefined
  11853. };
  11854. }
  11855. /**
  11856. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  11857. * Resets all internal track instances of the demuxer.
  11858. */
  11859. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11860. this.pmtParsed = false;
  11861. this._pmtId = -1;
  11862. this._videoTrack = TSDemuxer.createTrack('video');
  11863. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  11864. this._id3Track = TSDemuxer.createTrack('id3');
  11865. this._txtTrack = TSDemuxer.createTrack('text');
  11866. this._audioTrack.segmentCodec = 'aac';
  11867. // flush any partial content
  11868. this.aacOverFlow = null;
  11869. this.remainderData = null;
  11870. this.audioCodec = audioCodec;
  11871. this.videoCodec = videoCodec;
  11872. this._duration = trackDuration;
  11873. }
  11874. resetTimeStamp() {}
  11875. resetContiguity() {
  11876. const {
  11877. _audioTrack,
  11878. _videoTrack,
  11879. _id3Track
  11880. } = this;
  11881. if (_audioTrack) {
  11882. _audioTrack.pesData = null;
  11883. }
  11884. if (_videoTrack) {
  11885. _videoTrack.pesData = null;
  11886. }
  11887. if (_id3Track) {
  11888. _id3Track.pesData = null;
  11889. }
  11890. this.aacOverFlow = null;
  11891. this.remainderData = null;
  11892. }
  11893. demux(data, timeOffset, isSampleAes = false, flush = false) {
  11894. if (!isSampleAes) {
  11895. this.sampleAes = null;
  11896. }
  11897. let pes;
  11898. const videoTrack = this._videoTrack;
  11899. const audioTrack = this._audioTrack;
  11900. const id3Track = this._id3Track;
  11901. const textTrack = this._txtTrack;
  11902. let videoPid = videoTrack.pid;
  11903. let videoData = videoTrack.pesData;
  11904. let audioPid = audioTrack.pid;
  11905. let id3Pid = id3Track.pid;
  11906. let audioData = audioTrack.pesData;
  11907. let id3Data = id3Track.pesData;
  11908. let unknownPID = null;
  11909. let pmtParsed = this.pmtParsed;
  11910. let pmtId = this._pmtId;
  11911. let len = data.length;
  11912. if (this.remainderData) {
  11913. data = appendUint8Array(this.remainderData, data);
  11914. len = data.length;
  11915. this.remainderData = null;
  11916. }
  11917. if (len < PACKET_LENGTH && !flush) {
  11918. this.remainderData = data;
  11919. return {
  11920. audioTrack,
  11921. videoTrack,
  11922. id3Track,
  11923. textTrack
  11924. };
  11925. }
  11926. const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  11927. len -= (len - syncOffset) % PACKET_LENGTH;
  11928. if (len < data.byteLength && !flush) {
  11929. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11930. }
  11931. // loop through TS packets
  11932. let tsPacketErrors = 0;
  11933. for (let start = syncOffset; start < len; start += PACKET_LENGTH) {
  11934. if (data[start] === 0x47) {
  11935. const stt = !!(data[start + 1] & 0x40);
  11936. const pid = parsePID(data, start);
  11937. const atf = (data[start + 3] & 0x30) >> 4;
  11938. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  11939. let offset;
  11940. if (atf > 1) {
  11941. offset = start + 5 + data[start + 4];
  11942. // continue if there is only adaptation field
  11943. if (offset === start + PACKET_LENGTH) {
  11944. continue;
  11945. }
  11946. } else {
  11947. offset = start + 4;
  11948. }
  11949. switch (pid) {
  11950. case videoPid:
  11951. if (stt) {
  11952. if (videoData && (pes = parsePES(videoData))) {
  11953. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration);
  11954. }
  11955. videoData = {
  11956. data: [],
  11957. size: 0
  11958. };
  11959. }
  11960. if (videoData) {
  11961. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11962. videoData.size += start + PACKET_LENGTH - offset;
  11963. }
  11964. break;
  11965. case audioPid:
  11966. if (stt) {
  11967. if (audioData && (pes = parsePES(audioData))) {
  11968. switch (audioTrack.segmentCodec) {
  11969. case 'aac':
  11970. this.parseAACPES(audioTrack, pes);
  11971. break;
  11972. case 'mp3':
  11973. this.parseMPEGPES(audioTrack, pes);
  11974. break;
  11975. case 'ac3':
  11976. {
  11977. this.parseAC3PES(audioTrack, pes);
  11978. }
  11979. break;
  11980. }
  11981. }
  11982. audioData = {
  11983. data: [],
  11984. size: 0
  11985. };
  11986. }
  11987. if (audioData) {
  11988. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11989. audioData.size += start + PACKET_LENGTH - offset;
  11990. }
  11991. break;
  11992. case id3Pid:
  11993. if (stt) {
  11994. if (id3Data && (pes = parsePES(id3Data))) {
  11995. this.parseID3PES(id3Track, pes);
  11996. }
  11997. id3Data = {
  11998. data: [],
  11999. size: 0
  12000. };
  12001. }
  12002. if (id3Data) {
  12003. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  12004. id3Data.size += start + PACKET_LENGTH - offset;
  12005. }
  12006. break;
  12007. case 0:
  12008. if (stt) {
  12009. offset += data[offset] + 1;
  12010. }
  12011. pmtId = this._pmtId = parsePAT(data, offset);
  12012. // logger.log('PMT PID:' + this._pmtId);
  12013. break;
  12014. case pmtId:
  12015. {
  12016. if (stt) {
  12017. offset += data[offset] + 1;
  12018. }
  12019. const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer);
  12020. // only update track id if track PID found while parsing PMT
  12021. // this is to avoid resetting the PID to -1 in case
  12022. // track PID transiently disappears from the stream
  12023. // this could happen in case of transient missing audio samples for example
  12024. // NOTE this is only the PID of the track as found in TS,
  12025. // but we are not using this for MP4 track IDs.
  12026. videoPid = parsedPIDs.videoPid;
  12027. if (videoPid > 0) {
  12028. videoTrack.pid = videoPid;
  12029. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  12030. }
  12031. audioPid = parsedPIDs.audioPid;
  12032. if (audioPid > 0) {
  12033. audioTrack.pid = audioPid;
  12034. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  12035. }
  12036. id3Pid = parsedPIDs.id3Pid;
  12037. if (id3Pid > 0) {
  12038. id3Track.pid = id3Pid;
  12039. }
  12040. if (unknownPID !== null && !pmtParsed) {
  12041. logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);
  12042. unknownPID = null;
  12043. // we set it to -188, the += 188 in the for loop will reset start to 0
  12044. start = syncOffset - 188;
  12045. }
  12046. pmtParsed = this.pmtParsed = true;
  12047. break;
  12048. }
  12049. case 0x11:
  12050. case 0x1fff:
  12051. break;
  12052. default:
  12053. unknownPID = pid;
  12054. break;
  12055. }
  12056. } else {
  12057. tsPacketErrors++;
  12058. }
  12059. }
  12060. if (tsPacketErrors > 0) {
  12061. emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`));
  12062. }
  12063. videoTrack.pesData = videoData;
  12064. audioTrack.pesData = audioData;
  12065. id3Track.pesData = id3Data;
  12066. const demuxResult = {
  12067. audioTrack,
  12068. videoTrack,
  12069. id3Track,
  12070. textTrack
  12071. };
  12072. if (flush) {
  12073. this.extractRemainingSamples(demuxResult);
  12074. }
  12075. return demuxResult;
  12076. }
  12077. flush() {
  12078. const {
  12079. remainderData
  12080. } = this;
  12081. this.remainderData = null;
  12082. let result;
  12083. if (remainderData) {
  12084. result = this.demux(remainderData, -1, false, true);
  12085. } else {
  12086. result = {
  12087. videoTrack: this._videoTrack,
  12088. audioTrack: this._audioTrack,
  12089. id3Track: this._id3Track,
  12090. textTrack: this._txtTrack
  12091. };
  12092. }
  12093. this.extractRemainingSamples(result);
  12094. if (this.sampleAes) {
  12095. return this.decrypt(result, this.sampleAes);
  12096. }
  12097. return result;
  12098. }
  12099. extractRemainingSamples(demuxResult) {
  12100. const {
  12101. audioTrack,
  12102. videoTrack,
  12103. id3Track,
  12104. textTrack
  12105. } = demuxResult;
  12106. const videoData = videoTrack.pesData;
  12107. const audioData = audioTrack.pesData;
  12108. const id3Data = id3Track.pesData;
  12109. // try to parse last PES packets
  12110. let pes;
  12111. if (videoData && (pes = parsePES(videoData))) {
  12112. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration);
  12113. videoTrack.pesData = null;
  12114. } else {
  12115. // either avcData null or PES truncated, keep it for next frag parsing
  12116. videoTrack.pesData = videoData;
  12117. }
  12118. if (audioData && (pes = parsePES(audioData))) {
  12119. switch (audioTrack.segmentCodec) {
  12120. case 'aac':
  12121. this.parseAACPES(audioTrack, pes);
  12122. break;
  12123. case 'mp3':
  12124. this.parseMPEGPES(audioTrack, pes);
  12125. break;
  12126. case 'ac3':
  12127. {
  12128. this.parseAC3PES(audioTrack, pes);
  12129. }
  12130. break;
  12131. }
  12132. audioTrack.pesData = null;
  12133. } else {
  12134. if (audioData != null && audioData.size) {
  12135. logger.log('last AAC PES packet truncated,might overlap between fragments');
  12136. }
  12137. // either audioData null or PES truncated, keep it for next frag parsing
  12138. audioTrack.pesData = audioData;
  12139. }
  12140. if (id3Data && (pes = parsePES(id3Data))) {
  12141. this.parseID3PES(id3Track, pes);
  12142. id3Track.pesData = null;
  12143. } else {
  12144. // either id3Data null or PES truncated, keep it for next frag parsing
  12145. id3Track.pesData = id3Data;
  12146. }
  12147. }
  12148. demuxSampleAes(data, keyData, timeOffset) {
  12149. const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  12150. const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  12151. return this.decrypt(demuxResult, sampleAes);
  12152. }
  12153. decrypt(demuxResult, sampleAes) {
  12154. return new Promise(resolve => {
  12155. const {
  12156. audioTrack,
  12157. videoTrack
  12158. } = demuxResult;
  12159. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  12160. sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {
  12161. if (videoTrack.samples) {
  12162. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  12163. resolve(demuxResult);
  12164. });
  12165. } else {
  12166. resolve(demuxResult);
  12167. }
  12168. });
  12169. } else if (videoTrack.samples) {
  12170. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {
  12171. resolve(demuxResult);
  12172. });
  12173. }
  12174. });
  12175. }
  12176. destroy() {
  12177. this._duration = 0;
  12178. }
  12179. parseAACPES(track, pes) {
  12180. let startOffset = 0;
  12181. const aacOverFlow = this.aacOverFlow;
  12182. let data = pes.data;
  12183. if (aacOverFlow) {
  12184. this.aacOverFlow = null;
  12185. const frameMissingBytes = aacOverFlow.missing;
  12186. const sampleLength = aacOverFlow.sample.unit.byteLength;
  12187. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  12188. if (frameMissingBytes === -1) {
  12189. data = appendUint8Array(aacOverFlow.sample.unit, data);
  12190. } else {
  12191. const frameOverflowBytes = sampleLength - frameMissingBytes;
  12192. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  12193. track.samples.push(aacOverFlow.sample);
  12194. startOffset = aacOverFlow.missing;
  12195. }
  12196. }
  12197. // look for ADTS header (0xFFFx)
  12198. let offset;
  12199. let len;
  12200. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  12201. if (isHeader$1(data, offset)) {
  12202. break;
  12203. }
  12204. }
  12205. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  12206. if (offset !== startOffset) {
  12207. let reason;
  12208. const recoverable = offset < len - 1;
  12209. if (recoverable) {
  12210. reason = `AAC PES did not start with ADTS header,offset:${offset}`;
  12211. } else {
  12212. reason = 'No ADTS header found in AAC PES';
  12213. }
  12214. emitParsingError(this.observer, new Error(reason), recoverable);
  12215. if (!recoverable) {
  12216. return;
  12217. }
  12218. }
  12219. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  12220. let pts;
  12221. if (pes.pts !== undefined) {
  12222. pts = pes.pts;
  12223. } else if (aacOverFlow) {
  12224. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  12225. // first sample PTS should be equal to last sample PTS + frameDuration
  12226. const frameDuration = getFrameDuration(track.samplerate);
  12227. pts = aacOverFlow.sample.pts + frameDuration;
  12228. } else {
  12229. logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  12230. return;
  12231. }
  12232. // scan for aac samples
  12233. let frameIndex = 0;
  12234. let frame;
  12235. while (offset < len) {
  12236. frame = appendFrame$2(track, data, offset, pts, frameIndex);
  12237. offset += frame.length;
  12238. if (!frame.missing) {
  12239. frameIndex++;
  12240. for (; offset < len - 1; offset++) {
  12241. if (isHeader$1(data, offset)) {
  12242. break;
  12243. }
  12244. }
  12245. } else {
  12246. this.aacOverFlow = frame;
  12247. break;
  12248. }
  12249. }
  12250. }
  12251. parseMPEGPES(track, pes) {
  12252. const data = pes.data;
  12253. const length = data.length;
  12254. let frameIndex = 0;
  12255. let offset = 0;
  12256. const pts = pes.pts;
  12257. if (pts === undefined) {
  12258. logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  12259. return;
  12260. }
  12261. while (offset < length) {
  12262. if (isHeader(data, offset)) {
  12263. const frame = appendFrame$1(track, data, offset, pts, frameIndex);
  12264. if (frame) {
  12265. offset += frame.length;
  12266. frameIndex++;
  12267. } else {
  12268. // logger.log('Unable to parse Mpeg audio frame');
  12269. break;
  12270. }
  12271. } else {
  12272. // nothing found, keep looking
  12273. offset++;
  12274. }
  12275. }
  12276. }
  12277. parseAC3PES(track, pes) {
  12278. {
  12279. const data = pes.data;
  12280. const pts = pes.pts;
  12281. if (pts === undefined) {
  12282. logger.warn('[tsdemuxer]: AC3 PES unknown PTS');
  12283. return;
  12284. }
  12285. const length = data.length;
  12286. let frameIndex = 0;
  12287. let offset = 0;
  12288. let parsed;
  12289. while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  12290. offset += parsed;
  12291. }
  12292. }
  12293. }
  12294. parseID3PES(id3Track, pes) {
  12295. if (pes.pts === undefined) {
  12296. logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  12297. return;
  12298. }
  12299. const id3Sample = _extends({}, pes, {
  12300. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  12301. duration: Number.POSITIVE_INFINITY
  12302. });
  12303. id3Track.samples.push(id3Sample);
  12304. }
  12305. }
  12306. function parsePID(data, offset) {
  12307. // pid is a 13-bit field starting at the last bit of TS[1]
  12308. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  12309. }
  12310. function parsePAT(data, offset) {
  12311. // skip the PSI header and parse the first PMT entry
  12312. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  12313. }
  12314. function parsePMT(data, offset, typeSupported, isSampleAes, observer) {
  12315. const result = {
  12316. audioPid: -1,
  12317. videoPid: -1,
  12318. id3Pid: -1,
  12319. segmentVideoCodec: 'avc',
  12320. segmentAudioCodec: 'aac'
  12321. };
  12322. const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  12323. const tableEnd = offset + 3 + sectionLength - 4;
  12324. // to determine where the table is, we have to figure out how
  12325. // long the program info descriptors are
  12326. const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  12327. // advance the offset to the first entry in the mapping table
  12328. offset += 12 + programInfoLength;
  12329. while (offset < tableEnd) {
  12330. const pid = parsePID(data, offset);
  12331. const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  12332. switch (data[offset]) {
  12333. case 0xcf:
  12334. // SAMPLE-AES AAC
  12335. if (!isSampleAes) {
  12336. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');
  12337. break;
  12338. }
  12339. /* falls through */
  12340. case 0x0f:
  12341. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  12342. // logger.log('AAC PID:' + pid);
  12343. if (result.audioPid === -1) {
  12344. result.audioPid = pid;
  12345. }
  12346. break;
  12347. // Packetized metadata (ID3)
  12348. case 0x15:
  12349. // logger.log('ID3 PID:' + pid);
  12350. if (result.id3Pid === -1) {
  12351. result.id3Pid = pid;
  12352. }
  12353. break;
  12354. case 0xdb:
  12355. // SAMPLE-AES AVC
  12356. if (!isSampleAes) {
  12357. logEncryptedSamplesFoundInUnencryptedStream('H.264');
  12358. break;
  12359. }
  12360. /* falls through */
  12361. case 0x1b:
  12362. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  12363. // logger.log('AVC PID:' + pid);
  12364. if (result.videoPid === -1) {
  12365. result.videoPid = pid;
  12366. result.segmentVideoCodec = 'avc';
  12367. }
  12368. break;
  12369. // ISO/IEC 11172-3 (MPEG-1 audio)
  12370. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  12371. case 0x03:
  12372. case 0x04:
  12373. // logger.log('MPEG PID:' + pid);
  12374. if (!typeSupported.mpeg && !typeSupported.mp3) {
  12375. logger.log('MPEG audio found, not supported in this browser');
  12376. } else if (result.audioPid === -1) {
  12377. result.audioPid = pid;
  12378. result.segmentAudioCodec = 'mp3';
  12379. }
  12380. break;
  12381. case 0xc1:
  12382. // SAMPLE-AES AC3
  12383. if (!isSampleAes) {
  12384. logEncryptedSamplesFoundInUnencryptedStream('AC-3');
  12385. break;
  12386. }
  12387. /* falls through */
  12388. case 0x81:
  12389. {
  12390. if (!typeSupported.ac3) {
  12391. logger.log('AC-3 audio found, not supported in this browser');
  12392. } else if (result.audioPid === -1) {
  12393. result.audioPid = pid;
  12394. result.segmentAudioCodec = 'ac3';
  12395. }
  12396. }
  12397. break;
  12398. case 0x06:
  12399. // stream_type 6 can mean a lot of different things in case of DVB.
  12400. // We need to look at the descriptors. Right now, we're only interested
  12401. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  12402. // an audio PID yet.
  12403. if (result.audioPid === -1 && esInfoLength > 0) {
  12404. let parsePos = offset + 5;
  12405. let remaining = esInfoLength;
  12406. while (remaining > 2) {
  12407. const descriptorId = data[parsePos];
  12408. switch (descriptorId) {
  12409. case 0x6a:
  12410. // DVB Descriptor for AC-3
  12411. {
  12412. if (typeSupported.ac3 !== true) {
  12413. logger.log('AC-3 audio found, not supported in this browser for now');
  12414. } else {
  12415. result.audioPid = pid;
  12416. result.segmentAudioCodec = 'ac3';
  12417. }
  12418. }
  12419. break;
  12420. }
  12421. const descriptorLen = data[parsePos + 1] + 2;
  12422. parsePos += descriptorLen;
  12423. remaining -= descriptorLen;
  12424. }
  12425. }
  12426. break;
  12427. case 0xc2: // SAMPLE-AES EC3
  12428. /* falls through */
  12429. case 0x87:
  12430. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));
  12431. return result;
  12432. case 0x24:
  12433. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));
  12434. return result;
  12435. }
  12436. // move to the next table entry
  12437. // skip past the elementary stream descriptors, if present
  12438. offset += esInfoLength + 5;
  12439. }
  12440. return result;
  12441. }
  12442. function emitParsingError(observer, error, levelRetry) {
  12443. logger.warn(`parsing error: ${error.message}`);
  12444. observer.emit(Events.ERROR, Events.ERROR, {
  12445. type: ErrorTypes.MEDIA_ERROR,
  12446. details: ErrorDetails.FRAG_PARSING_ERROR,
  12447. fatal: false,
  12448. levelRetry,
  12449. error,
  12450. reason: error.message
  12451. });
  12452. }
  12453. function logEncryptedSamplesFoundInUnencryptedStream(type) {
  12454. logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);
  12455. }
  12456. function parsePES(stream) {
  12457. let i = 0;
  12458. let frag;
  12459. let pesLen;
  12460. let pesHdrLen;
  12461. let pesPts;
  12462. let pesDts;
  12463. const data = stream.data;
  12464. // safety check
  12465. if (!stream || stream.size === 0) {
  12466. return null;
  12467. }
  12468. // we might need up to 19 bytes to read PES header
  12469. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  12470. // usually only one merge is needed (and this is rare ...)
  12471. while (data[0].length < 19 && data.length > 1) {
  12472. data[0] = appendUint8Array(data[0], data[1]);
  12473. data.splice(1, 1);
  12474. }
  12475. // retrieve PTS/DTS from first fragment
  12476. frag = data[0];
  12477. const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  12478. if (pesPrefix === 1) {
  12479. pesLen = (frag[4] << 8) + frag[5];
  12480. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  12481. // minus 6 : PES header size
  12482. if (pesLen && pesLen > stream.size - 6) {
  12483. return null;
  12484. }
  12485. const pesFlags = frag[7];
  12486. if (pesFlags & 0xc0) {
  12487. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  12488. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  12489. as Bitwise operators treat their operands as a sequence of 32 bits */
  12490. pesPts = (frag[9] & 0x0e) * 536870912 +
  12491. // 1 << 29
  12492. (frag[10] & 0xff) * 4194304 +
  12493. // 1 << 22
  12494. (frag[11] & 0xfe) * 16384 +
  12495. // 1 << 14
  12496. (frag[12] & 0xff) * 128 +
  12497. // 1 << 7
  12498. (frag[13] & 0xfe) / 2;
  12499. if (pesFlags & 0x40) {
  12500. pesDts = (frag[14] & 0x0e) * 536870912 +
  12501. // 1 << 29
  12502. (frag[15] & 0xff) * 4194304 +
  12503. // 1 << 22
  12504. (frag[16] & 0xfe) * 16384 +
  12505. // 1 << 14
  12506. (frag[17] & 0xff) * 128 +
  12507. // 1 << 7
  12508. (frag[18] & 0xfe) / 2;
  12509. if (pesPts - pesDts > 60 * 90000) {
  12510. logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);
  12511. pesPts = pesDts;
  12512. }
  12513. } else {
  12514. pesDts = pesPts;
  12515. }
  12516. }
  12517. pesHdrLen = frag[8];
  12518. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  12519. let payloadStartOffset = pesHdrLen + 9;
  12520. if (stream.size <= payloadStartOffset) {
  12521. return null;
  12522. }
  12523. stream.size -= payloadStartOffset;
  12524. // reassemble PES packet
  12525. const pesData = new Uint8Array(stream.size);
  12526. for (let j = 0, dataLen = data.length; j < dataLen; j++) {
  12527. frag = data[j];
  12528. let len = frag.byteLength;
  12529. if (payloadStartOffset) {
  12530. if (payloadStartOffset > len) {
  12531. // trim full frag if PES header bigger than frag
  12532. payloadStartOffset -= len;
  12533. continue;
  12534. } else {
  12535. // trim partial frag if PES header smaller than frag
  12536. frag = frag.subarray(payloadStartOffset);
  12537. len -= payloadStartOffset;
  12538. payloadStartOffset = 0;
  12539. }
  12540. }
  12541. pesData.set(frag, i);
  12542. i += len;
  12543. }
  12544. if (pesLen) {
  12545. // payload size : remove PES header + PES extension
  12546. pesLen -= pesHdrLen + 3;
  12547. }
  12548. return {
  12549. data: pesData,
  12550. pts: pesPts,
  12551. dts: pesDts,
  12552. len: pesLen
  12553. };
  12554. }
  12555. return null;
  12556. }
  12557. /**
  12558. * MP3 demuxer
  12559. */
  12560. class MP3Demuxer extends BaseAudioDemuxer {
  12561. resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  12562. super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);
  12563. this._audioTrack = {
  12564. container: 'audio/mpeg',
  12565. type: 'audio',
  12566. id: 2,
  12567. pid: -1,
  12568. sequenceNumber: 0,
  12569. segmentCodec: 'mp3',
  12570. samples: [],
  12571. manifestCodec: audioCodec,
  12572. duration: trackDuration,
  12573. inputTimeScale: 90000,
  12574. dropped: 0
  12575. };
  12576. }
  12577. static probe(data) {
  12578. if (!data) {
  12579. return false;
  12580. }
  12581. // check if data contains ID3 timestamp and MPEG sync word
  12582. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  12583. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  12584. // More info http://www.mp3-tech.org/programmer/frame_header.html
  12585. const id3Data = getID3Data(data, 0);
  12586. let offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  12587. // Check for ac-3|ec-3 sync bytes and return false if present
  12588. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  12589. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  12590. getAudioBSID(data, offset) <= 16) {
  12591. return false;
  12592. }
  12593. for (let length = data.length; offset < length; offset++) {
  12594. if (probe(data, offset)) {
  12595. logger.log('MPEG Audio sync word found !');
  12596. return true;
  12597. }
  12598. }
  12599. return false;
  12600. }
  12601. canParse(data, offset) {
  12602. return canParse(data, offset);
  12603. }
  12604. appendFrame(track, data, offset) {
  12605. if (this.basePTS === null) {
  12606. return;
  12607. }
  12608. return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  12609. }
  12610. }
  12611. /**
  12612. * AAC helper
  12613. */
  12614. class AAC {
  12615. static getSilentFrame(codec, channelCount) {
  12616. switch (codec) {
  12617. case 'mp4a.40.2':
  12618. if (channelCount === 1) {
  12619. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  12620. } else if (channelCount === 2) {
  12621. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  12622. } else if (channelCount === 3) {
  12623. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  12624. } else if (channelCount === 4) {
  12625. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  12626. } else if (channelCount === 5) {
  12627. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  12628. } else if (channelCount === 6) {
  12629. 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]);
  12630. }
  12631. break;
  12632. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  12633. default:
  12634. if (channelCount === 1) {
  12635. // 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
  12636. 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]);
  12637. } else if (channelCount === 2) {
  12638. // 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
  12639. 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]);
  12640. } else if (channelCount === 3) {
  12641. // 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
  12642. 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]);
  12643. }
  12644. break;
  12645. }
  12646. return undefined;
  12647. }
  12648. }
  12649. /**
  12650. * Generate MP4 Box
  12651. */
  12652. const UINT32_MAX = Math.pow(2, 32) - 1;
  12653. class MP4 {
  12654. static init() {
  12655. MP4.types = {
  12656. avc1: [],
  12657. // codingname
  12658. avcC: [],
  12659. btrt: [],
  12660. dinf: [],
  12661. dref: [],
  12662. esds: [],
  12663. ftyp: [],
  12664. hdlr: [],
  12665. mdat: [],
  12666. mdhd: [],
  12667. mdia: [],
  12668. mfhd: [],
  12669. minf: [],
  12670. moof: [],
  12671. moov: [],
  12672. mp4a: [],
  12673. '.mp3': [],
  12674. dac3: [],
  12675. 'ac-3': [],
  12676. mvex: [],
  12677. mvhd: [],
  12678. pasp: [],
  12679. sdtp: [],
  12680. stbl: [],
  12681. stco: [],
  12682. stsc: [],
  12683. stsd: [],
  12684. stsz: [],
  12685. stts: [],
  12686. tfdt: [],
  12687. tfhd: [],
  12688. traf: [],
  12689. trak: [],
  12690. trun: [],
  12691. trex: [],
  12692. tkhd: [],
  12693. vmhd: [],
  12694. smhd: []
  12695. };
  12696. let i;
  12697. for (i in MP4.types) {
  12698. if (MP4.types.hasOwnProperty(i)) {
  12699. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  12700. }
  12701. }
  12702. const videoHdlr = new Uint8Array([0x00,
  12703. // version 0
  12704. 0x00, 0x00, 0x00,
  12705. // flags
  12706. 0x00, 0x00, 0x00, 0x00,
  12707. // pre_defined
  12708. 0x76, 0x69, 0x64, 0x65,
  12709. // handler_type: 'vide'
  12710. 0x00, 0x00, 0x00, 0x00,
  12711. // reserved
  12712. 0x00, 0x00, 0x00, 0x00,
  12713. // reserved
  12714. 0x00, 0x00, 0x00, 0x00,
  12715. // reserved
  12716. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  12717. ]);
  12718. const audioHdlr = new Uint8Array([0x00,
  12719. // version 0
  12720. 0x00, 0x00, 0x00,
  12721. // flags
  12722. 0x00, 0x00, 0x00, 0x00,
  12723. // pre_defined
  12724. 0x73, 0x6f, 0x75, 0x6e,
  12725. // handler_type: 'soun'
  12726. 0x00, 0x00, 0x00, 0x00,
  12727. // reserved
  12728. 0x00, 0x00, 0x00, 0x00,
  12729. // reserved
  12730. 0x00, 0x00, 0x00, 0x00,
  12731. // reserved
  12732. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  12733. ]);
  12734. MP4.HDLR_TYPES = {
  12735. video: videoHdlr,
  12736. audio: audioHdlr
  12737. };
  12738. const dref = new Uint8Array([0x00,
  12739. // version 0
  12740. 0x00, 0x00, 0x00,
  12741. // flags
  12742. 0x00, 0x00, 0x00, 0x01,
  12743. // entry_count
  12744. 0x00, 0x00, 0x00, 0x0c,
  12745. // entry_size
  12746. 0x75, 0x72, 0x6c, 0x20,
  12747. // 'url' type
  12748. 0x00,
  12749. // version 0
  12750. 0x00, 0x00, 0x01 // entry_flags
  12751. ]);
  12752. const stco = new Uint8Array([0x00,
  12753. // version
  12754. 0x00, 0x00, 0x00,
  12755. // flags
  12756. 0x00, 0x00, 0x00, 0x00 // entry_count
  12757. ]);
  12758. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  12759. MP4.STSZ = new Uint8Array([0x00,
  12760. // version
  12761. 0x00, 0x00, 0x00,
  12762. // flags
  12763. 0x00, 0x00, 0x00, 0x00,
  12764. // sample_size
  12765. 0x00, 0x00, 0x00, 0x00 // sample_count
  12766. ]);
  12767. MP4.VMHD = new Uint8Array([0x00,
  12768. // version
  12769. 0x00, 0x00, 0x01,
  12770. // flags
  12771. 0x00, 0x00,
  12772. // graphicsmode
  12773. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  12774. ]);
  12775. MP4.SMHD = new Uint8Array([0x00,
  12776. // version
  12777. 0x00, 0x00, 0x00,
  12778. // flags
  12779. 0x00, 0x00,
  12780. // balance
  12781. 0x00, 0x00 // reserved
  12782. ]);
  12783. MP4.STSD = new Uint8Array([0x00,
  12784. // version 0
  12785. 0x00, 0x00, 0x00,
  12786. // flags
  12787. 0x00, 0x00, 0x00, 0x01]); // entry_count
  12788. const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  12789. const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  12790. const minorVersion = new Uint8Array([0, 0, 0, 1]);
  12791. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  12792. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  12793. }
  12794. static box(type, ...payload) {
  12795. let size = 8;
  12796. let i = payload.length;
  12797. const len = i;
  12798. // calculate the total size we need to allocate
  12799. while (i--) {
  12800. size += payload[i].byteLength;
  12801. }
  12802. const result = new Uint8Array(size);
  12803. result[0] = size >> 24 & 0xff;
  12804. result[1] = size >> 16 & 0xff;
  12805. result[2] = size >> 8 & 0xff;
  12806. result[3] = size & 0xff;
  12807. result.set(type, 4);
  12808. // copy the payload into the result
  12809. for (i = 0, size = 8; i < len; i++) {
  12810. // copy payload[i] array @ offset size
  12811. result.set(payload[i], size);
  12812. size += payload[i].byteLength;
  12813. }
  12814. return result;
  12815. }
  12816. static hdlr(type) {
  12817. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  12818. }
  12819. static mdat(data) {
  12820. return MP4.box(MP4.types.mdat, data);
  12821. }
  12822. static mdhd(timescale, duration) {
  12823. duration *= timescale;
  12824. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12825. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12826. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  12827. // version 1
  12828. 0x00, 0x00, 0x00,
  12829. // flags
  12830. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12831. // creation_time
  12832. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12833. // modification_time
  12834. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12835. // timescale
  12836. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  12837. // 'und' language (undetermined)
  12838. 0x00, 0x00]));
  12839. }
  12840. static mdia(track) {
  12841. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  12842. }
  12843. static mfhd(sequenceNumber) {
  12844. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  12845. // flags
  12846. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  12847. ]));
  12848. }
  12849. static minf(track) {
  12850. if (track.type === 'audio') {
  12851. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  12852. } else {
  12853. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  12854. }
  12855. }
  12856. static moof(sn, baseMediaDecodeTime, track) {
  12857. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  12858. }
  12859. static moov(tracks) {
  12860. let i = tracks.length;
  12861. const boxes = [];
  12862. while (i--) {
  12863. boxes[i] = MP4.trak(tracks[i]);
  12864. }
  12865. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  12866. }
  12867. static mvex(tracks) {
  12868. let i = tracks.length;
  12869. const boxes = [];
  12870. while (i--) {
  12871. boxes[i] = MP4.trex(tracks[i]);
  12872. }
  12873. return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);
  12874. }
  12875. static mvhd(timescale, duration) {
  12876. duration *= timescale;
  12877. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12878. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12879. const bytes = new Uint8Array([0x01,
  12880. // version 1
  12881. 0x00, 0x00, 0x00,
  12882. // flags
  12883. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12884. // creation_time
  12885. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12886. // modification_time
  12887. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12888. // timescale
  12889. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  12890. // 1.0 rate
  12891. 0x01, 0x00,
  12892. // 1.0 volume
  12893. 0x00, 0x00,
  12894. // reserved
  12895. 0x00, 0x00, 0x00, 0x00,
  12896. // reserved
  12897. 0x00, 0x00, 0x00, 0x00,
  12898. // reserved
  12899. 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,
  12900. // transformation: unity matrix
  12901. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12902. // pre_defined
  12903. 0xff, 0xff, 0xff, 0xff // next_track_ID
  12904. ]);
  12905. return MP4.box(MP4.types.mvhd, bytes);
  12906. }
  12907. static sdtp(track) {
  12908. const samples = track.samples || [];
  12909. const bytes = new Uint8Array(4 + samples.length);
  12910. let i;
  12911. let flags;
  12912. // leave the full box header (4 bytes) all zero
  12913. // write the sample table
  12914. for (i = 0; i < samples.length; i++) {
  12915. flags = samples[i].flags;
  12916. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12917. }
  12918. return MP4.box(MP4.types.sdtp, bytes);
  12919. }
  12920. static stbl(track) {
  12921. 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));
  12922. }
  12923. static avc1(track) {
  12924. let sps = [];
  12925. let pps = [];
  12926. let i;
  12927. let data;
  12928. let len;
  12929. // assemble the SPSs
  12930. for (i = 0; i < track.sps.length; i++) {
  12931. data = track.sps[i];
  12932. len = data.byteLength;
  12933. sps.push(len >>> 8 & 0xff);
  12934. sps.push(len & 0xff);
  12935. // SPS
  12936. sps = sps.concat(Array.prototype.slice.call(data));
  12937. }
  12938. // assemble the PPSs
  12939. for (i = 0; i < track.pps.length; i++) {
  12940. data = track.pps[i];
  12941. len = data.byteLength;
  12942. pps.push(len >>> 8 & 0xff);
  12943. pps.push(len & 0xff);
  12944. pps = pps.concat(Array.prototype.slice.call(data));
  12945. }
  12946. const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  12947. // version
  12948. sps[3],
  12949. // profile
  12950. sps[4],
  12951. // profile compat
  12952. sps[5],
  12953. // level
  12954. 0xfc | 3,
  12955. // lengthSizeMinusOne, hard-coded to 4 bytes
  12956. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  12957. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  12958. ]).concat(pps))); // "PPS"
  12959. const width = track.width;
  12960. const height = track.height;
  12961. const hSpacing = track.pixelRatio[0];
  12962. const vSpacing = track.pixelRatio[1];
  12963. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  12964. // reserved
  12965. 0x00, 0x00, 0x00,
  12966. // reserved
  12967. 0x00, 0x01,
  12968. // data_reference_index
  12969. 0x00, 0x00,
  12970. // pre_defined
  12971. 0x00, 0x00,
  12972. // reserved
  12973. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12974. // pre_defined
  12975. width >> 8 & 0xff, width & 0xff,
  12976. // width
  12977. height >> 8 & 0xff, height & 0xff,
  12978. // height
  12979. 0x00, 0x48, 0x00, 0x00,
  12980. // horizresolution
  12981. 0x00, 0x48, 0x00, 0x00,
  12982. // vertresolution
  12983. 0x00, 0x00, 0x00, 0x00,
  12984. // reserved
  12985. 0x00, 0x01,
  12986. // frame_count
  12987. 0x12, 0x64, 0x61, 0x69, 0x6c,
  12988. // dailymotion/hls.js
  12989. 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,
  12990. // compressorname
  12991. 0x00, 0x18,
  12992. // depth = 24
  12993. 0x11, 0x11]),
  12994. // pre_defined = -1
  12995. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  12996. // bufferSizeDB
  12997. 0x00, 0x2d, 0xc6, 0xc0,
  12998. // maxBitrate
  12999. 0x00, 0x2d, 0xc6, 0xc0])),
  13000. // avgBitrate
  13001. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  13002. // hSpacing
  13003. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  13004. // vSpacing
  13005. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  13006. }
  13007. static esds(track) {
  13008. const configlen = track.config.length;
  13009. return new Uint8Array([0x00,
  13010. // version 0
  13011. 0x00, 0x00, 0x00,
  13012. // flags
  13013. 0x03,
  13014. // descriptor_type
  13015. 0x17 + configlen,
  13016. // length
  13017. 0x00, 0x01,
  13018. // es_id
  13019. 0x00,
  13020. // stream_priority
  13021. 0x04,
  13022. // descriptor_type
  13023. 0x0f + configlen,
  13024. // length
  13025. 0x40,
  13026. // codec : mpeg4_audio
  13027. 0x15,
  13028. // stream_type
  13029. 0x00, 0x00, 0x00,
  13030. // buffer_size
  13031. 0x00, 0x00, 0x00, 0x00,
  13032. // maxBitrate
  13033. 0x00, 0x00, 0x00, 0x00,
  13034. // avgBitrate
  13035. 0x05 // descriptor_type
  13036. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  13037. }
  13038. static audioStsd(track) {
  13039. const samplerate = track.samplerate;
  13040. return new Uint8Array([0x00, 0x00, 0x00,
  13041. // reserved
  13042. 0x00, 0x00, 0x00,
  13043. // reserved
  13044. 0x00, 0x01,
  13045. // data_reference_index
  13046. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  13047. // reserved
  13048. 0x00, track.channelCount,
  13049. // channelcount
  13050. 0x00, 0x10,
  13051. // sampleSize:16bits
  13052. 0x00, 0x00, 0x00, 0x00,
  13053. // reserved2
  13054. samplerate >> 8 & 0xff, samplerate & 0xff,
  13055. //
  13056. 0x00, 0x00]);
  13057. }
  13058. static mp4a(track) {
  13059. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  13060. }
  13061. static mp3(track) {
  13062. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  13063. }
  13064. static ac3(track) {
  13065. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  13066. }
  13067. static stsd(track) {
  13068. if (track.type === 'audio') {
  13069. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  13070. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  13071. }
  13072. if (track.segmentCodec === 'ac3') {
  13073. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  13074. }
  13075. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  13076. } else {
  13077. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  13078. }
  13079. }
  13080. static tkhd(track) {
  13081. const id = track.id;
  13082. const duration = track.duration * track.timescale;
  13083. const width = track.width;
  13084. const height = track.height;
  13085. const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13086. const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13087. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  13088. // version 1
  13089. 0x00, 0x00, 0x07,
  13090. // flags
  13091. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13092. // creation_time
  13093. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13094. // modification_time
  13095. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  13096. // track_ID
  13097. 0x00, 0x00, 0x00, 0x00,
  13098. // reserved
  13099. 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,
  13100. // reserved
  13101. 0x00, 0x00,
  13102. // layer
  13103. 0x00, 0x00,
  13104. // alternate_group
  13105. 0x00, 0x00,
  13106. // non-audio track volume
  13107. 0x00, 0x00,
  13108. // reserved
  13109. 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,
  13110. // transformation: unity matrix
  13111. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  13112. // width
  13113. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  13114. ]));
  13115. }
  13116. static traf(track, baseMediaDecodeTime) {
  13117. const sampleDependencyTable = MP4.sdtp(track);
  13118. const id = track.id;
  13119. const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  13120. const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  13121. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  13122. // version 0
  13123. 0x00, 0x00, 0x00,
  13124. // flags
  13125. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  13126. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  13127. // version 1
  13128. 0x00, 0x00, 0x00,
  13129. // flags
  13130. 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 +
  13131. // tfhd
  13132. 20 +
  13133. // tfdt
  13134. 8 +
  13135. // traf header
  13136. 16 +
  13137. // mfhd
  13138. 8 +
  13139. // moof header
  13140. 8),
  13141. // mdat header
  13142. sampleDependencyTable);
  13143. }
  13144. /**
  13145. * Generate a track box.
  13146. * @param track a track definition
  13147. */
  13148. static trak(track) {
  13149. track.duration = track.duration || 0xffffffff;
  13150. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  13151. }
  13152. static trex(track) {
  13153. const id = track.id;
  13154. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  13155. // version 0
  13156. 0x00, 0x00, 0x00,
  13157. // flags
  13158. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  13159. // track_ID
  13160. 0x00, 0x00, 0x00, 0x01,
  13161. // default_sample_description_index
  13162. 0x00, 0x00, 0x00, 0x00,
  13163. // default_sample_duration
  13164. 0x00, 0x00, 0x00, 0x00,
  13165. // default_sample_size
  13166. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  13167. ]));
  13168. }
  13169. static trun(track, offset) {
  13170. const samples = track.samples || [];
  13171. const len = samples.length;
  13172. const arraylen = 12 + 16 * len;
  13173. const array = new Uint8Array(arraylen);
  13174. let i;
  13175. let sample;
  13176. let duration;
  13177. let size;
  13178. let flags;
  13179. let cts;
  13180. offset += 8 + arraylen;
  13181. array.set([track.type === 'video' ? 0x01 : 0x00,
  13182. // version 1 for video with signed-int sample_composition_time_offset
  13183. 0x00, 0x0f, 0x01,
  13184. // flags
  13185. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  13186. // sample_count
  13187. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  13188. ], 0);
  13189. for (i = 0; i < len; i++) {
  13190. sample = samples[i];
  13191. duration = sample.duration;
  13192. size = sample.size;
  13193. flags = sample.flags;
  13194. cts = sample.cts;
  13195. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  13196. // sample_duration
  13197. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  13198. // sample_size
  13199. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  13200. // sample_flags
  13201. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  13202. ], 12 + 16 * i);
  13203. }
  13204. return MP4.box(MP4.types.trun, array);
  13205. }
  13206. static initSegment(tracks) {
  13207. if (!MP4.types) {
  13208. MP4.init();
  13209. }
  13210. const movie = MP4.moov(tracks);
  13211. const result = appendUint8Array(MP4.FTYP, movie);
  13212. return result;
  13213. }
  13214. }
  13215. MP4.types = void 0;
  13216. MP4.HDLR_TYPES = void 0;
  13217. MP4.STTS = void 0;
  13218. MP4.STSC = void 0;
  13219. MP4.STCO = void 0;
  13220. MP4.STSZ = void 0;
  13221. MP4.VMHD = void 0;
  13222. MP4.SMHD = void 0;
  13223. MP4.STSD = void 0;
  13224. MP4.FTYP = void 0;
  13225. MP4.DINF = void 0;
  13226. const MPEG_TS_CLOCK_FREQ_HZ = 90000;
  13227. function toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {
  13228. const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  13229. return round ? Math.round(result) : result;
  13230. }
  13231. function toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {
  13232. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  13233. }
  13234. function toMsFromMpegTsClock(baseTime, round = false) {
  13235. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  13236. }
  13237. function toMpegTsClockFromTimescale(baseTime, srcScale = 1) {
  13238. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  13239. }
  13240. const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  13241. const AAC_SAMPLES_PER_FRAME = 1024;
  13242. const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  13243. const AC3_SAMPLES_PER_FRAME = 1536;
  13244. let chromeVersion = null;
  13245. let safariWebkitVersion = null;
  13246. class MP4Remuxer {
  13247. constructor(observer, config, typeSupported, vendor = '') {
  13248. this.observer = void 0;
  13249. this.config = void 0;
  13250. this.typeSupported = void 0;
  13251. this.ISGenerated = false;
  13252. this._initPTS = null;
  13253. this._initDTS = null;
  13254. this.nextAvcDts = null;
  13255. this.nextAudioPts = null;
  13256. this.videoSampleDuration = null;
  13257. this.isAudioContiguous = false;
  13258. this.isVideoContiguous = false;
  13259. this.videoTrackConfig = void 0;
  13260. this.observer = observer;
  13261. this.config = config;
  13262. this.typeSupported = typeSupported;
  13263. this.ISGenerated = false;
  13264. if (chromeVersion === null) {
  13265. const userAgent = navigator.userAgent || '';
  13266. const result = userAgent.match(/Chrome\/(\d+)/i);
  13267. chromeVersion = result ? parseInt(result[1]) : 0;
  13268. }
  13269. if (safariWebkitVersion === null) {
  13270. const result = navigator.userAgent.match(/Safari\/(\d+)/i);
  13271. safariWebkitVersion = result ? parseInt(result[1]) : 0;
  13272. }
  13273. }
  13274. destroy() {
  13275. // @ts-ignore
  13276. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  13277. }
  13278. resetTimeStamp(defaultTimeStamp) {
  13279. logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  13280. this._initPTS = this._initDTS = defaultTimeStamp;
  13281. }
  13282. resetNextTimestamp() {
  13283. logger.log('[mp4-remuxer]: reset next timestamp');
  13284. this.isVideoContiguous = false;
  13285. this.isAudioContiguous = false;
  13286. }
  13287. resetInitSegment() {
  13288. logger.log('[mp4-remuxer]: ISGenerated flag reset');
  13289. this.ISGenerated = false;
  13290. this.videoTrackConfig = undefined;
  13291. }
  13292. getVideoStartPts(videoSamples) {
  13293. let rolloverDetected = false;
  13294. const startPTS = videoSamples.reduce((minPTS, sample) => {
  13295. const delta = sample.pts - minPTS;
  13296. if (delta < -4294967296) {
  13297. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  13298. rolloverDetected = true;
  13299. return normalizePts(minPTS, sample.pts);
  13300. } else if (delta > 0) {
  13301. return minPTS;
  13302. } else {
  13303. return sample.pts;
  13304. }
  13305. }, videoSamples[0].pts);
  13306. if (rolloverDetected) {
  13307. logger.debug('PTS rollover detected');
  13308. }
  13309. return startPTS;
  13310. }
  13311. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  13312. let video;
  13313. let audio;
  13314. let initSegment;
  13315. let text;
  13316. let id3;
  13317. let independent;
  13318. let audioTimeOffset = timeOffset;
  13319. let videoTimeOffset = timeOffset;
  13320. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  13321. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  13322. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  13323. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  13324. // then we can remux one track without waiting for the other.
  13325. const hasAudio = audioTrack.pid > -1;
  13326. const hasVideo = videoTrack.pid > -1;
  13327. const length = videoTrack.samples.length;
  13328. const enoughAudioSamples = audioTrack.samples.length > 0;
  13329. const enoughVideoSamples = flush && length > 0 || length > 1;
  13330. const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  13331. if (canRemuxAvc) {
  13332. if (this.ISGenerated) {
  13333. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  13334. const config = this.videoTrackConfig;
  13335. 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]))) {
  13336. this.resetInitSegment();
  13337. }
  13338. } else {
  13339. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13340. }
  13341. const isVideoContiguous = this.isVideoContiguous;
  13342. let firstKeyFrameIndex = -1;
  13343. let firstKeyFramePTS;
  13344. if (enoughVideoSamples) {
  13345. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  13346. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  13347. independent = true;
  13348. if (firstKeyFrameIndex > 0) {
  13349. logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);
  13350. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13351. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  13352. videoTrack.dropped += firstKeyFrameIndex;
  13353. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  13354. firstKeyFramePTS = videoTimeOffset;
  13355. } else if (firstKeyFrameIndex === -1) {
  13356. logger.warn(`[mp4-remuxer]: No keyframe found out of ${length} video samples`);
  13357. independent = false;
  13358. }
  13359. }
  13360. }
  13361. if (this.ISGenerated) {
  13362. if (enoughAudioSamples && enoughVideoSamples) {
  13363. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  13364. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  13365. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  13366. // drift between audio and video streams
  13367. const startPTS = this.getVideoStartPts(videoTrack.samples);
  13368. const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;
  13369. const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13370. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13371. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13372. }
  13373. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  13374. if (enoughAudioSamples) {
  13375. // if initSegment was generated without audio samples, regenerate it again
  13376. if (!audioTrack.samplerate) {
  13377. logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  13378. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13379. }
  13380. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  13381. if (enoughVideoSamples) {
  13382. const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13383. // if initSegment was generated without video samples, regenerate it again
  13384. if (!videoTrack.inputTimeScale) {
  13385. logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  13386. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13387. }
  13388. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13389. }
  13390. } else if (enoughVideoSamples) {
  13391. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13392. }
  13393. if (video) {
  13394. video.firstKeyFrame = firstKeyFrameIndex;
  13395. video.independent = firstKeyFrameIndex !== -1;
  13396. video.firstKeyFramePTS = firstKeyFramePTS;
  13397. }
  13398. }
  13399. }
  13400. // Allow ID3 and text to remux, even if more audio/video samples are required
  13401. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13402. if (id3Track.samples.length) {
  13403. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13404. }
  13405. if (textTrack.samples.length) {
  13406. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13407. }
  13408. }
  13409. return {
  13410. audio,
  13411. video,
  13412. initSegment,
  13413. independent,
  13414. text,
  13415. id3
  13416. };
  13417. }
  13418. generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13419. const audioSamples = audioTrack.samples;
  13420. const videoSamples = videoTrack.samples;
  13421. const typeSupported = this.typeSupported;
  13422. const tracks = {};
  13423. const _initPTS = this._initPTS;
  13424. let computePTSDTS = !_initPTS || accurateTimeOffset;
  13425. let container = 'audio/mp4';
  13426. let initPTS;
  13427. let initDTS;
  13428. let timescale;
  13429. if (computePTSDTS) {
  13430. initPTS = initDTS = Infinity;
  13431. }
  13432. if (audioTrack.config && audioSamples.length) {
  13433. // let's use audio sampling rate as MP4 time scale.
  13434. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  13435. // using audio sampling rate here helps having an integer MP4 frame duration
  13436. // this avoids potential rounding issue and AV sync issue
  13437. audioTrack.timescale = audioTrack.samplerate;
  13438. switch (audioTrack.segmentCodec) {
  13439. case 'mp3':
  13440. if (typeSupported.mpeg) {
  13441. // Chrome and Safari
  13442. container = 'audio/mpeg';
  13443. audioTrack.codec = '';
  13444. } else if (typeSupported.mp3) {
  13445. // Firefox
  13446. audioTrack.codec = 'mp3';
  13447. }
  13448. break;
  13449. case 'ac3':
  13450. audioTrack.codec = 'ac-3';
  13451. break;
  13452. }
  13453. tracks.audio = {
  13454. id: 'audio',
  13455. container: container,
  13456. codec: audioTrack.codec,
  13457. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13458. metadata: {
  13459. channelCount: audioTrack.channelCount
  13460. }
  13461. };
  13462. if (computePTSDTS) {
  13463. timescale = audioTrack.inputTimeScale;
  13464. if (!_initPTS || timescale !== _initPTS.timescale) {
  13465. // remember first PTS of this demuxing context. for audio, PTS = DTS
  13466. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  13467. } else {
  13468. computePTSDTS = false;
  13469. }
  13470. }
  13471. }
  13472. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13473. // let's use input time scale as MP4 video timescale
  13474. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  13475. videoTrack.timescale = videoTrack.inputTimeScale;
  13476. tracks.video = {
  13477. id: 'main',
  13478. container: 'video/mp4',
  13479. codec: videoTrack.codec,
  13480. initSegment: MP4.initSegment([videoTrack]),
  13481. metadata: {
  13482. width: videoTrack.width,
  13483. height: videoTrack.height
  13484. }
  13485. };
  13486. if (computePTSDTS) {
  13487. timescale = videoTrack.inputTimeScale;
  13488. if (!_initPTS || timescale !== _initPTS.timescale) {
  13489. const startPTS = this.getVideoStartPts(videoSamples);
  13490. const startOffset = Math.round(timescale * timeOffset);
  13491. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  13492. initPTS = Math.min(initPTS, startPTS - startOffset);
  13493. } else {
  13494. computePTSDTS = false;
  13495. }
  13496. }
  13497. this.videoTrackConfig = {
  13498. width: videoTrack.width,
  13499. height: videoTrack.height,
  13500. pixelRatio: videoTrack.pixelRatio
  13501. };
  13502. }
  13503. if (Object.keys(tracks).length) {
  13504. this.ISGenerated = true;
  13505. if (computePTSDTS) {
  13506. this._initPTS = {
  13507. baseTime: initPTS,
  13508. timescale: timescale
  13509. };
  13510. this._initDTS = {
  13511. baseTime: initDTS,
  13512. timescale: timescale
  13513. };
  13514. } else {
  13515. initPTS = timescale = undefined;
  13516. }
  13517. return {
  13518. tracks,
  13519. initPTS,
  13520. timescale
  13521. };
  13522. }
  13523. }
  13524. remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13525. const timeScale = track.inputTimeScale;
  13526. const inputSamples = track.samples;
  13527. const outputSamples = [];
  13528. const nbSamples = inputSamples.length;
  13529. const initPTS = this._initPTS;
  13530. let nextAvcDts = this.nextAvcDts;
  13531. let offset = 8;
  13532. let mp4SampleDuration = this.videoSampleDuration;
  13533. let firstDTS;
  13534. let lastDTS;
  13535. let minPTS = Number.POSITIVE_INFINITY;
  13536. let maxPTS = Number.NEGATIVE_INFINITY;
  13537. let sortSamples = false;
  13538. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  13539. if (!contiguous || nextAvcDts === null) {
  13540. const pts = timeOffset * timeScale;
  13541. const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13542. if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {
  13543. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  13544. contiguous = true;
  13545. } else {
  13546. // if not contiguous, let's use target timeOffset
  13547. nextAvcDts = pts - cts;
  13548. }
  13549. }
  13550. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  13551. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  13552. const initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13553. for (let i = 0; i < nbSamples; i++) {
  13554. const sample = inputSamples[i];
  13555. sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
  13556. sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
  13557. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13558. sortSamples = true;
  13559. }
  13560. }
  13561. // sort video samples by DTS then PTS then demux id order
  13562. if (sortSamples) {
  13563. inputSamples.sort(function (a, b) {
  13564. const deltadts = a.dts - b.dts;
  13565. const deltapts = a.pts - b.pts;
  13566. return deltadts || deltapts;
  13567. });
  13568. }
  13569. // Get first/last DTS
  13570. firstDTS = inputSamples[0].dts;
  13571. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13572. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  13573. // set this constant duration as being the avg delta between consecutive DTS.
  13574. const inputDuration = lastDTS - firstDTS;
  13575. const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13576. // if fragment are contiguous, detect hole/overlapping between fragments
  13577. if (contiguous) {
  13578. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  13579. const delta = firstDTS - nextAvcDts;
  13580. const foundHole = delta > averageSampleDuration;
  13581. const foundOverlap = delta < -1;
  13582. if (foundHole || foundOverlap) {
  13583. if (foundHole) {
  13584. logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);
  13585. } else {
  13586. logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);
  13587. }
  13588. if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
  13589. firstDTS = nextAvcDts;
  13590. const firstPTS = inputSamples[0].pts - delta;
  13591. if (foundHole) {
  13592. inputSamples[0].dts = firstDTS;
  13593. inputSamples[0].pts = firstPTS;
  13594. } else {
  13595. for (let i = 0; i < inputSamples.length; i++) {
  13596. if (inputSamples[i].dts > firstPTS) {
  13597. break;
  13598. }
  13599. inputSamples[i].dts -= delta;
  13600. inputSamples[i].pts -= delta;
  13601. }
  13602. }
  13603. logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);
  13604. }
  13605. }
  13606. }
  13607. firstDTS = Math.max(0, firstDTS);
  13608. let nbNalu = 0;
  13609. let naluLen = 0;
  13610. let dtsStep = firstDTS;
  13611. for (let i = 0; i < nbSamples; i++) {
  13612. // compute total/avc sample length and nb of NAL units
  13613. const sample = inputSamples[i];
  13614. const units = sample.units;
  13615. const nbUnits = units.length;
  13616. let sampleLen = 0;
  13617. for (let j = 0; j < nbUnits; j++) {
  13618. sampleLen += units[j].data.length;
  13619. }
  13620. naluLen += sampleLen;
  13621. nbNalu += nbUnits;
  13622. sample.length = sampleLen;
  13623. // ensure sample monotonic DTS
  13624. if (sample.dts < dtsStep) {
  13625. sample.dts = dtsStep;
  13626. dtsStep += averageSampleDuration / 4 | 0 || 1;
  13627. } else {
  13628. dtsStep = sample.dts;
  13629. }
  13630. minPTS = Math.min(sample.pts, minPTS);
  13631. maxPTS = Math.max(sample.pts, maxPTS);
  13632. }
  13633. lastDTS = inputSamples[nbSamples - 1].dts;
  13634. /* concatenate the video data and construct the mdat in place
  13635. (need 8 more bytes to fill length and mpdat type) */
  13636. const mdatSize = naluLen + 4 * nbNalu + 8;
  13637. let mdat;
  13638. try {
  13639. mdat = new Uint8Array(mdatSize);
  13640. } catch (err) {
  13641. this.observer.emit(Events.ERROR, Events.ERROR, {
  13642. type: ErrorTypes.MUX_ERROR,
  13643. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13644. fatal: false,
  13645. error: err,
  13646. bytes: mdatSize,
  13647. reason: `fail allocating video mdat ${mdatSize}`
  13648. });
  13649. return;
  13650. }
  13651. const view = new DataView(mdat.buffer);
  13652. view.setUint32(0, mdatSize);
  13653. mdat.set(MP4.types.mdat, 4);
  13654. let stretchedLastFrame = false;
  13655. let minDtsDelta = Number.POSITIVE_INFINITY;
  13656. let minPtsDelta = Number.POSITIVE_INFINITY;
  13657. let maxDtsDelta = Number.NEGATIVE_INFINITY;
  13658. let maxPtsDelta = Number.NEGATIVE_INFINITY;
  13659. for (let i = 0; i < nbSamples; i++) {
  13660. const VideoSample = inputSamples[i];
  13661. const VideoSampleUnits = VideoSample.units;
  13662. let mp4SampleLength = 0;
  13663. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  13664. for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {
  13665. const unit = VideoSampleUnits[j];
  13666. const unitData = unit.data;
  13667. const unitDataLen = unit.data.byteLength;
  13668. view.setUint32(offset, unitDataLen);
  13669. offset += 4;
  13670. mdat.set(unitData, offset);
  13671. offset += unitDataLen;
  13672. mp4SampleLength += 4 + unitDataLen;
  13673. }
  13674. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  13675. let ptsDelta;
  13676. if (i < nbSamples - 1) {
  13677. mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;
  13678. ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;
  13679. } else {
  13680. const config = this.config;
  13681. const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;
  13682. ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;
  13683. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  13684. // In some cases, a segment's audio track duration may exceed the video track duration.
  13685. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  13686. // see if the delta to the next segment is longer than maxBufferHole.
  13687. // If so, playback would potentially get stuck, so we artificially inflate
  13688. // the duration of the last frame to minimize any potential gap between segments.
  13689. const gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  13690. const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts;
  13691. if (deltaToFrameEnd > gapTolerance) {
  13692. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  13693. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  13694. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  13695. if (mp4SampleDuration < 0) {
  13696. mp4SampleDuration = lastFrameDuration;
  13697. } else {
  13698. stretchedLastFrame = true;
  13699. }
  13700. logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);
  13701. } else {
  13702. mp4SampleDuration = lastFrameDuration;
  13703. }
  13704. } else {
  13705. mp4SampleDuration = lastFrameDuration;
  13706. }
  13707. }
  13708. const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  13709. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  13710. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  13711. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  13712. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  13713. outputSamples.push(new Mp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  13714. }
  13715. if (outputSamples.length) {
  13716. if (chromeVersion) {
  13717. if (chromeVersion < 70) {
  13718. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  13719. // https://code.google.com/p/chromium/issues/detail?id=229412
  13720. const flags = outputSamples[0].flags;
  13721. flags.dependsOn = 2;
  13722. flags.isNonSync = 0;
  13723. }
  13724. } else if (safariWebkitVersion) {
  13725. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  13726. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  13727. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  13728. logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  13729. let dts = firstDTS;
  13730. for (let i = 0, len = outputSamples.length; i < len; i++) {
  13731. const nextDts = dts + outputSamples[i].duration;
  13732. const pts = dts + outputSamples[i].cts;
  13733. if (i < len - 1) {
  13734. const nextPts = nextDts + outputSamples[i + 1].cts;
  13735. outputSamples[i].duration = nextPts - pts;
  13736. } else {
  13737. outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;
  13738. }
  13739. outputSamples[i].cts = 0;
  13740. dts = nextDts;
  13741. }
  13742. }
  13743. }
  13744. }
  13745. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  13746. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  13747. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  13748. this.videoSampleDuration = mp4SampleDuration;
  13749. this.isVideoContiguous = true;
  13750. const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  13751. samples: outputSamples
  13752. }));
  13753. const type = 'video';
  13754. const data = {
  13755. data1: moof,
  13756. data2: mdat,
  13757. startPTS: minPTS / timeScale,
  13758. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  13759. startDTS: firstDTS / timeScale,
  13760. endDTS: nextAvcDts / timeScale,
  13761. type,
  13762. hasAudio: false,
  13763. hasVideo: true,
  13764. nb: outputSamples.length,
  13765. dropped: track.dropped
  13766. };
  13767. track.samples = [];
  13768. track.dropped = 0;
  13769. return data;
  13770. }
  13771. getSamplesPerFrame(track) {
  13772. switch (track.segmentCodec) {
  13773. case 'mp3':
  13774. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  13775. case 'ac3':
  13776. return AC3_SAMPLES_PER_FRAME;
  13777. default:
  13778. return AAC_SAMPLES_PER_FRAME;
  13779. }
  13780. }
  13781. remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  13782. const inputTimeScale = track.inputTimeScale;
  13783. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13784. const scaleFactor = inputTimeScale / mp4timeScale;
  13785. const mp4SampleDuration = this.getSamplesPerFrame(track);
  13786. const inputSampleDuration = mp4SampleDuration * scaleFactor;
  13787. const initPTS = this._initPTS;
  13788. const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  13789. const outputSamples = [];
  13790. const alignedWithVideo = videoTimeOffset !== undefined;
  13791. let inputSamples = track.samples;
  13792. let offset = rawMPEG ? 0 : 8;
  13793. let nextAudioPts = this.nextAudioPts || -1;
  13794. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  13795. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  13796. // for sake of clarity:
  13797. // consecutive fragments are frags with
  13798. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  13799. // - less than 20 audio frames distance
  13800. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  13801. // this helps ensuring audio continuity
  13802. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  13803. const timeOffsetMpegTS = timeOffset * inputTimeScale;
  13804. const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  13805. 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);
  13806. // compute normalized PTS
  13807. inputSamples.forEach(function (sample) {
  13808. sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
  13809. });
  13810. if (!contiguous || nextAudioPts < 0) {
  13811. // filter out sample with negative PTS that are not playable anyway
  13812. // if we don't remove these negative samples, they will shift all audio samples forward.
  13813. // leading to audio overlap between current / next fragment
  13814. inputSamples = inputSamples.filter(sample => sample.pts >= 0);
  13815. // in case all samples have negative PTS, and have been filtered out, return now
  13816. if (!inputSamples.length) {
  13817. return;
  13818. }
  13819. if (videoTimeOffset === 0) {
  13820. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  13821. nextAudioPts = 0;
  13822. } else if (accurateTimeOffset && !alignedWithVideo) {
  13823. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  13824. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  13825. } else {
  13826. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  13827. nextAudioPts = inputSamples[0].pts;
  13828. }
  13829. }
  13830. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  13831. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  13832. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  13833. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  13834. // frame.
  13835. if (track.segmentCodec === 'aac') {
  13836. const maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  13837. for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  13838. // First, let's see how far off this frame is from where we expect it to be
  13839. const sample = inputSamples[i];
  13840. const pts = sample.pts;
  13841. const delta = pts - nextPts;
  13842. const duration = Math.abs(1000 * delta / inputTimeScale);
  13843. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  13844. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  13845. if (i === 0) {
  13846. logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1000 * delta / inputTimeScale)} ms.`);
  13847. this.nextAudioPts = nextAudioPts = nextPts = pts;
  13848. }
  13849. } // eslint-disable-line brace-style
  13850. // Insert missing frames if:
  13851. // 1: We're more than maxAudioFramesDrift frame away
  13852. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  13853. // 3: currentTime (aka nextPtsNorm) is not 0
  13854. // 4: remuxing with video (videoTimeOffset !== undefined)
  13855. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  13856. let missing = Math.round(delta / inputSampleDuration);
  13857. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  13858. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  13859. nextPts = pts - missing * inputSampleDuration;
  13860. if (nextPts < 0) {
  13861. missing--;
  13862. nextPts += inputSampleDuration;
  13863. }
  13864. if (i === 0) {
  13865. this.nextAudioPts = nextAudioPts = nextPts;
  13866. }
  13867. logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);
  13868. for (let j = 0; j < missing; j++) {
  13869. const newStamp = Math.max(nextPts, 0);
  13870. let fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  13871. if (!fillFrame) {
  13872. logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  13873. fillFrame = sample.unit.subarray();
  13874. }
  13875. inputSamples.splice(i, 0, {
  13876. unit: fillFrame,
  13877. pts: newStamp
  13878. });
  13879. nextPts += inputSampleDuration;
  13880. i++;
  13881. }
  13882. }
  13883. sample.pts = nextPts;
  13884. nextPts += inputSampleDuration;
  13885. }
  13886. }
  13887. let firstPTS = null;
  13888. let lastPTS = null;
  13889. let mdat;
  13890. let mdatSize = 0;
  13891. let sampleLength = inputSamples.length;
  13892. while (sampleLength--) {
  13893. mdatSize += inputSamples[sampleLength].unit.byteLength;
  13894. }
  13895. for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {
  13896. const audioSample = inputSamples[j];
  13897. const unit = audioSample.unit;
  13898. let pts = audioSample.pts;
  13899. if (lastPTS !== null) {
  13900. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  13901. // the previous sample
  13902. const prevSample = outputSamples[j - 1];
  13903. prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);
  13904. } else {
  13905. if (contiguous && track.segmentCodec === 'aac') {
  13906. // set PTS/DTS to expected PTS/DTS
  13907. pts = nextAudioPts;
  13908. }
  13909. // remember first PTS of our audioSamples
  13910. firstPTS = pts;
  13911. if (mdatSize > 0) {
  13912. /* concatenate the audio data and construct the mdat in place
  13913. (need 8 more bytes to fill length and mdat type) */
  13914. mdatSize += offset;
  13915. try {
  13916. mdat = new Uint8Array(mdatSize);
  13917. } catch (err) {
  13918. this.observer.emit(Events.ERROR, Events.ERROR, {
  13919. type: ErrorTypes.MUX_ERROR,
  13920. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13921. fatal: false,
  13922. error: err,
  13923. bytes: mdatSize,
  13924. reason: `fail allocating audio mdat ${mdatSize}`
  13925. });
  13926. return;
  13927. }
  13928. if (!rawMPEG) {
  13929. const view = new DataView(mdat.buffer);
  13930. view.setUint32(0, mdatSize);
  13931. mdat.set(MP4.types.mdat, 4);
  13932. }
  13933. } else {
  13934. // no audio samples
  13935. return;
  13936. }
  13937. }
  13938. mdat.set(unit, offset);
  13939. const unitLen = unit.byteLength;
  13940. offset += unitLen;
  13941. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  13942. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  13943. // becomes the PTS diff with the previous sample
  13944. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  13945. lastPTS = pts;
  13946. }
  13947. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  13948. const nbSamples = outputSamples.length;
  13949. if (!nbSamples) {
  13950. return;
  13951. }
  13952. // The next audio sample PTS should be equal to last sample PTS + duration
  13953. const lastSample = outputSamples[outputSamples.length - 1];
  13954. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  13955. // Set the track samples from inputSamples to outputSamples before remuxing
  13956. const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  13957. samples: outputSamples
  13958. }));
  13959. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  13960. track.samples = [];
  13961. const start = firstPTS / inputTimeScale;
  13962. const end = nextAudioPts / inputTimeScale;
  13963. const type = 'audio';
  13964. const audioData = {
  13965. data1: moof,
  13966. data2: mdat,
  13967. startPTS: start,
  13968. endPTS: end,
  13969. startDTS: start,
  13970. endDTS: end,
  13971. type,
  13972. hasAudio: true,
  13973. hasVideo: false,
  13974. nb: nbSamples
  13975. };
  13976. this.isAudioContiguous = true;
  13977. return audioData;
  13978. }
  13979. remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  13980. const inputTimeScale = track.inputTimeScale;
  13981. const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13982. const scaleFactor = inputTimeScale / mp4timeScale;
  13983. const nextAudioPts = this.nextAudioPts;
  13984. // sync with video's timestamp
  13985. const initDTS = this._initDTS;
  13986. const init90kHz = initDTS.baseTime * 90000 / initDTS.timescale;
  13987. const startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz;
  13988. const endDTS = videoData.endDTS * inputTimeScale + init90kHz;
  13989. // one sample's duration value
  13990. const frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  13991. // samples count of this segment's duration
  13992. const nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  13993. // silent frame
  13994. const silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  13995. logger.warn('[mp4-remuxer]: remux empty Audio');
  13996. // Can't remux if we can't generate a silent frame...
  13997. if (!silentFrame) {
  13998. logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  13999. return;
  14000. }
  14001. const samples = [];
  14002. for (let i = 0; i < nbSamples; i++) {
  14003. const stamp = startDTS + i * frameDuration;
  14004. samples.push({
  14005. unit: silentFrame,
  14006. pts: stamp,
  14007. dts: stamp
  14008. });
  14009. }
  14010. track.samples = samples;
  14011. return this.remuxAudio(track, timeOffset, contiguous, false);
  14012. }
  14013. }
  14014. function normalizePts(value, reference) {
  14015. let offset;
  14016. if (reference === null) {
  14017. return value;
  14018. }
  14019. if (reference < value) {
  14020. // - 2^33
  14021. offset = -8589934592;
  14022. } else {
  14023. // + 2^33
  14024. offset = 8589934592;
  14025. }
  14026. /* PTS is 33bit (from 0 to 2^33 -1)
  14027. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  14028. PTS looping occured. fill the gap */
  14029. while (Math.abs(value - reference) > 4294967296) {
  14030. value += offset;
  14031. }
  14032. return value;
  14033. }
  14034. function findKeyframeIndex(samples) {
  14035. for (let i = 0; i < samples.length; i++) {
  14036. if (samples[i].key) {
  14037. return i;
  14038. }
  14039. }
  14040. return -1;
  14041. }
  14042. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  14043. const length = track.samples.length;
  14044. if (!length) {
  14045. return;
  14046. }
  14047. const inputTimeScale = track.inputTimeScale;
  14048. for (let index = 0; index < length; index++) {
  14049. const sample = track.samples[index];
  14050. // setting id3 pts, dts to relative time
  14051. // using this._initPTS and this._initDTS to calculate relative time
  14052. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14053. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14054. }
  14055. const samples = track.samples;
  14056. track.samples = [];
  14057. return {
  14058. samples
  14059. };
  14060. }
  14061. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  14062. const length = track.samples.length;
  14063. if (!length) {
  14064. return;
  14065. }
  14066. const inputTimeScale = track.inputTimeScale;
  14067. for (let index = 0; index < length; index++) {
  14068. const sample = track.samples[index];
  14069. // setting text pts, dts to relative time
  14070. // using this._initPTS and this._initDTS to calculate relative time
  14071. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  14072. }
  14073. track.samples.sort((a, b) => a.pts - b.pts);
  14074. const samples = track.samples;
  14075. track.samples = [];
  14076. return {
  14077. samples
  14078. };
  14079. }
  14080. class Mp4Sample {
  14081. constructor(isKeyframe, duration, size, cts) {
  14082. this.size = void 0;
  14083. this.duration = void 0;
  14084. this.cts = void 0;
  14085. this.flags = void 0;
  14086. this.duration = duration;
  14087. this.size = size;
  14088. this.cts = cts;
  14089. this.flags = {
  14090. isLeading: 0,
  14091. isDependedOn: 0,
  14092. hasRedundancy: 0,
  14093. degradPrio: 0,
  14094. dependsOn: isKeyframe ? 2 : 1,
  14095. isNonSync: isKeyframe ? 0 : 1
  14096. };
  14097. }
  14098. }
  14099. class PassThroughRemuxer {
  14100. constructor() {
  14101. this.emitInitSegment = false;
  14102. this.audioCodec = void 0;
  14103. this.videoCodec = void 0;
  14104. this.initData = void 0;
  14105. this.initPTS = null;
  14106. this.initTracks = void 0;
  14107. this.lastEndTime = null;
  14108. }
  14109. destroy() {}
  14110. resetTimeStamp(defaultInitPTS) {
  14111. this.initPTS = defaultInitPTS;
  14112. this.lastEndTime = null;
  14113. }
  14114. resetNextTimestamp() {
  14115. this.lastEndTime = null;
  14116. }
  14117. resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  14118. this.audioCodec = audioCodec;
  14119. this.videoCodec = videoCodec;
  14120. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  14121. this.emitInitSegment = true;
  14122. }
  14123. generateInitSegment(initSegment) {
  14124. let {
  14125. audioCodec,
  14126. videoCodec
  14127. } = this;
  14128. if (!(initSegment != null && initSegment.byteLength)) {
  14129. this.initTracks = undefined;
  14130. this.initData = undefined;
  14131. return;
  14132. }
  14133. const initData = this.initData = parseInitSegment(initSegment);
  14134. // Get codec from initSegment or fallback to default
  14135. if (initData.audio) {
  14136. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
  14137. }
  14138. if (initData.video) {
  14139. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
  14140. }
  14141. const tracks = {};
  14142. if (initData.audio && initData.video) {
  14143. tracks.audiovideo = {
  14144. container: 'video/mp4',
  14145. codec: audioCodec + ',' + videoCodec,
  14146. initSegment,
  14147. id: 'main'
  14148. };
  14149. } else if (initData.audio) {
  14150. tracks.audio = {
  14151. container: 'audio/mp4',
  14152. codec: audioCodec,
  14153. initSegment,
  14154. id: 'audio'
  14155. };
  14156. } else if (initData.video) {
  14157. tracks.video = {
  14158. container: 'video/mp4',
  14159. codec: videoCodec,
  14160. initSegment,
  14161. id: 'main'
  14162. };
  14163. } else {
  14164. logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  14165. }
  14166. this.initTracks = tracks;
  14167. }
  14168. remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  14169. var _initData, _initData2;
  14170. let {
  14171. initPTS,
  14172. lastEndTime
  14173. } = this;
  14174. const result = {
  14175. audio: undefined,
  14176. video: undefined,
  14177. text: textTrack,
  14178. id3: id3Track,
  14179. initSegment: undefined
  14180. };
  14181. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  14182. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  14183. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  14184. if (!isFiniteNumber(lastEndTime)) {
  14185. lastEndTime = this.lastEndTime = timeOffset || 0;
  14186. }
  14187. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  14188. // audio or video (or both); adding it to video was an arbitrary choice.
  14189. const data = videoTrack.samples;
  14190. if (!(data != null && data.length)) {
  14191. return result;
  14192. }
  14193. const initSegment = {
  14194. initPTS: undefined,
  14195. timescale: 1
  14196. };
  14197. let initData = this.initData;
  14198. if (!((_initData = initData) != null && _initData.length)) {
  14199. this.generateInitSegment(data);
  14200. initData = this.initData;
  14201. }
  14202. if (!((_initData2 = initData) != null && _initData2.length)) {
  14203. // We can't remux if the initSegment could not be generated
  14204. logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  14205. return result;
  14206. }
  14207. if (this.emitInitSegment) {
  14208. initSegment.tracks = this.initTracks;
  14209. this.emitInitSegment = false;
  14210. }
  14211. const duration = getDuration(data, initData);
  14212. const startDTS = getStartDTS(initData, data);
  14213. const decodeTime = startDTS === null ? timeOffset : startDTS;
  14214. if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) {
  14215. initSegment.initPTS = decodeTime - timeOffset;
  14216. if (initPTS && initPTS.timescale === 1) {
  14217. logger.warn(`Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`);
  14218. }
  14219. this.initPTS = initPTS = {
  14220. baseTime: initSegment.initPTS,
  14221. timescale: 1
  14222. };
  14223. }
  14224. const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  14225. const endTime = startTime + duration;
  14226. offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
  14227. if (duration > 0) {
  14228. this.lastEndTime = endTime;
  14229. } else {
  14230. logger.warn('Duration parsed from mp4 should be greater than zero');
  14231. this.resetNextTimestamp();
  14232. }
  14233. const hasAudio = !!initData.audio;
  14234. const hasVideo = !!initData.video;
  14235. let type = '';
  14236. if (hasAudio) {
  14237. type += 'audio';
  14238. }
  14239. if (hasVideo) {
  14240. type += 'video';
  14241. }
  14242. const track = {
  14243. data1: data,
  14244. startPTS: startTime,
  14245. startDTS: startTime,
  14246. endPTS: endTime,
  14247. endDTS: endTime,
  14248. type,
  14249. hasAudio,
  14250. hasVideo,
  14251. nb: 1,
  14252. dropped: 0
  14253. };
  14254. result.audio = track.type === 'audio' ? track : undefined;
  14255. result.video = track.type !== 'audio' ? track : undefined;
  14256. result.initSegment = initSegment;
  14257. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  14258. if (textTrack.samples.length) {
  14259. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  14260. }
  14261. return result;
  14262. }
  14263. }
  14264. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  14265. if (initPTS === null) {
  14266. return true;
  14267. }
  14268. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  14269. const minDuration = Math.max(duration, 1);
  14270. const startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  14271. return Math.abs(startTime - timeOffset) > minDuration;
  14272. }
  14273. function getParsedTrackCodec(track, type) {
  14274. const parsedCodec = track == null ? void 0 : track.codec;
  14275. if (parsedCodec && parsedCodec.length > 4) {
  14276. return parsedCodec;
  14277. }
  14278. if (type === ElementaryStreamTypes.AUDIO) {
  14279. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  14280. return parsedCodec;
  14281. }
  14282. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  14283. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  14284. const preferManagedMediaSource = false;
  14285. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  14286. }
  14287. const result = 'mp4a.40.5';
  14288. logger.info(`Parsed audio codec "${parsedCodec}" or audio object type not handled. Using "${result}"`);
  14289. return result;
  14290. }
  14291. // Provide defaults based on codec type
  14292. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  14293. logger.warn(`Unhandled video codec "${parsedCodec}"`);
  14294. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  14295. return 'hvc1.1.6.L120.90';
  14296. }
  14297. if (parsedCodec === 'av01') {
  14298. return 'av01.0.04M.08';
  14299. }
  14300. return 'avc1.42e01e';
  14301. }
  14302. let now;
  14303. // performance.now() not available on WebWorker, at least on Safari Desktop
  14304. try {
  14305. now = self.performance.now.bind(self.performance);
  14306. } catch (err) {
  14307. logger.debug('Unable to use Performance API on this environment');
  14308. now = optionalSelf == null ? void 0 : optionalSelf.Date.now;
  14309. }
  14310. const muxConfig = [{
  14311. demux: MP4Demuxer,
  14312. remux: PassThroughRemuxer
  14313. }, {
  14314. demux: TSDemuxer,
  14315. remux: MP4Remuxer
  14316. }, {
  14317. demux: AACDemuxer,
  14318. remux: MP4Remuxer
  14319. }, {
  14320. demux: MP3Demuxer,
  14321. remux: MP4Remuxer
  14322. }];
  14323. {
  14324. muxConfig.splice(2, 0, {
  14325. demux: AC3Demuxer,
  14326. remux: MP4Remuxer
  14327. });
  14328. }
  14329. class Transmuxer {
  14330. constructor(observer, typeSupported, config, vendor, id) {
  14331. this.async = false;
  14332. this.observer = void 0;
  14333. this.typeSupported = void 0;
  14334. this.config = void 0;
  14335. this.vendor = void 0;
  14336. this.id = void 0;
  14337. this.demuxer = void 0;
  14338. this.remuxer = void 0;
  14339. this.decrypter = void 0;
  14340. this.probe = void 0;
  14341. this.decryptionPromise = null;
  14342. this.transmuxConfig = void 0;
  14343. this.currentTransmuxState = void 0;
  14344. this.observer = observer;
  14345. this.typeSupported = typeSupported;
  14346. this.config = config;
  14347. this.vendor = vendor;
  14348. this.id = id;
  14349. }
  14350. configure(transmuxConfig) {
  14351. this.transmuxConfig = transmuxConfig;
  14352. if (this.decrypter) {
  14353. this.decrypter.reset();
  14354. }
  14355. }
  14356. push(data, decryptdata, chunkMeta, state) {
  14357. const stats = chunkMeta.transmuxing;
  14358. stats.executeStart = now();
  14359. let uintData = new Uint8Array(data);
  14360. const {
  14361. currentTransmuxState,
  14362. transmuxConfig
  14363. } = this;
  14364. if (state) {
  14365. this.currentTransmuxState = state;
  14366. }
  14367. const {
  14368. contiguous,
  14369. discontinuity,
  14370. trackSwitch,
  14371. accurateTimeOffset,
  14372. timeOffset,
  14373. initSegmentChange
  14374. } = state || currentTransmuxState;
  14375. const {
  14376. audioCodec,
  14377. videoCodec,
  14378. defaultInitPts,
  14379. duration,
  14380. initSegmentData
  14381. } = transmuxConfig;
  14382. const keyData = getEncryptionType(uintData, decryptdata);
  14383. if (keyData && keyData.method === 'AES-128') {
  14384. const decrypter = this.getDecrypter();
  14385. // Software decryption is synchronous; webCrypto is not
  14386. if (decrypter.isSync()) {
  14387. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  14388. // data is handled in the flush() call
  14389. let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  14390. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  14391. const loadingParts = chunkMeta.part > -1;
  14392. if (loadingParts) {
  14393. decryptedData = decrypter.flush();
  14394. }
  14395. if (!decryptedData) {
  14396. stats.executeEnd = now();
  14397. return emptyResult(chunkMeta);
  14398. }
  14399. uintData = new Uint8Array(decryptedData);
  14400. } else {
  14401. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(decryptedData => {
  14402. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  14403. // the decrypted data has been transmuxed
  14404. const result = this.push(decryptedData, null, chunkMeta);
  14405. this.decryptionPromise = null;
  14406. return result;
  14407. });
  14408. return this.decryptionPromise;
  14409. }
  14410. }
  14411. const resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  14412. if (resetMuxers) {
  14413. const error = this.configureTransmuxer(uintData);
  14414. if (error) {
  14415. logger.warn(`[transmuxer] ${error.message}`);
  14416. this.observer.emit(Events.ERROR, Events.ERROR, {
  14417. type: ErrorTypes.MEDIA_ERROR,
  14418. details: ErrorDetails.FRAG_PARSING_ERROR,
  14419. fatal: false,
  14420. error,
  14421. reason: error.message
  14422. });
  14423. stats.executeEnd = now();
  14424. return emptyResult(chunkMeta);
  14425. }
  14426. }
  14427. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  14428. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  14429. }
  14430. if (discontinuity || initSegmentChange || resetMuxers) {
  14431. this.resetInitialTimestamp(defaultInitPts);
  14432. }
  14433. if (!contiguous) {
  14434. this.resetContiguity();
  14435. }
  14436. const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14437. const currentState = this.currentTransmuxState;
  14438. currentState.contiguous = true;
  14439. currentState.discontinuity = false;
  14440. currentState.trackSwitch = false;
  14441. stats.executeEnd = now();
  14442. return result;
  14443. }
  14444. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  14445. flush(chunkMeta) {
  14446. const stats = chunkMeta.transmuxing;
  14447. stats.executeStart = now();
  14448. const {
  14449. decrypter,
  14450. currentTransmuxState,
  14451. decryptionPromise
  14452. } = this;
  14453. if (decryptionPromise) {
  14454. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  14455. // only flushing is required for async decryption
  14456. return decryptionPromise.then(() => {
  14457. return this.flush(chunkMeta);
  14458. });
  14459. }
  14460. const transmuxResults = [];
  14461. const {
  14462. timeOffset
  14463. } = currentTransmuxState;
  14464. if (decrypter) {
  14465. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  14466. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  14467. // or for progressive downloads with small segments)
  14468. const decryptedData = decrypter.flush();
  14469. if (decryptedData) {
  14470. // Push always returns a TransmuxerResult if decryptdata is null
  14471. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  14472. }
  14473. }
  14474. const {
  14475. demuxer,
  14476. remuxer
  14477. } = this;
  14478. if (!demuxer || !remuxer) {
  14479. // If probing failed, then Hls.js has been given content its not able to handle
  14480. stats.executeEnd = now();
  14481. return [emptyResult(chunkMeta)];
  14482. }
  14483. const demuxResultOrPromise = demuxer.flush(timeOffset);
  14484. if (isPromise(demuxResultOrPromise)) {
  14485. // Decrypt final SAMPLE-AES samples
  14486. return demuxResultOrPromise.then(demuxResult => {
  14487. this.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14488. return transmuxResults;
  14489. });
  14490. }
  14491. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14492. return transmuxResults;
  14493. }
  14494. flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14495. const {
  14496. audioTrack,
  14497. videoTrack,
  14498. id3Track,
  14499. textTrack
  14500. } = demuxResult;
  14501. const {
  14502. accurateTimeOffset,
  14503. timeOffset
  14504. } = this.currentTransmuxState;
  14505. logger.log(`[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''} of level ${chunkMeta.level}`);
  14506. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14507. transmuxResults.push({
  14508. remuxResult,
  14509. chunkMeta
  14510. });
  14511. chunkMeta.transmuxing.executeEnd = now();
  14512. }
  14513. resetInitialTimestamp(defaultInitPts) {
  14514. const {
  14515. demuxer,
  14516. remuxer
  14517. } = this;
  14518. if (!demuxer || !remuxer) {
  14519. return;
  14520. }
  14521. demuxer.resetTimeStamp(defaultInitPts);
  14522. remuxer.resetTimeStamp(defaultInitPts);
  14523. }
  14524. resetContiguity() {
  14525. const {
  14526. demuxer,
  14527. remuxer
  14528. } = this;
  14529. if (!demuxer || !remuxer) {
  14530. return;
  14531. }
  14532. demuxer.resetContiguity();
  14533. remuxer.resetNextTimestamp();
  14534. }
  14535. resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14536. const {
  14537. demuxer,
  14538. remuxer
  14539. } = this;
  14540. if (!demuxer || !remuxer) {
  14541. return;
  14542. }
  14543. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14544. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14545. }
  14546. destroy() {
  14547. if (this.demuxer) {
  14548. this.demuxer.destroy();
  14549. this.demuxer = undefined;
  14550. }
  14551. if (this.remuxer) {
  14552. this.remuxer.destroy();
  14553. this.remuxer = undefined;
  14554. }
  14555. }
  14556. transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14557. let result;
  14558. if (keyData && keyData.method === 'SAMPLE-AES') {
  14559. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14560. } else {
  14561. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14562. }
  14563. return result;
  14564. }
  14565. transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14566. const {
  14567. audioTrack,
  14568. videoTrack,
  14569. id3Track,
  14570. textTrack
  14571. } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);
  14572. const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14573. return {
  14574. remuxResult,
  14575. chunkMeta
  14576. };
  14577. }
  14578. transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14579. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {
  14580. const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14581. return {
  14582. remuxResult,
  14583. chunkMeta
  14584. };
  14585. });
  14586. }
  14587. configureTransmuxer(data) {
  14588. const {
  14589. config,
  14590. observer,
  14591. typeSupported,
  14592. vendor
  14593. } = this;
  14594. // probe for content type
  14595. let mux;
  14596. for (let i = 0, len = muxConfig.length; i < len; i++) {
  14597. var _muxConfig$i$demux;
  14598. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data)) {
  14599. mux = muxConfig[i];
  14600. break;
  14601. }
  14602. }
  14603. if (!mux) {
  14604. return new Error('Failed to find demuxer by probing fragment data');
  14605. }
  14606. // so let's check that current remuxer and demuxer are still valid
  14607. const demuxer = this.demuxer;
  14608. const remuxer = this.remuxer;
  14609. const Remuxer = mux.remux;
  14610. const Demuxer = mux.demux;
  14611. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14612. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  14613. }
  14614. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14615. this.demuxer = new Demuxer(observer, config, typeSupported);
  14616. this.probe = Demuxer.probe;
  14617. }
  14618. }
  14619. needsProbing(discontinuity, trackSwitch) {
  14620. // in case of continuity change, or track switch
  14621. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  14622. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14623. }
  14624. getDecrypter() {
  14625. let decrypter = this.decrypter;
  14626. if (!decrypter) {
  14627. decrypter = this.decrypter = new Decrypter(this.config);
  14628. }
  14629. return decrypter;
  14630. }
  14631. }
  14632. function getEncryptionType(data, decryptData) {
  14633. let encryptionType = null;
  14634. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14635. encryptionType = decryptData;
  14636. }
  14637. return encryptionType;
  14638. }
  14639. const emptyResult = chunkMeta => ({
  14640. remuxResult: {},
  14641. chunkMeta
  14642. });
  14643. function isPromise(p) {
  14644. return 'then' in p && p.then instanceof Function;
  14645. }
  14646. class TransmuxConfig {
  14647. constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14648. this.audioCodec = void 0;
  14649. this.videoCodec = void 0;
  14650. this.initSegmentData = void 0;
  14651. this.duration = void 0;
  14652. this.defaultInitPts = void 0;
  14653. this.audioCodec = audioCodec;
  14654. this.videoCodec = videoCodec;
  14655. this.initSegmentData = initSegmentData;
  14656. this.duration = duration;
  14657. this.defaultInitPts = defaultInitPts || null;
  14658. }
  14659. }
  14660. class TransmuxState {
  14661. constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14662. this.discontinuity = void 0;
  14663. this.contiguous = void 0;
  14664. this.accurateTimeOffset = void 0;
  14665. this.trackSwitch = void 0;
  14666. this.timeOffset = void 0;
  14667. this.initSegmentChange = void 0;
  14668. this.discontinuity = discontinuity;
  14669. this.contiguous = contiguous;
  14670. this.accurateTimeOffset = accurateTimeOffset;
  14671. this.trackSwitch = trackSwitch;
  14672. this.timeOffset = timeOffset;
  14673. this.initSegmentChange = initSegmentChange;
  14674. }
  14675. }
  14676. var eventemitter3 = {exports: {}};
  14677. (function (module) {
  14678. var has = Object.prototype.hasOwnProperty
  14679. , prefix = '~';
  14680. /**
  14681. * Constructor to create a storage for our `EE` objects.
  14682. * An `Events` instance is a plain object whose properties are event names.
  14683. *
  14684. * @constructor
  14685. * @private
  14686. */
  14687. function Events() {}
  14688. //
  14689. // We try to not inherit from `Object.prototype`. In some engines creating an
  14690. // instance in this way is faster than calling `Object.create(null)` directly.
  14691. // If `Object.create(null)` is not supported we prefix the event names with a
  14692. // character to make sure that the built-in object properties are not
  14693. // overridden or used as an attack vector.
  14694. //
  14695. if (Object.create) {
  14696. Events.prototype = Object.create(null);
  14697. //
  14698. // This hack is needed because the `__proto__` property is still inherited in
  14699. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  14700. //
  14701. if (!new Events().__proto__) prefix = false;
  14702. }
  14703. /**
  14704. * Representation of a single event listener.
  14705. *
  14706. * @param {Function} fn The listener function.
  14707. * @param {*} context The context to invoke the listener with.
  14708. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  14709. * @constructor
  14710. * @private
  14711. */
  14712. function EE(fn, context, once) {
  14713. this.fn = fn;
  14714. this.context = context;
  14715. this.once = once || false;
  14716. }
  14717. /**
  14718. * Add a listener for a given event.
  14719. *
  14720. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  14721. * @param {(String|Symbol)} event The event name.
  14722. * @param {Function} fn The listener function.
  14723. * @param {*} context The context to invoke the listener with.
  14724. * @param {Boolean} once Specify if the listener is a one-time listener.
  14725. * @returns {EventEmitter}
  14726. * @private
  14727. */
  14728. function addListener(emitter, event, fn, context, once) {
  14729. if (typeof fn !== 'function') {
  14730. throw new TypeError('The listener must be a function');
  14731. }
  14732. var listener = new EE(fn, context || emitter, once)
  14733. , evt = prefix ? prefix + event : event;
  14734. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  14735. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  14736. else emitter._events[evt] = [emitter._events[evt], listener];
  14737. return emitter;
  14738. }
  14739. /**
  14740. * Clear event by name.
  14741. *
  14742. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  14743. * @param {(String|Symbol)} evt The Event name.
  14744. * @private
  14745. */
  14746. function clearEvent(emitter, evt) {
  14747. if (--emitter._eventsCount === 0) emitter._events = new Events();
  14748. else delete emitter._events[evt];
  14749. }
  14750. /**
  14751. * Minimal `EventEmitter` interface that is molded against the Node.js
  14752. * `EventEmitter` interface.
  14753. *
  14754. * @constructor
  14755. * @public
  14756. */
  14757. function EventEmitter() {
  14758. this._events = new Events();
  14759. this._eventsCount = 0;
  14760. }
  14761. /**
  14762. * Return an array listing the events for which the emitter has registered
  14763. * listeners.
  14764. *
  14765. * @returns {Array}
  14766. * @public
  14767. */
  14768. EventEmitter.prototype.eventNames = function eventNames() {
  14769. var names = []
  14770. , events
  14771. , name;
  14772. if (this._eventsCount === 0) return names;
  14773. for (name in (events = this._events)) {
  14774. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  14775. }
  14776. if (Object.getOwnPropertySymbols) {
  14777. return names.concat(Object.getOwnPropertySymbols(events));
  14778. }
  14779. return names;
  14780. };
  14781. /**
  14782. * Return the listeners registered for a given event.
  14783. *
  14784. * @param {(String|Symbol)} event The event name.
  14785. * @returns {Array} The registered listeners.
  14786. * @public
  14787. */
  14788. EventEmitter.prototype.listeners = function listeners(event) {
  14789. var evt = prefix ? prefix + event : event
  14790. , handlers = this._events[evt];
  14791. if (!handlers) return [];
  14792. if (handlers.fn) return [handlers.fn];
  14793. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  14794. ee[i] = handlers[i].fn;
  14795. }
  14796. return ee;
  14797. };
  14798. /**
  14799. * Return the number of listeners listening to a given event.
  14800. *
  14801. * @param {(String|Symbol)} event The event name.
  14802. * @returns {Number} The number of listeners.
  14803. * @public
  14804. */
  14805. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  14806. var evt = prefix ? prefix + event : event
  14807. , listeners = this._events[evt];
  14808. if (!listeners) return 0;
  14809. if (listeners.fn) return 1;
  14810. return listeners.length;
  14811. };
  14812. /**
  14813. * Calls each of the listeners registered for a given event.
  14814. *
  14815. * @param {(String|Symbol)} event The event name.
  14816. * @returns {Boolean} `true` if the event had listeners, else `false`.
  14817. * @public
  14818. */
  14819. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  14820. var evt = prefix ? prefix + event : event;
  14821. if (!this._events[evt]) return false;
  14822. var listeners = this._events[evt]
  14823. , len = arguments.length
  14824. , args
  14825. , i;
  14826. if (listeners.fn) {
  14827. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  14828. switch (len) {
  14829. case 1: return listeners.fn.call(listeners.context), true;
  14830. case 2: return listeners.fn.call(listeners.context, a1), true;
  14831. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  14832. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  14833. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  14834. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  14835. }
  14836. for (i = 1, args = new Array(len -1); i < len; i++) {
  14837. args[i - 1] = arguments[i];
  14838. }
  14839. listeners.fn.apply(listeners.context, args);
  14840. } else {
  14841. var length = listeners.length
  14842. , j;
  14843. for (i = 0; i < length; i++) {
  14844. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  14845. switch (len) {
  14846. case 1: listeners[i].fn.call(listeners[i].context); break;
  14847. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  14848. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  14849. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  14850. default:
  14851. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  14852. args[j - 1] = arguments[j];
  14853. }
  14854. listeners[i].fn.apply(listeners[i].context, args);
  14855. }
  14856. }
  14857. }
  14858. return true;
  14859. };
  14860. /**
  14861. * Add a listener for a given event.
  14862. *
  14863. * @param {(String|Symbol)} event The event name.
  14864. * @param {Function} fn The listener function.
  14865. * @param {*} [context=this] The context to invoke the listener with.
  14866. * @returns {EventEmitter} `this`.
  14867. * @public
  14868. */
  14869. EventEmitter.prototype.on = function on(event, fn, context) {
  14870. return addListener(this, event, fn, context, false);
  14871. };
  14872. /**
  14873. * Add a one-time listener for a given event.
  14874. *
  14875. * @param {(String|Symbol)} event The event name.
  14876. * @param {Function} fn The listener function.
  14877. * @param {*} [context=this] The context to invoke the listener with.
  14878. * @returns {EventEmitter} `this`.
  14879. * @public
  14880. */
  14881. EventEmitter.prototype.once = function once(event, fn, context) {
  14882. return addListener(this, event, fn, context, true);
  14883. };
  14884. /**
  14885. * Remove the listeners of a given event.
  14886. *
  14887. * @param {(String|Symbol)} event The event name.
  14888. * @param {Function} fn Only remove the listeners that match this function.
  14889. * @param {*} context Only remove the listeners that have this context.
  14890. * @param {Boolean} once Only remove one-time listeners.
  14891. * @returns {EventEmitter} `this`.
  14892. * @public
  14893. */
  14894. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  14895. var evt = prefix ? prefix + event : event;
  14896. if (!this._events[evt]) return this;
  14897. if (!fn) {
  14898. clearEvent(this, evt);
  14899. return this;
  14900. }
  14901. var listeners = this._events[evt];
  14902. if (listeners.fn) {
  14903. if (
  14904. listeners.fn === fn &&
  14905. (!once || listeners.once) &&
  14906. (!context || listeners.context === context)
  14907. ) {
  14908. clearEvent(this, evt);
  14909. }
  14910. } else {
  14911. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  14912. if (
  14913. listeners[i].fn !== fn ||
  14914. (once && !listeners[i].once) ||
  14915. (context && listeners[i].context !== context)
  14916. ) {
  14917. events.push(listeners[i]);
  14918. }
  14919. }
  14920. //
  14921. // Reset the array, or remove it completely if we have no more listeners.
  14922. //
  14923. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  14924. else clearEvent(this, evt);
  14925. }
  14926. return this;
  14927. };
  14928. /**
  14929. * Remove all listeners, or those of the specified event.
  14930. *
  14931. * @param {(String|Symbol)} [event] The event name.
  14932. * @returns {EventEmitter} `this`.
  14933. * @public
  14934. */
  14935. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  14936. var evt;
  14937. if (event) {
  14938. evt = prefix ? prefix + event : event;
  14939. if (this._events[evt]) clearEvent(this, evt);
  14940. } else {
  14941. this._events = new Events();
  14942. this._eventsCount = 0;
  14943. }
  14944. return this;
  14945. };
  14946. //
  14947. // Alias methods names because people roll like that.
  14948. //
  14949. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  14950. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  14951. //
  14952. // Expose the prefix.
  14953. //
  14954. EventEmitter.prefixed = prefix;
  14955. //
  14956. // Allow `EventEmitter` to be imported as module namespace.
  14957. //
  14958. EventEmitter.EventEmitter = EventEmitter;
  14959. //
  14960. // Expose the module.
  14961. //
  14962. {
  14963. module.exports = EventEmitter;
  14964. }
  14965. } (eventemitter3));
  14966. var eventemitter3Exports = eventemitter3.exports;
  14967. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  14968. class TransmuxerInterface {
  14969. constructor(hls, id, onTransmuxComplete, onFlush) {
  14970. this.error = null;
  14971. this.hls = void 0;
  14972. this.id = void 0;
  14973. this.observer = void 0;
  14974. this.frag = null;
  14975. this.part = null;
  14976. this.useWorker = void 0;
  14977. this.workerContext = null;
  14978. this.onwmsg = void 0;
  14979. this.transmuxer = null;
  14980. this.onTransmuxComplete = void 0;
  14981. this.onFlush = void 0;
  14982. const config = hls.config;
  14983. this.hls = hls;
  14984. this.id = id;
  14985. this.useWorker = !!config.enableWorker;
  14986. this.onTransmuxComplete = onTransmuxComplete;
  14987. this.onFlush = onFlush;
  14988. const forwardMessage = (ev, data) => {
  14989. data = data || {};
  14990. data.frag = this.frag;
  14991. data.id = this.id;
  14992. if (ev === Events.ERROR) {
  14993. this.error = data.error;
  14994. }
  14995. this.hls.trigger(ev, data);
  14996. };
  14997. // forward events to main thread
  14998. this.observer = new EventEmitter();
  14999. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  15000. this.observer.on(Events.ERROR, forwardMessage);
  15001. const MediaSource = getMediaSource(config.preferManagedMediaSource) || {
  15002. isTypeSupported: () => false
  15003. };
  15004. const m2tsTypeSupported = {
  15005. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  15006. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  15007. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  15008. };
  15009. if (this.useWorker && typeof Worker !== 'undefined') {
  15010. const canCreateWorker = config.workerPath || hasUMDWorker();
  15011. if (canCreateWorker) {
  15012. try {
  15013. if (config.workerPath) {
  15014. logger.log(`loading Web Worker ${config.workerPath} for "${id}"`);
  15015. this.workerContext = loadWorker(config.workerPath);
  15016. } else {
  15017. logger.log(`injecting Web Worker for "${id}"`);
  15018. this.workerContext = injectWorker();
  15019. }
  15020. this.onwmsg = event => this.onWorkerMessage(event);
  15021. const {
  15022. worker
  15023. } = this.workerContext;
  15024. worker.addEventListener('message', this.onwmsg);
  15025. worker.onerror = event => {
  15026. const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);
  15027. config.enableWorker = false;
  15028. logger.warn(`Error in "${id}" Web Worker, fallback to inline`);
  15029. this.hls.trigger(Events.ERROR, {
  15030. type: ErrorTypes.OTHER_ERROR,
  15031. details: ErrorDetails.INTERNAL_EXCEPTION,
  15032. fatal: false,
  15033. event: 'demuxerWorker',
  15034. error
  15035. });
  15036. };
  15037. worker.postMessage({
  15038. cmd: 'init',
  15039. typeSupported: m2tsTypeSupported,
  15040. vendor: '',
  15041. id: id,
  15042. config: JSON.stringify(config)
  15043. });
  15044. } catch (err) {
  15045. logger.warn(`Error setting up "${id}" Web Worker, fallback to inline`, err);
  15046. this.resetWorker();
  15047. this.error = null;
  15048. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  15049. }
  15050. return;
  15051. }
  15052. }
  15053. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  15054. }
  15055. resetWorker() {
  15056. if (this.workerContext) {
  15057. const {
  15058. worker,
  15059. objectURL
  15060. } = this.workerContext;
  15061. if (objectURL) {
  15062. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  15063. self.URL.revokeObjectURL(objectURL);
  15064. }
  15065. worker.removeEventListener('message', this.onwmsg);
  15066. worker.onerror = null;
  15067. worker.terminate();
  15068. this.workerContext = null;
  15069. }
  15070. }
  15071. destroy() {
  15072. if (this.workerContext) {
  15073. this.resetWorker();
  15074. this.onwmsg = undefined;
  15075. } else {
  15076. const transmuxer = this.transmuxer;
  15077. if (transmuxer) {
  15078. transmuxer.destroy();
  15079. this.transmuxer = null;
  15080. }
  15081. }
  15082. const observer = this.observer;
  15083. if (observer) {
  15084. observer.removeAllListeners();
  15085. }
  15086. this.frag = null;
  15087. // @ts-ignore
  15088. this.observer = null;
  15089. // @ts-ignore
  15090. this.hls = null;
  15091. }
  15092. push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  15093. var _frag$initSegment, _lastFrag$initSegment;
  15094. chunkMeta.transmuxing.start = self.performance.now();
  15095. const {
  15096. transmuxer
  15097. } = this;
  15098. const timeOffset = part ? part.start : frag.start;
  15099. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  15100. const decryptdata = frag.decryptdata;
  15101. const lastFrag = this.frag;
  15102. const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  15103. const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  15104. const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  15105. const partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  15106. const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  15107. const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  15108. const now = self.performance.now();
  15109. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  15110. frag.stats.parsing.start = now;
  15111. }
  15112. if (part && (partDiff || !contiguous)) {
  15113. part.stats.parsing.start = now;
  15114. }
  15115. const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  15116. const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  15117. if (!contiguous || discontinuity || initSegmentChange) {
  15118. logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}
  15119. discontinuity: ${discontinuity}
  15120. trackSwitch: ${trackSwitch}
  15121. contiguous: ${contiguous}
  15122. accurateTimeOffset: ${accurateTimeOffset}
  15123. timeOffset: ${timeOffset}
  15124. initSegmentChange: ${initSegmentChange}`);
  15125. const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  15126. this.configureTransmuxer(config);
  15127. }
  15128. this.frag = frag;
  15129. this.part = part;
  15130. // Frags with sn of 'initSegment' are not transmuxed
  15131. if (this.workerContext) {
  15132. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  15133. this.workerContext.worker.postMessage({
  15134. cmd: 'demux',
  15135. data,
  15136. decryptdata,
  15137. chunkMeta,
  15138. state
  15139. }, data instanceof ArrayBuffer ? [data] : []);
  15140. } else if (transmuxer) {
  15141. const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  15142. if (isPromise(transmuxResult)) {
  15143. transmuxer.async = true;
  15144. transmuxResult.then(data => {
  15145. this.handleTransmuxComplete(data);
  15146. }).catch(error => {
  15147. this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  15148. });
  15149. } else {
  15150. transmuxer.async = false;
  15151. this.handleTransmuxComplete(transmuxResult);
  15152. }
  15153. }
  15154. }
  15155. flush(chunkMeta) {
  15156. chunkMeta.transmuxing.start = self.performance.now();
  15157. const {
  15158. transmuxer
  15159. } = this;
  15160. if (this.workerContext) {
  15161. this.workerContext.worker.postMessage({
  15162. cmd: 'flush',
  15163. chunkMeta
  15164. });
  15165. } else if (transmuxer) {
  15166. let transmuxResult = transmuxer.flush(chunkMeta);
  15167. const asyncFlush = isPromise(transmuxResult);
  15168. if (asyncFlush || transmuxer.async) {
  15169. if (!isPromise(transmuxResult)) {
  15170. transmuxResult = Promise.resolve(transmuxResult);
  15171. }
  15172. transmuxResult.then(data => {
  15173. this.handleFlushResult(data, chunkMeta);
  15174. }).catch(error => {
  15175. this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  15176. });
  15177. } else {
  15178. this.handleFlushResult(transmuxResult, chunkMeta);
  15179. }
  15180. }
  15181. }
  15182. transmuxerError(error, chunkMeta, reason) {
  15183. if (!this.hls) {
  15184. return;
  15185. }
  15186. this.error = error;
  15187. this.hls.trigger(Events.ERROR, {
  15188. type: ErrorTypes.MEDIA_ERROR,
  15189. details: ErrorDetails.FRAG_PARSING_ERROR,
  15190. chunkMeta,
  15191. frag: this.frag || undefined,
  15192. fatal: false,
  15193. error,
  15194. err: error,
  15195. reason
  15196. });
  15197. }
  15198. handleFlushResult(results, chunkMeta) {
  15199. results.forEach(result => {
  15200. this.handleTransmuxComplete(result);
  15201. });
  15202. this.onFlush(chunkMeta);
  15203. }
  15204. onWorkerMessage(event) {
  15205. const data = event.data;
  15206. if (!(data != null && data.event)) {
  15207. logger.warn(`worker message received with no ${data ? 'event name' : 'data'}`);
  15208. return;
  15209. }
  15210. const hls = this.hls;
  15211. if (!this.hls) {
  15212. return;
  15213. }
  15214. switch (data.event) {
  15215. case 'init':
  15216. {
  15217. var _this$workerContext;
  15218. const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  15219. if (objectURL) {
  15220. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  15221. self.URL.revokeObjectURL(objectURL);
  15222. }
  15223. break;
  15224. }
  15225. case 'transmuxComplete':
  15226. {
  15227. this.handleTransmuxComplete(data.data);
  15228. break;
  15229. }
  15230. case 'flush':
  15231. {
  15232. this.onFlush(data.data);
  15233. break;
  15234. }
  15235. // pass logs from the worker thread to the main logger
  15236. case 'workerLog':
  15237. if (logger[data.data.logType]) {
  15238. logger[data.data.logType](data.data.message);
  15239. }
  15240. break;
  15241. default:
  15242. {
  15243. data.data = data.data || {};
  15244. data.data.frag = this.frag;
  15245. data.data.id = this.id;
  15246. hls.trigger(data.event, data.data);
  15247. break;
  15248. }
  15249. }
  15250. }
  15251. configureTransmuxer(config) {
  15252. const {
  15253. transmuxer
  15254. } = this;
  15255. if (this.workerContext) {
  15256. this.workerContext.worker.postMessage({
  15257. cmd: 'configure',
  15258. config
  15259. });
  15260. } else if (transmuxer) {
  15261. transmuxer.configure(config);
  15262. }
  15263. }
  15264. handleTransmuxComplete(result) {
  15265. result.chunkMeta.transmuxing.end = self.performance.now();
  15266. this.onTransmuxComplete(result);
  15267. }
  15268. }
  15269. function subtitleOptionsIdentical(trackList1, trackList2) {
  15270. if (trackList1.length !== trackList2.length) {
  15271. return false;
  15272. }
  15273. for (let i = 0; i < trackList1.length; i++) {
  15274. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  15275. return false;
  15276. }
  15277. }
  15278. return true;
  15279. }
  15280. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  15281. // Media options with the same rendition ID must be bit identical
  15282. const stableRenditionId = attrs1['STABLE-RENDITION-ID'];
  15283. if (stableRenditionId && !customAttributes) {
  15284. return stableRenditionId === attrs2['STABLE-RENDITION-ID'];
  15285. }
  15286. // When rendition ID is not present, compare attributes
  15287. return !(customAttributes || ['LANGUAGE', 'NAME', 'CHARACTERISTICS', 'AUTOSELECT', 'DEFAULT', 'FORCED', 'ASSOC-LANGUAGE']).some(subtitleAttribute => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);
  15288. }
  15289. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  15290. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || '').toLowerCase());
  15291. }
  15292. const TICK_INTERVAL$2 = 100; // how often to tick in ms
  15293. class AudioStreamController extends BaseStreamController {
  15294. constructor(hls, fragmentTracker, keyLoader) {
  15295. super(hls, fragmentTracker, keyLoader, '[audio-stream-controller]', PlaylistLevelType.AUDIO);
  15296. this.videoBuffer = null;
  15297. this.videoTrackCC = -1;
  15298. this.waitingVideoCC = -1;
  15299. this.bufferedTrack = null;
  15300. this.switchingTrack = null;
  15301. this.trackId = -1;
  15302. this.waitingData = null;
  15303. this.mainDetails = null;
  15304. this.flushing = false;
  15305. this.bufferFlushed = false;
  15306. this.cachedTrackLoadedData = null;
  15307. this._registerListeners();
  15308. }
  15309. onHandlerDestroying() {
  15310. this._unregisterListeners();
  15311. super.onHandlerDestroying();
  15312. this.mainDetails = null;
  15313. this.bufferedTrack = null;
  15314. this.switchingTrack = null;
  15315. }
  15316. _registerListeners() {
  15317. const {
  15318. hls
  15319. } = this;
  15320. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15321. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15322. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15323. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15324. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15325. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15326. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15327. hls.on(Events.ERROR, this.onError, this);
  15328. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  15329. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15330. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15331. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15332. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15333. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15334. }
  15335. _unregisterListeners() {
  15336. const {
  15337. hls
  15338. } = this;
  15339. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  15340. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  15341. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15342. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  15343. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  15344. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  15345. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  15346. hls.off(Events.ERROR, this.onError, this);
  15347. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  15348. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  15349. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  15350. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  15351. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  15352. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15353. }
  15354. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  15355. onInitPtsFound(event, {
  15356. frag,
  15357. id,
  15358. initPTS,
  15359. timescale
  15360. }) {
  15361. // Always update the new INIT PTS
  15362. // Can change due level switch
  15363. if (id === 'main') {
  15364. const cc = frag.cc;
  15365. this.initPTS[frag.cc] = {
  15366. baseTime: initPTS,
  15367. timescale
  15368. };
  15369. this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`);
  15370. this.videoTrackCC = cc;
  15371. // If we are waiting, tick immediately to unblock audio fragment transmuxing
  15372. if (this.state === State.WAITING_INIT_PTS) {
  15373. this.tick();
  15374. }
  15375. }
  15376. }
  15377. startLoad(startPosition) {
  15378. if (!this.levels) {
  15379. this.startPosition = startPosition;
  15380. this.state = State.STOPPED;
  15381. return;
  15382. }
  15383. const lastCurrentTime = this.lastCurrentTime;
  15384. this.stopLoad();
  15385. this.setInterval(TICK_INTERVAL$2);
  15386. if (lastCurrentTime > 0 && startPosition === -1) {
  15387. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  15388. startPosition = lastCurrentTime;
  15389. this.state = State.IDLE;
  15390. } else {
  15391. this.loadedmetadata = false;
  15392. this.state = State.WAITING_TRACK;
  15393. }
  15394. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  15395. this.tick();
  15396. }
  15397. doTick() {
  15398. switch (this.state) {
  15399. case State.IDLE:
  15400. this.doTickIdle();
  15401. break;
  15402. case State.WAITING_TRACK:
  15403. {
  15404. var _levels$trackId;
  15405. const {
  15406. levels,
  15407. trackId
  15408. } = this;
  15409. const details = levels == null ? void 0 : (_levels$trackId = levels[trackId]) == null ? void 0 : _levels$trackId.details;
  15410. if (details) {
  15411. if (this.waitForCdnTuneIn(details)) {
  15412. break;
  15413. }
  15414. this.state = State.WAITING_INIT_PTS;
  15415. }
  15416. break;
  15417. }
  15418. case State.FRAG_LOADING_WAITING_RETRY:
  15419. {
  15420. var _this$media;
  15421. const now = performance.now();
  15422. const retryDate = this.retryDate;
  15423. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  15424. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  15425. const {
  15426. levels,
  15427. trackId
  15428. } = this;
  15429. this.log('RetryDate reached, switch back to IDLE state');
  15430. this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);
  15431. this.state = State.IDLE;
  15432. }
  15433. break;
  15434. }
  15435. case State.WAITING_INIT_PTS:
  15436. {
  15437. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  15438. const waitingData = this.waitingData;
  15439. if (waitingData) {
  15440. const {
  15441. frag,
  15442. part,
  15443. cache,
  15444. complete
  15445. } = waitingData;
  15446. if (this.initPTS[frag.cc] !== undefined) {
  15447. this.waitingData = null;
  15448. this.waitingVideoCC = -1;
  15449. this.state = State.FRAG_LOADING;
  15450. const payload = cache.flush();
  15451. const data = {
  15452. frag,
  15453. part,
  15454. payload,
  15455. networkDetails: null
  15456. };
  15457. this._handleFragmentLoadProgress(data);
  15458. if (complete) {
  15459. super._handleFragmentLoadComplete(data);
  15460. }
  15461. } else if (this.videoTrackCC !== this.waitingVideoCC) {
  15462. // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
  15463. this.log(`Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`);
  15464. this.clearWaitingFragment();
  15465. } else {
  15466. // Drop waiting fragment if an earlier fragment is needed
  15467. const pos = this.getLoadPosition();
  15468. const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole);
  15469. const waitingFragmentAtPosition = fragmentWithinToleranceTest(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
  15470. if (waitingFragmentAtPosition < 0) {
  15471. this.log(`Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`);
  15472. this.clearWaitingFragment();
  15473. }
  15474. }
  15475. } else {
  15476. this.state = State.IDLE;
  15477. }
  15478. }
  15479. }
  15480. this.onTickEnd();
  15481. }
  15482. clearWaitingFragment() {
  15483. const waitingData = this.waitingData;
  15484. if (waitingData) {
  15485. this.fragmentTracker.removeFragment(waitingData.frag);
  15486. this.waitingData = null;
  15487. this.waitingVideoCC = -1;
  15488. this.state = State.IDLE;
  15489. }
  15490. }
  15491. resetLoadingState() {
  15492. this.clearWaitingFragment();
  15493. super.resetLoadingState();
  15494. }
  15495. onTickEnd() {
  15496. const {
  15497. media
  15498. } = this;
  15499. if (!(media != null && media.readyState)) {
  15500. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  15501. return;
  15502. }
  15503. this.lastCurrentTime = media.currentTime;
  15504. }
  15505. doTickIdle() {
  15506. const {
  15507. hls,
  15508. levels,
  15509. media,
  15510. trackId
  15511. } = this;
  15512. const config = hls.config;
  15513. // 1. if video not attached AND
  15514. // start fragment already requested OR start frag prefetch not enabled
  15515. // 2. if tracks or track not loaded and selected
  15516. // then exit loop
  15517. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  15518. if (!media && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  15519. return;
  15520. }
  15521. const levelInfo = levels[trackId];
  15522. const trackDetails = levelInfo.details;
  15523. if (!trackDetails || trackDetails.live && this.levelLastLoaded !== levelInfo || this.waitForCdnTuneIn(trackDetails)) {
  15524. this.state = State.WAITING_TRACK;
  15525. return;
  15526. }
  15527. const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  15528. if (this.bufferFlushed && bufferable) {
  15529. this.bufferFlushed = false;
  15530. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  15531. }
  15532. const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  15533. if (bufferInfo === null) {
  15534. return;
  15535. }
  15536. const {
  15537. bufferedTrack,
  15538. switchingTrack
  15539. } = this;
  15540. if (!switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  15541. hls.trigger(Events.BUFFER_EOS, {
  15542. type: 'audio'
  15543. });
  15544. this.state = State.ENDED;
  15545. return;
  15546. }
  15547. const mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, PlaylistLevelType.MAIN);
  15548. const bufferLen = bufferInfo.len;
  15549. const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len);
  15550. const fragments = trackDetails.fragments;
  15551. const start = fragments[0].start;
  15552. let targetBufferTime = this.flushing ? this.getLoadPosition() : bufferInfo.end;
  15553. if (switchingTrack && media) {
  15554. const pos = this.getLoadPosition();
  15555. // STABLE
  15556. if (bufferedTrack && !mediaAttributesIdentical(switchingTrack.attrs, bufferedTrack.attrs)) {
  15557. targetBufferTime = pos;
  15558. }
  15559. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  15560. if (trackDetails.PTSKnown && pos < start) {
  15561. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  15562. if (bufferInfo.end > start || bufferInfo.nextStart) {
  15563. this.log('Alt audio track ahead of main track, seek to start of alt audio track');
  15564. media.currentTime = start + 0.05;
  15565. }
  15566. }
  15567. }
  15568. // if buffer length is less than maxBufLen, or near the end, find a fragment to load
  15569. if (bufferLen >= maxBufLen && !switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  15570. return;
  15571. }
  15572. let frag = this.getNextFragment(targetBufferTime, trackDetails);
  15573. let atGap = false;
  15574. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  15575. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  15576. atGap = !!frag.gap;
  15577. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  15578. }
  15579. if (!frag) {
  15580. this.bufferFlushed = true;
  15581. return;
  15582. }
  15583. // Buffer audio up to one target duration ahead of main buffer
  15584. const atBufferSyncLimit = mainBufferInfo && frag.start > mainBufferInfo.end + trackDetails.targetduration;
  15585. if (atBufferSyncLimit ||
  15586. // Or wait for main buffer after buffing some audio
  15587. !(mainBufferInfo != null && mainBufferInfo.len) && bufferInfo.len) {
  15588. // Check fragment-tracker for main fragments since GAP segments do not show up in bufferInfo
  15589. const mainFrag = this.getAppendedFrag(frag.start, PlaylistLevelType.MAIN);
  15590. if (mainFrag === null) {
  15591. return;
  15592. }
  15593. // Bridge gaps in main buffer
  15594. atGap || (atGap = !!mainFrag.gap || !!atBufferSyncLimit && mainBufferInfo.len === 0);
  15595. if (atBufferSyncLimit && !atGap || atGap && bufferInfo.nextStart && bufferInfo.nextStart < mainFrag.end) {
  15596. return;
  15597. }
  15598. }
  15599. this.loadFragment(frag, levelInfo, targetBufferTime);
  15600. }
  15601. getMaxBufferLength(mainBufferLength) {
  15602. const maxConfigBuffer = super.getMaxBufferLength();
  15603. if (!mainBufferLength) {
  15604. return maxConfigBuffer;
  15605. }
  15606. return Math.min(Math.max(maxConfigBuffer, mainBufferLength), this.config.maxMaxBufferLength);
  15607. }
  15608. onMediaDetaching() {
  15609. this.videoBuffer = null;
  15610. this.bufferFlushed = this.flushing = false;
  15611. super.onMediaDetaching();
  15612. }
  15613. onAudioTracksUpdated(event, {
  15614. audioTracks
  15615. }) {
  15616. // Reset tranxmuxer is essential for large context switches (Content Steering)
  15617. this.resetTransmuxer();
  15618. this.levels = audioTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  15619. }
  15620. onAudioTrackSwitching(event, data) {
  15621. // if any URL found on new audio track, it is an alternate audio track
  15622. const altAudio = !!data.url;
  15623. this.trackId = data.id;
  15624. const {
  15625. fragCurrent
  15626. } = this;
  15627. if (fragCurrent) {
  15628. fragCurrent.abortRequests();
  15629. this.removeUnbufferedFrags(fragCurrent.start);
  15630. }
  15631. this.resetLoadingState();
  15632. // destroy useless transmuxer when switching audio to main
  15633. if (!altAudio) {
  15634. this.resetTransmuxer();
  15635. } else {
  15636. // switching to audio track, start timer if not already started
  15637. this.setInterval(TICK_INTERVAL$2);
  15638. }
  15639. // should we switch tracks ?
  15640. if (altAudio) {
  15641. this.switchingTrack = data;
  15642. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  15643. this.state = State.IDLE;
  15644. this.flushAudioIfNeeded(data);
  15645. } else {
  15646. this.switchingTrack = null;
  15647. this.bufferedTrack = data;
  15648. this.state = State.STOPPED;
  15649. }
  15650. this.tick();
  15651. }
  15652. onManifestLoading() {
  15653. this.fragmentTracker.removeAllFragments();
  15654. this.startPosition = this.lastCurrentTime = 0;
  15655. this.bufferFlushed = this.flushing = false;
  15656. this.levels = this.mainDetails = this.waitingData = this.bufferedTrack = this.cachedTrackLoadedData = this.switchingTrack = null;
  15657. this.startFragRequested = false;
  15658. this.trackId = this.videoTrackCC = this.waitingVideoCC = -1;
  15659. }
  15660. onLevelLoaded(event, data) {
  15661. this.mainDetails = data.details;
  15662. if (this.cachedTrackLoadedData !== null) {
  15663. this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData);
  15664. this.cachedTrackLoadedData = null;
  15665. }
  15666. }
  15667. onAudioTrackLoaded(event, data) {
  15668. var _track$details;
  15669. if (this.mainDetails == null) {
  15670. this.cachedTrackLoadedData = data;
  15671. return;
  15672. }
  15673. const {
  15674. levels
  15675. } = this;
  15676. const {
  15677. details: newDetails,
  15678. id: trackId
  15679. } = data;
  15680. if (!levels) {
  15681. this.warn(`Audio tracks were reset while loading level ${trackId}`);
  15682. return;
  15683. }
  15684. this.log(`Audio track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  15685. const track = levels[trackId];
  15686. let sliding = 0;
  15687. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  15688. this.checkLiveUpdate(newDetails);
  15689. const mainDetails = this.mainDetails;
  15690. if (newDetails.deltaUpdateFailed || !mainDetails) {
  15691. return;
  15692. }
  15693. if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  15694. // Make sure our audio rendition is aligned with the "main" rendition, using
  15695. // pdt as our reference times.
  15696. alignMediaPlaylistByPDT(newDetails, mainDetails);
  15697. sliding = newDetails.fragments[0].start;
  15698. } else {
  15699. var _this$levelLastLoaded;
  15700. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  15701. }
  15702. }
  15703. track.details = newDetails;
  15704. this.levelLastLoaded = track;
  15705. // compute start position if we are aligned with the main playlist
  15706. if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
  15707. this.setStartPosition(this.mainDetails || newDetails, sliding);
  15708. }
  15709. // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
  15710. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  15711. this.state = State.IDLE;
  15712. }
  15713. // trigger handler right now
  15714. this.tick();
  15715. }
  15716. _handleFragmentLoadProgress(data) {
  15717. var _frag$initSegment;
  15718. const {
  15719. frag,
  15720. part,
  15721. payload
  15722. } = data;
  15723. const {
  15724. config,
  15725. trackId,
  15726. levels
  15727. } = this;
  15728. if (!levels) {
  15729. this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  15730. return;
  15731. }
  15732. const track = levels[trackId];
  15733. if (!track) {
  15734. this.warn('Audio track is undefined on fragment load progress');
  15735. return;
  15736. }
  15737. const details = track.details;
  15738. if (!details) {
  15739. this.warn('Audio track details undefined on fragment load progress');
  15740. this.removeUnbufferedFrags(frag.start);
  15741. return;
  15742. }
  15743. const audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
  15744. let transmuxer = this.transmuxer;
  15745. if (!transmuxer) {
  15746. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  15747. }
  15748. // Check if we have video initPTS
  15749. // If not we need to wait for it
  15750. const initPTS = this.initPTS[frag.cc];
  15751. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  15752. if (initPTS !== undefined) {
  15753. // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  15754. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  15755. const accurateTimeOffset = false; // details.PTSKnown || !details.live;
  15756. const partIndex = part ? part.index : -1;
  15757. const partial = partIndex !== -1;
  15758. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  15759. transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  15760. } else {
  15761. 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}`);
  15762. const {
  15763. cache
  15764. } = this.waitingData = this.waitingData || {
  15765. frag,
  15766. part,
  15767. cache: new ChunkCache(),
  15768. complete: false
  15769. };
  15770. cache.push(new Uint8Array(payload));
  15771. this.waitingVideoCC = this.videoTrackCC;
  15772. this.state = State.WAITING_INIT_PTS;
  15773. }
  15774. }
  15775. _handleFragmentLoadComplete(fragLoadedData) {
  15776. if (this.waitingData) {
  15777. this.waitingData.complete = true;
  15778. return;
  15779. }
  15780. super._handleFragmentLoadComplete(fragLoadedData);
  15781. }
  15782. onBufferReset( /* event: Events.BUFFER_RESET */
  15783. ) {
  15784. // reset reference to sourcebuffers
  15785. this.mediaBuffer = this.videoBuffer = null;
  15786. this.loadedmetadata = false;
  15787. }
  15788. onBufferCreated(event, data) {
  15789. const audioTrack = data.tracks.audio;
  15790. if (audioTrack) {
  15791. this.mediaBuffer = audioTrack.buffer || null;
  15792. }
  15793. if (data.tracks.video) {
  15794. this.videoBuffer = data.tracks.video.buffer || null;
  15795. }
  15796. }
  15797. onFragBuffered(event, data) {
  15798. const {
  15799. frag,
  15800. part
  15801. } = data;
  15802. if (frag.type !== PlaylistLevelType.AUDIO) {
  15803. if (!this.loadedmetadata && frag.type === PlaylistLevelType.MAIN) {
  15804. const bufferable = this.videoBuffer || this.media;
  15805. if (bufferable) {
  15806. const bufferedTimeRanges = BufferHelper.getBuffered(bufferable);
  15807. if (bufferedTimeRanges.length) {
  15808. this.loadedmetadata = true;
  15809. }
  15810. }
  15811. }
  15812. return;
  15813. }
  15814. if (this.fragContextChanged(frag)) {
  15815. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  15816. // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
  15817. 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'}`);
  15818. return;
  15819. }
  15820. if (frag.sn !== 'initSegment') {
  15821. this.fragPrevious = frag;
  15822. const track = this.switchingTrack;
  15823. if (track) {
  15824. this.bufferedTrack = track;
  15825. this.switchingTrack = null;
  15826. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  15827. }
  15828. }
  15829. this.fragBufferedComplete(frag, part);
  15830. }
  15831. onError(event, data) {
  15832. var _data$context;
  15833. if (data.fatal) {
  15834. this.state = State.ERROR;
  15835. return;
  15836. }
  15837. switch (data.details) {
  15838. case ErrorDetails.FRAG_GAP:
  15839. case ErrorDetails.FRAG_PARSING_ERROR:
  15840. case ErrorDetails.FRAG_DECRYPT_ERROR:
  15841. case ErrorDetails.FRAG_LOAD_ERROR:
  15842. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  15843. case ErrorDetails.KEY_LOAD_ERROR:
  15844. case ErrorDetails.KEY_LOAD_TIMEOUT:
  15845. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  15846. break;
  15847. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  15848. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  15849. case ErrorDetails.LEVEL_PARSING_ERROR:
  15850. // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE
  15851. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  15852. this.state = State.IDLE;
  15853. }
  15854. break;
  15855. case ErrorDetails.BUFFER_APPEND_ERROR:
  15856. case ErrorDetails.BUFFER_FULL_ERROR:
  15857. if (!data.parent || data.parent !== 'audio') {
  15858. return;
  15859. }
  15860. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  15861. this.resetLoadingState();
  15862. return;
  15863. }
  15864. if (this.reduceLengthAndFlushBuffer(data)) {
  15865. this.bufferedTrack = null;
  15866. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  15867. }
  15868. break;
  15869. case ErrorDetails.INTERNAL_EXCEPTION:
  15870. this.recoverWorkerError(data);
  15871. break;
  15872. }
  15873. }
  15874. onBufferFlushing(event, {
  15875. type
  15876. }) {
  15877. if (type !== ElementaryStreamTypes.VIDEO) {
  15878. this.flushing = true;
  15879. }
  15880. }
  15881. onBufferFlushed(event, {
  15882. type
  15883. }) {
  15884. if (type !== ElementaryStreamTypes.VIDEO) {
  15885. this.flushing = false;
  15886. this.bufferFlushed = true;
  15887. if (this.state === State.ENDED) {
  15888. this.state = State.IDLE;
  15889. }
  15890. const mediaBuffer = this.mediaBuffer || this.media;
  15891. if (mediaBuffer) {
  15892. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  15893. this.tick();
  15894. }
  15895. }
  15896. }
  15897. _handleTransmuxComplete(transmuxResult) {
  15898. var _id3$samples;
  15899. const id = 'audio';
  15900. const {
  15901. hls
  15902. } = this;
  15903. const {
  15904. remuxResult,
  15905. chunkMeta
  15906. } = transmuxResult;
  15907. const context = this.getCurrentContext(chunkMeta);
  15908. if (!context) {
  15909. this.resetWhenMissingContext(chunkMeta);
  15910. return;
  15911. }
  15912. const {
  15913. frag,
  15914. part,
  15915. level
  15916. } = context;
  15917. const {
  15918. details
  15919. } = level;
  15920. const {
  15921. audio,
  15922. text,
  15923. id3,
  15924. initSegment
  15925. } = remuxResult;
  15926. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  15927. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  15928. if (this.fragContextChanged(frag) || !details) {
  15929. this.fragmentTracker.removeFragment(frag);
  15930. return;
  15931. }
  15932. this.state = State.PARSING;
  15933. if (this.switchingTrack && audio) {
  15934. this.completeAudioSwitch(this.switchingTrack);
  15935. }
  15936. if (initSegment != null && initSegment.tracks) {
  15937. const mapFragment = frag.initSegment || frag;
  15938. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  15939. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  15940. frag: mapFragment,
  15941. id,
  15942. tracks: initSegment.tracks
  15943. });
  15944. // Only flush audio from old audio tracks when PTS is known on new audio track
  15945. }
  15946. if (audio) {
  15947. const {
  15948. startPTS,
  15949. endPTS,
  15950. startDTS,
  15951. endDTS
  15952. } = audio;
  15953. if (part) {
  15954. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  15955. startPTS,
  15956. endPTS,
  15957. startDTS,
  15958. endDTS
  15959. };
  15960. }
  15961. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  15962. this.bufferFragmentData(audio, frag, part, chunkMeta);
  15963. }
  15964. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  15965. const emittedID3 = _extends({
  15966. id,
  15967. frag,
  15968. details
  15969. }, id3);
  15970. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  15971. }
  15972. if (text) {
  15973. const emittedText = _extends({
  15974. id,
  15975. frag,
  15976. details
  15977. }, text);
  15978. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  15979. }
  15980. }
  15981. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  15982. if (this.state !== State.PARSING) {
  15983. return;
  15984. }
  15985. // delete any video track found on audio transmuxer
  15986. if (tracks.video) {
  15987. delete tracks.video;
  15988. }
  15989. // include levelCodec in audio and video tracks
  15990. const track = tracks.audio;
  15991. if (!track) {
  15992. return;
  15993. }
  15994. track.id = 'audio';
  15995. const variantAudioCodecs = currentLevel.audioCodec;
  15996. this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);
  15997. // SourceBuffer will use track.levelCodec if defined
  15998. if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {
  15999. track.levelCodec = variantAudioCodecs;
  16000. }
  16001. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  16002. const initSegment = track.initSegment;
  16003. if (initSegment != null && initSegment.byteLength) {
  16004. const segment = {
  16005. type: 'audio',
  16006. frag,
  16007. part: null,
  16008. chunkMeta,
  16009. parent: frag.type,
  16010. data: initSegment
  16011. };
  16012. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  16013. }
  16014. // trigger handler right now
  16015. this.tickImmediate();
  16016. }
  16017. loadFragment(frag, track, targetBufferTime) {
  16018. // only load if fragment is not loaded or if in audio switch
  16019. const fragState = this.fragmentTracker.getState(frag);
  16020. this.fragCurrent = frag;
  16021. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  16022. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  16023. var _track$details2;
  16024. if (frag.sn === 'initSegment') {
  16025. this._loadInitSegment(frag, track);
  16026. } else if ((_track$details2 = track.details) != null && _track$details2.live && !this.initPTS[frag.cc]) {
  16027. this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);
  16028. this.state = State.WAITING_INIT_PTS;
  16029. const mainDetails = this.mainDetails;
  16030. if (mainDetails && mainDetails.fragments[0].start !== track.details.fragments[0].start) {
  16031. alignMediaPlaylistByPDT(track.details, mainDetails);
  16032. }
  16033. } else {
  16034. this.startFragRequested = true;
  16035. super.loadFragment(frag, track, targetBufferTime);
  16036. }
  16037. } else {
  16038. this.clearTrackerIfNeeded(frag);
  16039. }
  16040. }
  16041. flushAudioIfNeeded(switchingTrack) {
  16042. const {
  16043. media,
  16044. bufferedTrack
  16045. } = this;
  16046. const bufferedAttributes = bufferedTrack == null ? void 0 : bufferedTrack.attrs;
  16047. const switchAttributes = switchingTrack.attrs;
  16048. if (media && bufferedAttributes && (bufferedAttributes.CHANNELS !== switchAttributes.CHANNELS || bufferedTrack.name !== switchingTrack.name || bufferedTrack.lang !== switchingTrack.lang)) {
  16049. this.log('Switching audio track : flushing all audio');
  16050. super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');
  16051. this.bufferedTrack = null;
  16052. }
  16053. }
  16054. completeAudioSwitch(switchingTrack) {
  16055. const {
  16056. hls
  16057. } = this;
  16058. this.flushAudioIfNeeded(switchingTrack);
  16059. this.bufferedTrack = switchingTrack;
  16060. this.switchingTrack = null;
  16061. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  16062. }
  16063. }
  16064. class AudioTrackController extends BasePlaylistController {
  16065. constructor(hls) {
  16066. super(hls, '[audio-track-controller]');
  16067. this.tracks = [];
  16068. this.groupIds = null;
  16069. this.tracksInGroup = [];
  16070. this.trackId = -1;
  16071. this.currentTrack = null;
  16072. this.selectDefaultTrack = true;
  16073. this.registerListeners();
  16074. }
  16075. registerListeners() {
  16076. const {
  16077. hls
  16078. } = this;
  16079. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16080. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16081. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16082. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16083. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16084. hls.on(Events.ERROR, this.onError, this);
  16085. }
  16086. unregisterListeners() {
  16087. const {
  16088. hls
  16089. } = this;
  16090. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16091. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16092. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16093. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16094. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16095. hls.off(Events.ERROR, this.onError, this);
  16096. }
  16097. destroy() {
  16098. this.unregisterListeners();
  16099. this.tracks.length = 0;
  16100. this.tracksInGroup.length = 0;
  16101. this.currentTrack = null;
  16102. super.destroy();
  16103. }
  16104. onManifestLoading() {
  16105. this.tracks = [];
  16106. this.tracksInGroup = [];
  16107. this.groupIds = null;
  16108. this.currentTrack = null;
  16109. this.trackId = -1;
  16110. this.selectDefaultTrack = true;
  16111. }
  16112. onManifestParsed(event, data) {
  16113. this.tracks = data.audioTracks || [];
  16114. }
  16115. onAudioTrackLoaded(event, data) {
  16116. const {
  16117. id,
  16118. groupId,
  16119. details
  16120. } = data;
  16121. const trackInActiveGroup = this.tracksInGroup[id];
  16122. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16123. this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16124. return;
  16125. }
  16126. const curDetails = trackInActiveGroup.details;
  16127. trackInActiveGroup.details = data.details;
  16128. this.log(`Audio track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16129. if (id === this.trackId) {
  16130. this.playlistLoaded(id, data, curDetails);
  16131. }
  16132. }
  16133. onLevelLoading(event, data) {
  16134. this.switchLevel(data.level);
  16135. }
  16136. onLevelSwitching(event, data) {
  16137. this.switchLevel(data.level);
  16138. }
  16139. switchLevel(levelIndex) {
  16140. const levelInfo = this.hls.levels[levelIndex];
  16141. if (!levelInfo) {
  16142. return;
  16143. }
  16144. const audioGroups = levelInfo.audioGroups || null;
  16145. const currentGroups = this.groupIds;
  16146. let currentTrack = this.currentTrack;
  16147. 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)) {
  16148. this.groupIds = audioGroups;
  16149. this.trackId = -1;
  16150. this.currentTrack = null;
  16151. const audioTracks = this.tracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);
  16152. if (audioTracks.length) {
  16153. // Disable selectDefaultTrack if there are no default tracks
  16154. if (this.selectDefaultTrack && !audioTracks.some(track => track.default)) {
  16155. this.selectDefaultTrack = false;
  16156. }
  16157. // track.id should match hls.audioTracks index
  16158. audioTracks.forEach((track, i) => {
  16159. track.id = i;
  16160. });
  16161. } else if (!currentTrack && !this.tracksInGroup.length) {
  16162. // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks
  16163. return;
  16164. }
  16165. this.tracksInGroup = audioTracks;
  16166. // Find preferred track
  16167. const audioPreference = this.hls.config.audioPreference;
  16168. if (!currentTrack && audioPreference) {
  16169. const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  16170. if (groupIndex > -1) {
  16171. currentTrack = audioTracks[groupIndex];
  16172. } else {
  16173. const allIndex = findMatchingOption(audioPreference, this.tracks);
  16174. currentTrack = this.tracks[allIndex];
  16175. }
  16176. }
  16177. // Select initial track
  16178. let trackId = this.findTrackId(currentTrack);
  16179. if (trackId === -1 && currentTrack) {
  16180. trackId = this.findTrackId(null);
  16181. }
  16182. // Dispatch events and load track if needed
  16183. const audioTracksUpdated = {
  16184. audioTracks
  16185. };
  16186. this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(',')}`);
  16187. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  16188. const selectedTrackId = this.trackId;
  16189. if (trackId !== -1 && selectedTrackId === -1) {
  16190. this.setAudioTrack(trackId);
  16191. } else if (audioTracks.length && selectedTrackId === -1) {
  16192. var _this$groupIds;
  16193. 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}`);
  16194. this.warn(error.message);
  16195. this.hls.trigger(Events.ERROR, {
  16196. type: ErrorTypes.MEDIA_ERROR,
  16197. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  16198. fatal: true,
  16199. error
  16200. });
  16201. }
  16202. } else if (this.shouldReloadPlaylist(currentTrack)) {
  16203. // Retry playlist loading if no playlist is or has been loaded yet
  16204. this.setAudioTrack(this.trackId);
  16205. }
  16206. }
  16207. onError(event, data) {
  16208. if (data.fatal || !data.context) {
  16209. return;
  16210. }
  16211. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  16212. this.requestScheduled = -1;
  16213. this.checkRetry(data);
  16214. }
  16215. }
  16216. get allAudioTracks() {
  16217. return this.tracks;
  16218. }
  16219. get audioTracks() {
  16220. return this.tracksInGroup;
  16221. }
  16222. get audioTrack() {
  16223. return this.trackId;
  16224. }
  16225. set audioTrack(newId) {
  16226. // If audio track is selected from API then don't choose from the manifest default track
  16227. this.selectDefaultTrack = false;
  16228. this.setAudioTrack(newId);
  16229. }
  16230. setAudioOption(audioOption) {
  16231. const hls = this.hls;
  16232. hls.config.audioPreference = audioOption;
  16233. if (audioOption) {
  16234. const allAudioTracks = this.allAudioTracks;
  16235. this.selectDefaultTrack = false;
  16236. if (allAudioTracks.length) {
  16237. // First see if current option matches (no switch op)
  16238. const currentTrack = this.currentTrack;
  16239. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  16240. return currentTrack;
  16241. }
  16242. // Find option in available tracks (tracksInGroup)
  16243. const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  16244. if (groupIndex > -1) {
  16245. const track = this.tracksInGroup[groupIndex];
  16246. this.setAudioTrack(groupIndex);
  16247. return track;
  16248. } else if (currentTrack) {
  16249. // Find option in nearest level audio group
  16250. let searchIndex = hls.loadLevel;
  16251. if (searchIndex === -1) {
  16252. searchIndex = hls.firstAutoLevel;
  16253. }
  16254. const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  16255. if (switchIndex === -1) {
  16256. // could not find matching variant
  16257. return null;
  16258. }
  16259. // and switch level to acheive the audio group switch
  16260. hls.nextLoadLevel = switchIndex;
  16261. }
  16262. if (audioOption.channels || audioOption.audioCodec) {
  16263. // Could not find a match with codec / channels predicate
  16264. // Find a match without channels or codec
  16265. const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  16266. if (withoutCodecAndChannelsMatch > -1) {
  16267. return allAudioTracks[withoutCodecAndChannelsMatch];
  16268. }
  16269. }
  16270. }
  16271. }
  16272. return null;
  16273. }
  16274. setAudioTrack(newId) {
  16275. const tracks = this.tracksInGroup;
  16276. // check if level idx is valid
  16277. if (newId < 0 || newId >= tracks.length) {
  16278. this.warn(`Invalid audio track id: ${newId}`);
  16279. return;
  16280. }
  16281. // stopping live reloading timer if any
  16282. this.clearTimer();
  16283. this.selectDefaultTrack = false;
  16284. const lastTrack = this.currentTrack;
  16285. const track = tracks[newId];
  16286. const trackLoaded = track.details && !track.details.live;
  16287. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  16288. return;
  16289. }
  16290. this.log(`Switching to audio-track ${newId} "${track.name}" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);
  16291. this.trackId = newId;
  16292. this.currentTrack = track;
  16293. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  16294. // Do not reload track unless live
  16295. if (trackLoaded) {
  16296. return;
  16297. }
  16298. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  16299. this.loadPlaylist(hlsUrlParameters);
  16300. }
  16301. findTrackId(currentTrack) {
  16302. const audioTracks = this.tracksInGroup;
  16303. for (let i = 0; i < audioTracks.length; i++) {
  16304. const track = audioTracks[i];
  16305. if (this.selectDefaultTrack && !track.default) {
  16306. continue;
  16307. }
  16308. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  16309. return i;
  16310. }
  16311. }
  16312. if (currentTrack) {
  16313. const {
  16314. name,
  16315. lang,
  16316. assocLang,
  16317. characteristics,
  16318. audioCodec,
  16319. channels
  16320. } = currentTrack;
  16321. for (let i = 0; i < audioTracks.length; i++) {
  16322. const track = audioTracks[i];
  16323. if (matchesOption({
  16324. name,
  16325. lang,
  16326. assocLang,
  16327. characteristics,
  16328. audioCodec,
  16329. channels
  16330. }, track, audioMatchPredicate)) {
  16331. return i;
  16332. }
  16333. }
  16334. for (let i = 0; i < audioTracks.length; i++) {
  16335. const track = audioTracks[i];
  16336. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  16337. return i;
  16338. }
  16339. }
  16340. for (let i = 0; i < audioTracks.length; i++) {
  16341. const track = audioTracks[i];
  16342. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  16343. return i;
  16344. }
  16345. }
  16346. }
  16347. return -1;
  16348. }
  16349. loadPlaylist(hlsUrlParameters) {
  16350. const audioTrack = this.currentTrack;
  16351. if (this.shouldLoadPlaylist(audioTrack) && audioTrack) {
  16352. super.loadPlaylist();
  16353. const id = audioTrack.id;
  16354. const groupId = audioTrack.groupId;
  16355. let url = audioTrack.url;
  16356. if (hlsUrlParameters) {
  16357. try {
  16358. url = hlsUrlParameters.addDirectives(url);
  16359. } catch (error) {
  16360. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  16361. }
  16362. }
  16363. // track not retrieved yet, or live playlist we need to (re)load it
  16364. this.log(`loading audio-track playlist ${id} "${audioTrack.name}" lang:${audioTrack.lang} group:${groupId}`);
  16365. this.clearTimer();
  16366. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  16367. url,
  16368. id,
  16369. groupId,
  16370. deliveryDirectives: hlsUrlParameters || null
  16371. });
  16372. }
  16373. }
  16374. }
  16375. const TICK_INTERVAL$1 = 500; // how often to tick in ms
  16376. class SubtitleStreamController extends BaseStreamController {
  16377. constructor(hls, fragmentTracker, keyLoader) {
  16378. super(hls, fragmentTracker, keyLoader, '[subtitle-stream-controller]', PlaylistLevelType.SUBTITLE);
  16379. this.currentTrackId = -1;
  16380. this.tracksBuffered = [];
  16381. this.mainDetails = null;
  16382. this._registerListeners();
  16383. }
  16384. onHandlerDestroying() {
  16385. this._unregisterListeners();
  16386. super.onHandlerDestroying();
  16387. this.mainDetails = null;
  16388. }
  16389. _registerListeners() {
  16390. const {
  16391. hls
  16392. } = this;
  16393. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16394. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16395. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16396. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16397. hls.on(Events.ERROR, this.onError, this);
  16398. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  16399. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  16400. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16401. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  16402. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16403. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16404. }
  16405. _unregisterListeners() {
  16406. const {
  16407. hls
  16408. } = this;
  16409. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16410. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16411. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16412. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16413. hls.off(Events.ERROR, this.onError, this);
  16414. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  16415. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  16416. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16417. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  16418. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16419. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16420. }
  16421. startLoad(startPosition) {
  16422. this.stopLoad();
  16423. this.state = State.IDLE;
  16424. this.setInterval(TICK_INTERVAL$1);
  16425. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  16426. this.tick();
  16427. }
  16428. onManifestLoading() {
  16429. this.mainDetails = null;
  16430. this.fragmentTracker.removeAllFragments();
  16431. }
  16432. onMediaDetaching() {
  16433. this.tracksBuffered = [];
  16434. super.onMediaDetaching();
  16435. }
  16436. onLevelLoaded(event, data) {
  16437. this.mainDetails = data.details;
  16438. }
  16439. onSubtitleFragProcessed(event, data) {
  16440. const {
  16441. frag,
  16442. success
  16443. } = data;
  16444. this.fragPrevious = frag;
  16445. this.state = State.IDLE;
  16446. if (!success) {
  16447. return;
  16448. }
  16449. const buffered = this.tracksBuffered[this.currentTrackId];
  16450. if (!buffered) {
  16451. return;
  16452. }
  16453. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  16454. // so we can re-use the logic used to detect how much has been buffered
  16455. let timeRange;
  16456. const fragStart = frag.start;
  16457. for (let i = 0; i < buffered.length; i++) {
  16458. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  16459. timeRange = buffered[i];
  16460. break;
  16461. }
  16462. }
  16463. const fragEnd = frag.start + frag.duration;
  16464. if (timeRange) {
  16465. timeRange.end = fragEnd;
  16466. } else {
  16467. timeRange = {
  16468. start: fragStart,
  16469. end: fragEnd
  16470. };
  16471. buffered.push(timeRange);
  16472. }
  16473. this.fragmentTracker.fragBuffered(frag);
  16474. this.fragBufferedComplete(frag, null);
  16475. }
  16476. onBufferFlushing(event, data) {
  16477. const {
  16478. startOffset,
  16479. endOffset
  16480. } = data;
  16481. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  16482. const endOffsetSubtitles = endOffset - 1;
  16483. if (endOffsetSubtitles <= 0) {
  16484. return;
  16485. }
  16486. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  16487. this.tracksBuffered.forEach(buffered => {
  16488. for (let i = 0; i < buffered.length;) {
  16489. if (buffered[i].end <= endOffsetSubtitles) {
  16490. buffered.shift();
  16491. continue;
  16492. } else if (buffered[i].start < endOffsetSubtitles) {
  16493. buffered[i].start = endOffsetSubtitles;
  16494. } else {
  16495. break;
  16496. }
  16497. i++;
  16498. }
  16499. });
  16500. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  16501. }
  16502. }
  16503. onFragBuffered(event, data) {
  16504. if (!this.loadedmetadata && data.frag.type === PlaylistLevelType.MAIN) {
  16505. var _this$media;
  16506. if ((_this$media = this.media) != null && _this$media.buffered.length) {
  16507. this.loadedmetadata = true;
  16508. }
  16509. }
  16510. }
  16511. // If something goes wrong, proceed to next frag, if we were processing one.
  16512. onError(event, data) {
  16513. const frag = data.frag;
  16514. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  16515. if (data.details === ErrorDetails.FRAG_GAP) {
  16516. this.fragmentTracker.fragBuffered(frag, true);
  16517. }
  16518. if (this.fragCurrent) {
  16519. this.fragCurrent.abortRequests();
  16520. }
  16521. if (this.state !== State.STOPPED) {
  16522. this.state = State.IDLE;
  16523. }
  16524. }
  16525. }
  16526. // Got all new subtitle levels.
  16527. onSubtitleTracksUpdated(event, {
  16528. subtitleTracks
  16529. }) {
  16530. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  16531. this.levels = subtitleTracks.map(mediaPlaylist => new Level(mediaPlaylist));
  16532. return;
  16533. }
  16534. this.tracksBuffered = [];
  16535. this.levels = subtitleTracks.map(mediaPlaylist => {
  16536. const level = new Level(mediaPlaylist);
  16537. this.tracksBuffered[level.id] = [];
  16538. return level;
  16539. });
  16540. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  16541. this.fragPrevious = null;
  16542. this.mediaBuffer = null;
  16543. }
  16544. onSubtitleTrackSwitch(event, data) {
  16545. var _this$levels;
  16546. this.currentTrackId = data.id;
  16547. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  16548. this.clearInterval();
  16549. return;
  16550. }
  16551. // Check if track has the necessary details to load fragments
  16552. const currentTrack = this.levels[this.currentTrackId];
  16553. if (currentTrack != null && currentTrack.details) {
  16554. this.mediaBuffer = this.mediaBufferTimeRanges;
  16555. } else {
  16556. this.mediaBuffer = null;
  16557. }
  16558. if (currentTrack) {
  16559. this.setInterval(TICK_INTERVAL$1);
  16560. }
  16561. }
  16562. // Got a new set of subtitle fragments.
  16563. onSubtitleTrackLoaded(event, data) {
  16564. var _track$details;
  16565. const {
  16566. currentTrackId,
  16567. levels
  16568. } = this;
  16569. const {
  16570. details: newDetails,
  16571. id: trackId
  16572. } = data;
  16573. if (!levels) {
  16574. this.warn(`Subtitle tracks were reset while loading level ${trackId}`);
  16575. return;
  16576. }
  16577. const track = levels[trackId];
  16578. if (trackId >= levels.length || !track) {
  16579. return;
  16580. }
  16581. this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);
  16582. this.mediaBuffer = this.mediaBufferTimeRanges;
  16583. let sliding = 0;
  16584. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  16585. const mainDetails = this.mainDetails;
  16586. if (newDetails.deltaUpdateFailed || !mainDetails) {
  16587. return;
  16588. }
  16589. const mainSlidingStartFragment = mainDetails.fragments[0];
  16590. if (!track.details) {
  16591. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  16592. alignMediaPlaylistByPDT(newDetails, mainDetails);
  16593. sliding = newDetails.fragments[0].start;
  16594. } else if (mainSlidingStartFragment) {
  16595. // line up live playlist with main so that fragments in range are loaded
  16596. sliding = mainSlidingStartFragment.start;
  16597. addSliding(newDetails, sliding);
  16598. }
  16599. } else {
  16600. var _this$levelLastLoaded;
  16601. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  16602. if (sliding === 0 && mainSlidingStartFragment) {
  16603. // realign with main when there is no overlap with last refresh
  16604. sliding = mainSlidingStartFragment.start;
  16605. addSliding(newDetails, sliding);
  16606. }
  16607. }
  16608. }
  16609. track.details = newDetails;
  16610. this.levelLastLoaded = track;
  16611. if (trackId !== currentTrackId) {
  16612. return;
  16613. }
  16614. if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
  16615. this.setStartPosition(this.mainDetails || newDetails, sliding);
  16616. }
  16617. // trigger handler right now
  16618. this.tick();
  16619. // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
  16620. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  16621. const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  16622. if (!foundFrag) {
  16623. this.warn('Subtitle playlist not aligned with playback');
  16624. track.details = undefined;
  16625. }
  16626. }
  16627. }
  16628. _handleFragmentLoadComplete(fragLoadedData) {
  16629. const {
  16630. frag,
  16631. payload
  16632. } = fragLoadedData;
  16633. const decryptData = frag.decryptdata;
  16634. const hls = this.hls;
  16635. if (this.fragContextChanged(frag)) {
  16636. return;
  16637. }
  16638. // check to see if the payload needs to be decrypted
  16639. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  16640. const startTime = performance.now();
  16641. // decrypt the subtitles
  16642. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(err => {
  16643. hls.trigger(Events.ERROR, {
  16644. type: ErrorTypes.MEDIA_ERROR,
  16645. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  16646. fatal: false,
  16647. error: err,
  16648. reason: err.message,
  16649. frag
  16650. });
  16651. throw err;
  16652. }).then(decryptedData => {
  16653. const endTime = performance.now();
  16654. hls.trigger(Events.FRAG_DECRYPTED, {
  16655. frag,
  16656. payload: decryptedData,
  16657. stats: {
  16658. tstart: startTime,
  16659. tdecrypt: endTime
  16660. }
  16661. });
  16662. }).catch(err => {
  16663. this.warn(`${err.name}: ${err.message}`);
  16664. this.state = State.IDLE;
  16665. });
  16666. }
  16667. }
  16668. doTick() {
  16669. if (!this.media) {
  16670. this.state = State.IDLE;
  16671. return;
  16672. }
  16673. if (this.state === State.IDLE) {
  16674. const {
  16675. currentTrackId,
  16676. levels
  16677. } = this;
  16678. const track = levels == null ? void 0 : levels[currentTrackId];
  16679. if (!track || !levels.length || !track.details) {
  16680. return;
  16681. }
  16682. const {
  16683. config
  16684. } = this;
  16685. const currentTime = this.getLoadPosition();
  16686. const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  16687. const {
  16688. end: targetBufferTime,
  16689. len: bufferLen
  16690. } = bufferedInfo;
  16691. const mainBufferInfo = this.getFwdBufferInfo(this.media, PlaylistLevelType.MAIN);
  16692. const trackDetails = track.details;
  16693. const maxBufLen = this.getMaxBufferLength(mainBufferInfo == null ? void 0 : mainBufferInfo.len) + trackDetails.levelTargetDuration;
  16694. if (bufferLen > maxBufLen) {
  16695. return;
  16696. }
  16697. const fragments = trackDetails.fragments;
  16698. const fragLen = fragments.length;
  16699. const end = trackDetails.edge;
  16700. let foundFrag = null;
  16701. const fragPrevious = this.fragPrevious;
  16702. if (targetBufferTime < end) {
  16703. const tolerance = config.maxFragLookUpTolerance;
  16704. const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  16705. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  16706. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  16707. foundFrag = fragments[0];
  16708. }
  16709. } else {
  16710. foundFrag = fragments[fragLen - 1];
  16711. }
  16712. if (!foundFrag) {
  16713. return;
  16714. }
  16715. foundFrag = this.mapToInitFragWhenRequired(foundFrag);
  16716. if (foundFrag.sn !== 'initSegment') {
  16717. // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment
  16718. const curSNIdx = foundFrag.sn - trackDetails.startSN;
  16719. const prevFrag = fragments[curSNIdx - 1];
  16720. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  16721. foundFrag = prevFrag;
  16722. }
  16723. }
  16724. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  16725. // only load if fragment is not loaded
  16726. this.loadFragment(foundFrag, track, targetBufferTime);
  16727. }
  16728. }
  16729. }
  16730. getMaxBufferLength(mainBufferLength) {
  16731. const maxConfigBuffer = super.getMaxBufferLength();
  16732. if (!mainBufferLength) {
  16733. return maxConfigBuffer;
  16734. }
  16735. return Math.max(maxConfigBuffer, mainBufferLength);
  16736. }
  16737. loadFragment(frag, level, targetBufferTime) {
  16738. this.fragCurrent = frag;
  16739. if (frag.sn === 'initSegment') {
  16740. this._loadInitSegment(frag, level);
  16741. } else {
  16742. this.startFragRequested = true;
  16743. super.loadFragment(frag, level, targetBufferTime);
  16744. }
  16745. }
  16746. get mediaBufferTimeRanges() {
  16747. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  16748. }
  16749. }
  16750. class BufferableInstance {
  16751. constructor(timeranges) {
  16752. this.buffered = void 0;
  16753. const getRange = (name, index, length) => {
  16754. index = index >>> 0;
  16755. if (index > length - 1) {
  16756. throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);
  16757. }
  16758. return timeranges[index][name];
  16759. };
  16760. this.buffered = {
  16761. get length() {
  16762. return timeranges.length;
  16763. },
  16764. end(index) {
  16765. return getRange('end', index, timeranges.length);
  16766. },
  16767. start(index) {
  16768. return getRange('start', index, timeranges.length);
  16769. }
  16770. };
  16771. }
  16772. }
  16773. class SubtitleTrackController extends BasePlaylistController {
  16774. constructor(hls) {
  16775. super(hls, '[subtitle-track-controller]');
  16776. this.media = null;
  16777. this.tracks = [];
  16778. this.groupIds = null;
  16779. this.tracksInGroup = [];
  16780. this.trackId = -1;
  16781. this.currentTrack = null;
  16782. this.selectDefaultTrack = true;
  16783. this.queuedDefaultTrack = -1;
  16784. this.asyncPollTrackChange = () => this.pollTrackChange(0);
  16785. this.useTextTrackPolling = false;
  16786. this.subtitlePollingInterval = -1;
  16787. this._subtitleDisplay = true;
  16788. this.onTextTracksChanged = () => {
  16789. if (!this.useTextTrackPolling) {
  16790. self.clearInterval(this.subtitlePollingInterval);
  16791. }
  16792. // Media is undefined when switching streams via loadSource()
  16793. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  16794. return;
  16795. }
  16796. let textTrack = null;
  16797. const tracks = filterSubtitleTracks(this.media.textTracks);
  16798. for (let i = 0; i < tracks.length; i++) {
  16799. if (tracks[i].mode === 'hidden') {
  16800. // Do not break in case there is a following track with showing.
  16801. textTrack = tracks[i];
  16802. } else if (tracks[i].mode === 'showing') {
  16803. textTrack = tracks[i];
  16804. break;
  16805. }
  16806. }
  16807. // Find internal track index for TextTrack
  16808. const trackId = this.findTrackForTextTrack(textTrack);
  16809. if (this.subtitleTrack !== trackId) {
  16810. this.setSubtitleTrack(trackId);
  16811. }
  16812. };
  16813. this.registerListeners();
  16814. }
  16815. destroy() {
  16816. this.unregisterListeners();
  16817. this.tracks.length = 0;
  16818. this.tracksInGroup.length = 0;
  16819. this.currentTrack = null;
  16820. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  16821. super.destroy();
  16822. }
  16823. get subtitleDisplay() {
  16824. return this._subtitleDisplay;
  16825. }
  16826. set subtitleDisplay(value) {
  16827. this._subtitleDisplay = value;
  16828. if (this.trackId > -1) {
  16829. this.toggleTrackModes();
  16830. }
  16831. }
  16832. registerListeners() {
  16833. const {
  16834. hls
  16835. } = this;
  16836. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16837. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16838. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16839. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16840. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16841. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16842. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16843. hls.on(Events.ERROR, this.onError, this);
  16844. }
  16845. unregisterListeners() {
  16846. const {
  16847. hls
  16848. } = this;
  16849. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16850. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16851. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16852. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  16853. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  16854. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  16855. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  16856. hls.off(Events.ERROR, this.onError, this);
  16857. }
  16858. // Listen for subtitle track change, then extract the current track ID.
  16859. onMediaAttached(event, data) {
  16860. this.media = data.media;
  16861. if (!this.media) {
  16862. return;
  16863. }
  16864. if (this.queuedDefaultTrack > -1) {
  16865. this.subtitleTrack = this.queuedDefaultTrack;
  16866. this.queuedDefaultTrack = -1;
  16867. }
  16868. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  16869. if (this.useTextTrackPolling) {
  16870. this.pollTrackChange(500);
  16871. } else {
  16872. this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
  16873. }
  16874. }
  16875. pollTrackChange(timeout) {
  16876. self.clearInterval(this.subtitlePollingInterval);
  16877. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  16878. }
  16879. onMediaDetaching() {
  16880. if (!this.media) {
  16881. return;
  16882. }
  16883. self.clearInterval(this.subtitlePollingInterval);
  16884. if (!this.useTextTrackPolling) {
  16885. this.media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
  16886. }
  16887. if (this.trackId > -1) {
  16888. this.queuedDefaultTrack = this.trackId;
  16889. }
  16890. const textTracks = filterSubtitleTracks(this.media.textTracks);
  16891. // Clear loaded cues on media detachment from tracks
  16892. textTracks.forEach(track => {
  16893. clearCurrentCues(track);
  16894. });
  16895. // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
  16896. this.subtitleTrack = -1;
  16897. this.media = null;
  16898. }
  16899. onManifestLoading() {
  16900. this.tracks = [];
  16901. this.groupIds = null;
  16902. this.tracksInGroup = [];
  16903. this.trackId = -1;
  16904. this.currentTrack = null;
  16905. this.selectDefaultTrack = true;
  16906. }
  16907. // Fired whenever a new manifest is loaded.
  16908. onManifestParsed(event, data) {
  16909. this.tracks = data.subtitleTracks;
  16910. }
  16911. onSubtitleTrackLoaded(event, data) {
  16912. const {
  16913. id,
  16914. groupId,
  16915. details
  16916. } = data;
  16917. const trackInActiveGroup = this.tracksInGroup[id];
  16918. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  16919. this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);
  16920. return;
  16921. }
  16922. const curDetails = trackInActiveGroup.details;
  16923. trackInActiveGroup.details = data.details;
  16924. this.log(`Subtitle track ${id} "${trackInActiveGroup.name}" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);
  16925. if (id === this.trackId) {
  16926. this.playlistLoaded(id, data, curDetails);
  16927. }
  16928. }
  16929. onLevelLoading(event, data) {
  16930. this.switchLevel(data.level);
  16931. }
  16932. onLevelSwitching(event, data) {
  16933. this.switchLevel(data.level);
  16934. }
  16935. switchLevel(levelIndex) {
  16936. const levelInfo = this.hls.levels[levelIndex];
  16937. if (!levelInfo) {
  16938. return;
  16939. }
  16940. const subtitleGroups = levelInfo.subtitleGroups || null;
  16941. const currentGroups = this.groupIds;
  16942. let currentTrack = this.currentTrack;
  16943. 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)) {
  16944. this.groupIds = subtitleGroups;
  16945. this.trackId = -1;
  16946. this.currentTrack = null;
  16947. const subtitleTracks = this.tracks.filter(track => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);
  16948. if (subtitleTracks.length) {
  16949. // Disable selectDefaultTrack if there are no default tracks
  16950. if (this.selectDefaultTrack && !subtitleTracks.some(track => track.default)) {
  16951. this.selectDefaultTrack = false;
  16952. }
  16953. // track.id should match hls.audioTracks index
  16954. subtitleTracks.forEach((track, i) => {
  16955. track.id = i;
  16956. });
  16957. } else if (!currentTrack && !this.tracksInGroup.length) {
  16958. // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks
  16959. return;
  16960. }
  16961. this.tracksInGroup = subtitleTracks;
  16962. // Find preferred track
  16963. const subtitlePreference = this.hls.config.subtitlePreference;
  16964. if (!currentTrack && subtitlePreference) {
  16965. this.selectDefaultTrack = false;
  16966. const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  16967. if (groupIndex > -1) {
  16968. currentTrack = subtitleTracks[groupIndex];
  16969. } else {
  16970. const allIndex = findMatchingOption(subtitlePreference, this.tracks);
  16971. currentTrack = this.tracks[allIndex];
  16972. }
  16973. }
  16974. // Select initial track
  16975. let trackId = this.findTrackId(currentTrack);
  16976. if (trackId === -1 && currentTrack) {
  16977. trackId = this.findTrackId(null);
  16978. }
  16979. // Dispatch events and load track if needed
  16980. const subtitleTracksUpdated = {
  16981. subtitleTracks
  16982. };
  16983. this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in "${subtitleGroups == null ? void 0 : subtitleGroups.join(',')}" group-id`);
  16984. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  16985. if (trackId !== -1 && this.trackId === -1) {
  16986. this.setSubtitleTrack(trackId);
  16987. }
  16988. } else if (this.shouldReloadPlaylist(currentTrack)) {
  16989. // Retry playlist loading if no playlist is or has been loaded yet
  16990. this.setSubtitleTrack(this.trackId);
  16991. }
  16992. }
  16993. findTrackId(currentTrack) {
  16994. const tracks = this.tracksInGroup;
  16995. const selectDefault = this.selectDefaultTrack;
  16996. for (let i = 0; i < tracks.length; i++) {
  16997. const track = tracks[i];
  16998. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  16999. continue;
  17000. }
  17001. if (!currentTrack || matchesOption(track, currentTrack)) {
  17002. return i;
  17003. }
  17004. }
  17005. if (currentTrack) {
  17006. for (let i = 0; i < tracks.length; i++) {
  17007. const track = tracks[i];
  17008. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  17009. return i;
  17010. }
  17011. }
  17012. for (let i = 0; i < tracks.length; i++) {
  17013. const track = tracks[i];
  17014. if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {
  17015. return i;
  17016. }
  17017. }
  17018. }
  17019. return -1;
  17020. }
  17021. findTrackForTextTrack(textTrack) {
  17022. if (textTrack) {
  17023. const tracks = this.tracksInGroup;
  17024. for (let i = 0; i < tracks.length; i++) {
  17025. const track = tracks[i];
  17026. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  17027. return i;
  17028. }
  17029. }
  17030. }
  17031. return -1;
  17032. }
  17033. onError(event, data) {
  17034. if (data.fatal || !data.context) {
  17035. return;
  17036. }
  17037. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  17038. this.checkRetry(data);
  17039. }
  17040. }
  17041. get allSubtitleTracks() {
  17042. return this.tracks;
  17043. }
  17044. /** get alternate subtitle tracks list from playlist **/
  17045. get subtitleTracks() {
  17046. return this.tracksInGroup;
  17047. }
  17048. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  17049. get subtitleTrack() {
  17050. return this.trackId;
  17051. }
  17052. set subtitleTrack(newId) {
  17053. this.selectDefaultTrack = false;
  17054. this.setSubtitleTrack(newId);
  17055. }
  17056. setSubtitleOption(subtitleOption) {
  17057. this.hls.config.subtitlePreference = subtitleOption;
  17058. if (subtitleOption) {
  17059. const allSubtitleTracks = this.allSubtitleTracks;
  17060. this.selectDefaultTrack = false;
  17061. if (allSubtitleTracks.length) {
  17062. // First see if current option matches (no switch op)
  17063. const currentTrack = this.currentTrack;
  17064. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  17065. return currentTrack;
  17066. }
  17067. // Find option in current group
  17068. const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  17069. if (groupIndex > -1) {
  17070. const track = this.tracksInGroup[groupIndex];
  17071. this.setSubtitleTrack(groupIndex);
  17072. return track;
  17073. } else if (currentTrack) {
  17074. // If this is not the initial selection return null
  17075. // option should have matched one in active group
  17076. return null;
  17077. } else {
  17078. // Find the option in all tracks for initial selection
  17079. const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  17080. if (allIndex > -1) {
  17081. return allSubtitleTracks[allIndex];
  17082. }
  17083. }
  17084. }
  17085. }
  17086. return null;
  17087. }
  17088. loadPlaylist(hlsUrlParameters) {
  17089. super.loadPlaylist();
  17090. const currentTrack = this.currentTrack;
  17091. if (this.shouldLoadPlaylist(currentTrack) && currentTrack) {
  17092. const id = currentTrack.id;
  17093. const groupId = currentTrack.groupId;
  17094. let url = currentTrack.url;
  17095. if (hlsUrlParameters) {
  17096. try {
  17097. url = hlsUrlParameters.addDirectives(url);
  17098. } catch (error) {
  17099. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  17100. }
  17101. }
  17102. this.log(`Loading subtitle playlist for id ${id}`);
  17103. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  17104. url,
  17105. id,
  17106. groupId,
  17107. deliveryDirectives: hlsUrlParameters || null
  17108. });
  17109. }
  17110. }
  17111. /**
  17112. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  17113. * This operates on the DOM textTracks.
  17114. * A value of -1 will disable all subtitle tracks.
  17115. */
  17116. toggleTrackModes() {
  17117. const {
  17118. media
  17119. } = this;
  17120. if (!media) {
  17121. return;
  17122. }
  17123. const textTracks = filterSubtitleTracks(media.textTracks);
  17124. const currentTrack = this.currentTrack;
  17125. let nextTrack;
  17126. if (currentTrack) {
  17127. nextTrack = textTracks.filter(textTrack => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];
  17128. if (!nextTrack) {
  17129. this.warn(`Unable to find subtitle TextTrack with name "${currentTrack.name}" and language "${currentTrack.lang}"`);
  17130. }
  17131. }
  17132. [].slice.call(textTracks).forEach(track => {
  17133. if (track.mode !== 'disabled' && track !== nextTrack) {
  17134. track.mode = 'disabled';
  17135. }
  17136. });
  17137. if (nextTrack) {
  17138. const mode = this.subtitleDisplay ? 'showing' : 'hidden';
  17139. if (nextTrack.mode !== mode) {
  17140. nextTrack.mode = mode;
  17141. }
  17142. }
  17143. }
  17144. /**
  17145. * This method is responsible for validating the subtitle index and periodically reloading if live.
  17146. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  17147. */
  17148. setSubtitleTrack(newId) {
  17149. const tracks = this.tracksInGroup;
  17150. // setting this.subtitleTrack will trigger internal logic
  17151. // if media has not been attached yet, it will fail
  17152. // we keep a reference to the default track id
  17153. // and we'll set subtitleTrack when onMediaAttached is triggered
  17154. if (!this.media) {
  17155. this.queuedDefaultTrack = newId;
  17156. return;
  17157. }
  17158. // exit if track id as already set or invalid
  17159. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  17160. this.warn(`Invalid subtitle track id: ${newId}`);
  17161. return;
  17162. }
  17163. // stopping live reloading timer if any
  17164. this.clearTimer();
  17165. this.selectDefaultTrack = false;
  17166. const lastTrack = this.currentTrack;
  17167. const track = tracks[newId] || null;
  17168. this.trackId = newId;
  17169. this.currentTrack = track;
  17170. this.toggleTrackModes();
  17171. if (!track) {
  17172. // switch to -1
  17173. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  17174. id: newId
  17175. });
  17176. return;
  17177. }
  17178. const trackLoaded = !!track.details && !track.details.live;
  17179. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  17180. return;
  17181. }
  17182. this.log(`Switching to subtitle-track ${newId}` + (track ? ` "${track.name}" lang:${track.lang} group:${track.groupId}` : ''));
  17183. const {
  17184. id,
  17185. groupId = '',
  17186. name,
  17187. type,
  17188. url
  17189. } = track;
  17190. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  17191. id,
  17192. groupId,
  17193. name,
  17194. type,
  17195. url
  17196. });
  17197. const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  17198. this.loadPlaylist(hlsUrlParameters);
  17199. }
  17200. }
  17201. class BufferOperationQueue {
  17202. constructor(sourceBufferReference) {
  17203. this.buffers = void 0;
  17204. this.queues = {
  17205. video: [],
  17206. audio: [],
  17207. audiovideo: []
  17208. };
  17209. this.buffers = sourceBufferReference;
  17210. }
  17211. append(operation, type, pending) {
  17212. const queue = this.queues[type];
  17213. queue.push(operation);
  17214. if (queue.length === 1 && !pending) {
  17215. this.executeNext(type);
  17216. }
  17217. }
  17218. insertAbort(operation, type) {
  17219. const queue = this.queues[type];
  17220. queue.unshift(operation);
  17221. this.executeNext(type);
  17222. }
  17223. appendBlocker(type) {
  17224. let execute;
  17225. const promise = new Promise(resolve => {
  17226. execute = resolve;
  17227. });
  17228. const operation = {
  17229. execute,
  17230. onStart: () => {},
  17231. onComplete: () => {},
  17232. onError: () => {}
  17233. };
  17234. this.append(operation, type);
  17235. return promise;
  17236. }
  17237. executeNext(type) {
  17238. const queue = this.queues[type];
  17239. if (queue.length) {
  17240. const operation = queue[0];
  17241. try {
  17242. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  17243. // which do not end with this event must call _onSBUpdateEnd manually
  17244. operation.execute();
  17245. } catch (error) {
  17246. logger.warn(`[buffer-operation-queue]: Exception executing "${type}" SourceBuffer operation: ${error}`);
  17247. operation.onError(error);
  17248. // Only shift the current operation off, otherwise the updateend handler will do this for us
  17249. const sb = this.buffers[type];
  17250. if (!(sb != null && sb.updating)) {
  17251. this.shiftAndExecuteNext(type);
  17252. }
  17253. }
  17254. }
  17255. }
  17256. shiftAndExecuteNext(type) {
  17257. this.queues[type].shift();
  17258. this.executeNext(type);
  17259. }
  17260. current(type) {
  17261. return this.queues[type][0];
  17262. }
  17263. }
  17264. const VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  17265. class BufferController {
  17266. constructor(hls) {
  17267. // The level details used to determine duration, target-duration and live
  17268. this.details = null;
  17269. // cache the self generated object url to detect hijack of video tag
  17270. this._objectUrl = null;
  17271. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  17272. this.operationQueue = void 0;
  17273. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  17274. this.listeners = void 0;
  17275. this.hls = void 0;
  17276. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  17277. this.bufferCodecEventsExpected = 0;
  17278. // The total number of BUFFER_CODEC events received
  17279. this._bufferCodecEventsTotal = 0;
  17280. // A reference to the attached media element
  17281. this.media = null;
  17282. // A reference to the active media source
  17283. this.mediaSource = null;
  17284. // Last MP3 audio chunk appended
  17285. this.lastMpegAudioChunk = null;
  17286. this.appendSource = void 0;
  17287. // counters
  17288. this.appendErrors = {
  17289. audio: 0,
  17290. video: 0,
  17291. audiovideo: 0
  17292. };
  17293. this.tracks = {};
  17294. this.pendingTracks = {};
  17295. this.sourceBuffer = void 0;
  17296. this.log = void 0;
  17297. this.warn = void 0;
  17298. this.error = void 0;
  17299. this._onEndStreaming = event => {
  17300. if (!this.hls) {
  17301. return;
  17302. }
  17303. this.hls.pauseBuffering();
  17304. };
  17305. this._onStartStreaming = event => {
  17306. if (!this.hls) {
  17307. return;
  17308. }
  17309. this.hls.resumeBuffering();
  17310. };
  17311. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  17312. this._onMediaSourceOpen = () => {
  17313. const {
  17314. media,
  17315. mediaSource
  17316. } = this;
  17317. this.log('Media source opened');
  17318. if (media) {
  17319. media.removeEventListener('emptied', this._onMediaEmptied);
  17320. this.updateMediaElementDuration();
  17321. this.hls.trigger(Events.MEDIA_ATTACHED, {
  17322. media,
  17323. mediaSource: mediaSource
  17324. });
  17325. }
  17326. if (mediaSource) {
  17327. // once received, don't listen anymore to sourceopen event
  17328. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  17329. }
  17330. this.checkPendingTracks();
  17331. };
  17332. this._onMediaSourceClose = () => {
  17333. this.log('Media source closed');
  17334. };
  17335. this._onMediaSourceEnded = () => {
  17336. this.log('Media source ended');
  17337. };
  17338. this._onMediaEmptied = () => {
  17339. const {
  17340. mediaSrc,
  17341. _objectUrl
  17342. } = this;
  17343. if (mediaSrc !== _objectUrl) {
  17344. logger.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);
  17345. }
  17346. };
  17347. this.hls = hls;
  17348. const logPrefix = '[buffer-controller]';
  17349. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  17350. this.log = logger.log.bind(logger, logPrefix);
  17351. this.warn = logger.warn.bind(logger, logPrefix);
  17352. this.error = logger.error.bind(logger, logPrefix);
  17353. this._initSourceBuffer();
  17354. this.registerListeners();
  17355. }
  17356. hasSourceTypes() {
  17357. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  17358. }
  17359. destroy() {
  17360. this.unregisterListeners();
  17361. this.details = null;
  17362. this.lastMpegAudioChunk = null;
  17363. // @ts-ignore
  17364. this.hls = null;
  17365. }
  17366. registerListeners() {
  17367. const {
  17368. hls
  17369. } = this;
  17370. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17371. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17372. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17373. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17374. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  17375. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17376. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17377. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  17378. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17379. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17380. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  17381. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  17382. }
  17383. unregisterListeners() {
  17384. const {
  17385. hls
  17386. } = this;
  17387. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  17388. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17389. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17390. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17391. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  17392. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  17393. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  17394. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  17395. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  17396. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  17397. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  17398. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  17399. }
  17400. _initSourceBuffer() {
  17401. this.sourceBuffer = {};
  17402. this.operationQueue = new BufferOperationQueue(this.sourceBuffer);
  17403. this.listeners = {
  17404. audio: [],
  17405. video: [],
  17406. audiovideo: []
  17407. };
  17408. this.appendErrors = {
  17409. audio: 0,
  17410. video: 0,
  17411. audiovideo: 0
  17412. };
  17413. this.lastMpegAudioChunk = null;
  17414. }
  17415. onManifestLoading() {
  17416. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;
  17417. this.details = null;
  17418. }
  17419. onManifestParsed(event, data) {
  17420. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  17421. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  17422. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  17423. // it will contain the expected nb of source buffers, no need to compute it
  17424. let codecEvents = 2;
  17425. if (data.audio && !data.video || !data.altAudio || !true) {
  17426. codecEvents = 1;
  17427. }
  17428. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  17429. this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);
  17430. }
  17431. onMediaAttaching(event, data) {
  17432. const media = this.media = data.media;
  17433. const MediaSource = getMediaSource(this.appendSource);
  17434. if (media && MediaSource) {
  17435. var _ms$constructor;
  17436. const ms = this.mediaSource = new MediaSource();
  17437. this.log(`created media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);
  17438. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  17439. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  17440. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  17441. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  17442. if (this.appendSource) {
  17443. ms.addEventListener('startstreaming', this._onStartStreaming);
  17444. ms.addEventListener('endstreaming', this._onEndStreaming);
  17445. }
  17446. // cache the locally generated object url
  17447. const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  17448. // link video and media Source
  17449. if (this.appendSource) {
  17450. try {
  17451. media.removeAttribute('src');
  17452. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  17453. const MMS = self.ManagedMediaSource;
  17454. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  17455. removeSourceChildren(media);
  17456. addSource(media, objectUrl);
  17457. media.load();
  17458. } catch (error) {
  17459. media.src = objectUrl;
  17460. }
  17461. } else {
  17462. media.src = objectUrl;
  17463. }
  17464. media.addEventListener('emptied', this._onMediaEmptied);
  17465. }
  17466. }
  17467. onMediaDetaching() {
  17468. const {
  17469. media,
  17470. mediaSource,
  17471. _objectUrl
  17472. } = this;
  17473. if (mediaSource) {
  17474. this.log('media source detaching');
  17475. if (mediaSource.readyState === 'open') {
  17476. try {
  17477. // endOfStream could trigger exception if any sourcebuffer is in updating state
  17478. // we don't really care about checking sourcebuffer state here,
  17479. // as we are anyway detaching the MediaSource
  17480. // let's just avoid this exception to propagate
  17481. mediaSource.endOfStream();
  17482. } catch (err) {
  17483. this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);
  17484. }
  17485. }
  17486. // Clean up the SourceBuffers by invoking onBufferReset
  17487. this.onBufferReset();
  17488. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  17489. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  17490. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  17491. if (this.appendSource) {
  17492. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  17493. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  17494. }
  17495. // Detach properly the MediaSource from the HTMLMediaElement as
  17496. // suggested in https://github.com/w3c/media-source/issues/53.
  17497. if (media) {
  17498. media.removeEventListener('emptied', this._onMediaEmptied);
  17499. if (_objectUrl) {
  17500. self.URL.revokeObjectURL(_objectUrl);
  17501. }
  17502. // clean up video tag src only if it's our own url. some external libraries might
  17503. // hijack the video tag and change its 'src' without destroying the Hls instance first
  17504. if (this.mediaSrc === _objectUrl) {
  17505. media.removeAttribute('src');
  17506. if (this.appendSource) {
  17507. removeSourceChildren(media);
  17508. }
  17509. media.load();
  17510. } else {
  17511. this.warn('media|source.src was changed by a third party - skip cleanup');
  17512. }
  17513. }
  17514. this.mediaSource = null;
  17515. this.media = null;
  17516. this._objectUrl = null;
  17517. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  17518. this.pendingTracks = {};
  17519. this.tracks = {};
  17520. }
  17521. this.hls.trigger(Events.MEDIA_DETACHED, undefined);
  17522. }
  17523. onBufferReset() {
  17524. this.getSourceBufferTypes().forEach(type => {
  17525. this.resetBuffer(type);
  17526. });
  17527. this._initSourceBuffer();
  17528. }
  17529. resetBuffer(type) {
  17530. const sb = this.sourceBuffer[type];
  17531. try {
  17532. if (sb) {
  17533. var _this$mediaSource;
  17534. this.removeBufferListeners(type);
  17535. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  17536. // accessing it
  17537. this.sourceBuffer[type] = undefined;
  17538. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  17539. this.mediaSource.removeSourceBuffer(sb);
  17540. }
  17541. }
  17542. } catch (err) {
  17543. this.warn(`onBufferReset ${type}`, err);
  17544. }
  17545. }
  17546. onBufferCodecs(event, data) {
  17547. const sourceBufferCount = this.getSourceBufferTypes().length;
  17548. const trackNames = Object.keys(data);
  17549. trackNames.forEach(trackName => {
  17550. if (sourceBufferCount) {
  17551. // check if SourceBuffer codec needs to change
  17552. const track = this.tracks[trackName];
  17553. if (track && typeof track.buffer.changeType === 'function') {
  17554. var _trackCodec;
  17555. const {
  17556. id,
  17557. codec,
  17558. levelCodec,
  17559. container,
  17560. metadata
  17561. } = data[trackName];
  17562. const currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec);
  17563. const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  17564. let trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  17565. const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  17566. if (trackCodec && currentCodec !== nextCodec) {
  17567. if (trackName.slice(0, 5) === 'audio') {
  17568. trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);
  17569. }
  17570. const mimeType = `${container};codecs=${trackCodec}`;
  17571. this.appendChangeType(trackName, mimeType);
  17572. this.log(`switching codec ${currentCodecFull} to ${trackCodec}`);
  17573. this.tracks[trackName] = {
  17574. buffer: track.buffer,
  17575. codec,
  17576. container,
  17577. levelCodec,
  17578. metadata,
  17579. id
  17580. };
  17581. }
  17582. }
  17583. } else {
  17584. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  17585. this.pendingTracks[trackName] = data[trackName];
  17586. }
  17587. });
  17588. // if sourcebuffers already created, do nothing ...
  17589. if (sourceBufferCount) {
  17590. return;
  17591. }
  17592. const bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  17593. if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {
  17594. this.log(`${bufferCodecEventsExpected} bufferCodec event(s) expected ${trackNames.join(',')}`);
  17595. this.bufferCodecEventsExpected = bufferCodecEventsExpected;
  17596. }
  17597. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  17598. this.checkPendingTracks();
  17599. }
  17600. }
  17601. appendChangeType(type, mimeType) {
  17602. const {
  17603. operationQueue
  17604. } = this;
  17605. const operation = {
  17606. execute: () => {
  17607. const sb = this.sourceBuffer[type];
  17608. if (sb) {
  17609. this.log(`changing ${type} sourceBuffer type to ${mimeType}`);
  17610. sb.changeType(mimeType);
  17611. }
  17612. operationQueue.shiftAndExecuteNext(type);
  17613. },
  17614. onStart: () => {},
  17615. onComplete: () => {},
  17616. onError: error => {
  17617. this.warn(`Failed to change ${type} SourceBuffer type`, error);
  17618. }
  17619. };
  17620. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  17621. }
  17622. onBufferAppending(event, eventData) {
  17623. const {
  17624. hls,
  17625. operationQueue,
  17626. tracks
  17627. } = this;
  17628. const {
  17629. data,
  17630. type,
  17631. frag,
  17632. part,
  17633. chunkMeta
  17634. } = eventData;
  17635. const chunkStats = chunkMeta.buffering[type];
  17636. const bufferAppendingStart = self.performance.now();
  17637. chunkStats.start = bufferAppendingStart;
  17638. const fragBuffering = frag.stats.buffering;
  17639. const partBuffering = part ? part.stats.buffering : null;
  17640. if (fragBuffering.start === 0) {
  17641. fragBuffering.start = bufferAppendingStart;
  17642. }
  17643. if (partBuffering && partBuffering.start === 0) {
  17644. partBuffering.start = bufferAppendingStart;
  17645. }
  17646. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  17647. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  17648. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  17649. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  17650. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  17651. const audioTrack = tracks.audio;
  17652. let checkTimestampOffset = false;
  17653. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  17654. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  17655. this.lastMpegAudioChunk = chunkMeta;
  17656. }
  17657. const fragStart = frag.start;
  17658. const operation = {
  17659. execute: () => {
  17660. chunkStats.executeStart = self.performance.now();
  17661. if (checkTimestampOffset) {
  17662. const sb = this.sourceBuffer[type];
  17663. if (sb) {
  17664. const delta = fragStart - sb.timestampOffset;
  17665. if (Math.abs(delta) >= 0.1) {
  17666. this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`);
  17667. sb.timestampOffset = fragStart;
  17668. }
  17669. }
  17670. }
  17671. this.appendExecutor(data, type);
  17672. },
  17673. onStart: () => {
  17674. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  17675. },
  17676. onComplete: () => {
  17677. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  17678. const end = self.performance.now();
  17679. chunkStats.executeEnd = chunkStats.end = end;
  17680. if (fragBuffering.first === 0) {
  17681. fragBuffering.first = end;
  17682. }
  17683. if (partBuffering && partBuffering.first === 0) {
  17684. partBuffering.first = end;
  17685. }
  17686. const {
  17687. sourceBuffer
  17688. } = this;
  17689. const timeRanges = {};
  17690. for (const type in sourceBuffer) {
  17691. timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);
  17692. }
  17693. this.appendErrors[type] = 0;
  17694. if (type === 'audio' || type === 'video') {
  17695. this.appendErrors.audiovideo = 0;
  17696. } else {
  17697. this.appendErrors.audio = 0;
  17698. this.appendErrors.video = 0;
  17699. }
  17700. this.hls.trigger(Events.BUFFER_APPENDED, {
  17701. type,
  17702. frag,
  17703. part,
  17704. chunkMeta,
  17705. parent: frag.type,
  17706. timeRanges
  17707. });
  17708. },
  17709. onError: error => {
  17710. // in case any error occured while appending, put back segment in segments table
  17711. const event = {
  17712. type: ErrorTypes.MEDIA_ERROR,
  17713. parent: frag.type,
  17714. details: ErrorDetails.BUFFER_APPEND_ERROR,
  17715. sourceBufferName: type,
  17716. frag,
  17717. part,
  17718. chunkMeta,
  17719. error,
  17720. err: error,
  17721. fatal: false
  17722. };
  17723. if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
  17724. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  17725. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  17726. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  17727. } else {
  17728. const appendErrorCount = ++this.appendErrors[type];
  17729. event.details = ErrorDetails.BUFFER_APPEND_ERROR;
  17730. /* with UHD content, we could get loop of quota exceeded error until
  17731. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  17732. */
  17733. this.warn(`Failed ${appendErrorCount}/${hls.config.appendErrorMaxRetry} times to append segment in "${type}" sourceBuffer`);
  17734. if (appendErrorCount >= hls.config.appendErrorMaxRetry) {
  17735. event.fatal = true;
  17736. }
  17737. }
  17738. hls.trigger(Events.ERROR, event);
  17739. }
  17740. };
  17741. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  17742. }
  17743. onBufferFlushing(event, data) {
  17744. const {
  17745. operationQueue
  17746. } = this;
  17747. const flushOperation = type => ({
  17748. execute: this.removeExecutor.bind(this, type, data.startOffset, data.endOffset),
  17749. onStart: () => {
  17750. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  17751. },
  17752. onComplete: () => {
  17753. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  17754. this.hls.trigger(Events.BUFFER_FLUSHED, {
  17755. type
  17756. });
  17757. },
  17758. onError: error => {
  17759. this.warn(`Failed to remove from ${type} SourceBuffer`, error);
  17760. }
  17761. });
  17762. if (data.type) {
  17763. operationQueue.append(flushOperation(data.type), data.type);
  17764. } else {
  17765. this.getSourceBufferTypes().forEach(type => {
  17766. operationQueue.append(flushOperation(type), type);
  17767. });
  17768. }
  17769. }
  17770. onFragParsed(event, data) {
  17771. const {
  17772. frag,
  17773. part
  17774. } = data;
  17775. const buffersAppendedTo = [];
  17776. const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  17777. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  17778. buffersAppendedTo.push('audiovideo');
  17779. } else {
  17780. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  17781. buffersAppendedTo.push('audio');
  17782. }
  17783. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  17784. buffersAppendedTo.push('video');
  17785. }
  17786. }
  17787. const onUnblocked = () => {
  17788. const now = self.performance.now();
  17789. frag.stats.buffering.end = now;
  17790. if (part) {
  17791. part.stats.buffering.end = now;
  17792. }
  17793. const stats = part ? part.stats : frag.stats;
  17794. this.hls.trigger(Events.FRAG_BUFFERED, {
  17795. frag,
  17796. part,
  17797. stats,
  17798. id: frag.type
  17799. });
  17800. };
  17801. if (buffersAppendedTo.length === 0) {
  17802. this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);
  17803. }
  17804. this.blockBuffers(onUnblocked, buffersAppendedTo);
  17805. }
  17806. onFragChanged(event, data) {
  17807. this.trimBuffers();
  17808. }
  17809. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  17810. // an undefined data.type will mark all buffers as EOS.
  17811. onBufferEos(event, data) {
  17812. const ended = this.getSourceBufferTypes().reduce((acc, type) => {
  17813. const sb = this.sourceBuffer[type];
  17814. if (sb && (!data.type || data.type === type)) {
  17815. sb.ending = true;
  17816. if (!sb.ended) {
  17817. sb.ended = true;
  17818. this.log(`${type} sourceBuffer now EOS`);
  17819. }
  17820. }
  17821. return acc && !!(!sb || sb.ended);
  17822. }, true);
  17823. if (ended) {
  17824. this.log(`Queueing mediaSource.endOfStream()`);
  17825. this.blockBuffers(() => {
  17826. this.getSourceBufferTypes().forEach(type => {
  17827. const sb = this.sourceBuffer[type];
  17828. if (sb) {
  17829. sb.ending = false;
  17830. }
  17831. });
  17832. const {
  17833. mediaSource
  17834. } = this;
  17835. if (!mediaSource || mediaSource.readyState !== 'open') {
  17836. if (mediaSource) {
  17837. this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);
  17838. }
  17839. return;
  17840. }
  17841. this.log(`Calling mediaSource.endOfStream()`);
  17842. // Allow this to throw and be caught by the enqueueing function
  17843. mediaSource.endOfStream();
  17844. });
  17845. }
  17846. }
  17847. onLevelUpdated(event, {
  17848. details
  17849. }) {
  17850. if (!details.fragments.length) {
  17851. return;
  17852. }
  17853. this.details = details;
  17854. if (this.getSourceBufferTypes().length) {
  17855. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  17856. } else {
  17857. this.updateMediaElementDuration();
  17858. }
  17859. }
  17860. trimBuffers() {
  17861. const {
  17862. hls,
  17863. details,
  17864. media
  17865. } = this;
  17866. if (!media || details === null) {
  17867. return;
  17868. }
  17869. const sourceBufferTypes = this.getSourceBufferTypes();
  17870. if (!sourceBufferTypes.length) {
  17871. return;
  17872. }
  17873. const config = hls.config;
  17874. const currentTime = media.currentTime;
  17875. const targetDuration = details.levelTargetDuration;
  17876. // Support for deprecated liveBackBufferLength
  17877. const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  17878. if (isFiniteNumber(backBufferLength) && backBufferLength > 0) {
  17879. const maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  17880. const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  17881. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  17882. }
  17883. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  17884. const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  17885. const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  17886. const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  17887. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  17888. }
  17889. }
  17890. flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  17891. const {
  17892. details,
  17893. sourceBuffer
  17894. } = this;
  17895. const sourceBufferTypes = this.getSourceBufferTypes();
  17896. sourceBufferTypes.forEach(type => {
  17897. const sb = sourceBuffer[type];
  17898. if (sb) {
  17899. const buffered = BufferHelper.getBuffered(sb);
  17900. // when target buffer start exceeds actual buffer start
  17901. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  17902. this.hls.trigger(Events.BACK_BUFFER_REACHED, {
  17903. bufferEnd: targetBackBufferPosition
  17904. });
  17905. // Support for deprecated event:
  17906. if (details != null && details.live) {
  17907. this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  17908. bufferEnd: targetBackBufferPosition
  17909. });
  17910. } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) {
  17911. this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);
  17912. return;
  17913. }
  17914. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17915. startOffset: 0,
  17916. endOffset: targetBackBufferPosition,
  17917. type
  17918. });
  17919. }
  17920. }
  17921. });
  17922. }
  17923. flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  17924. const {
  17925. sourceBuffer
  17926. } = this;
  17927. const sourceBufferTypes = this.getSourceBufferTypes();
  17928. sourceBufferTypes.forEach(type => {
  17929. const sb = sourceBuffer[type];
  17930. if (sb) {
  17931. const buffered = BufferHelper.getBuffered(sb);
  17932. const numBufferedRanges = buffered.length;
  17933. // The buffer is either empty or contiguous
  17934. if (numBufferedRanges < 2) {
  17935. return;
  17936. }
  17937. const bufferStart = buffered.start(numBufferedRanges - 1);
  17938. const bufferEnd = buffered.end(numBufferedRanges - 1);
  17939. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  17940. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  17941. return;
  17942. } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {
  17943. this.log(`Cannot flush ${type} front buffer while SourceBuffer is in ended state`);
  17944. return;
  17945. }
  17946. this.hls.trigger(Events.BUFFER_FLUSHING, {
  17947. startOffset: bufferStart,
  17948. endOffset: Infinity,
  17949. type
  17950. });
  17951. }
  17952. });
  17953. }
  17954. /**
  17955. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  17956. * 'liveDurationInfinity` is set to `true`
  17957. * More details: https://github.com/video-dev/hls.js/issues/355
  17958. */
  17959. updateMediaElementDuration() {
  17960. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  17961. return;
  17962. }
  17963. const {
  17964. details,
  17965. hls,
  17966. media,
  17967. mediaSource
  17968. } = this;
  17969. const levelDuration = details.fragments[0].start + details.totalduration;
  17970. const mediaDuration = media.duration;
  17971. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  17972. if (details.live && hls.config.liveDurationInfinity) {
  17973. // Override duration to Infinity
  17974. mediaSource.duration = Infinity;
  17975. this.updateSeekableRange(details);
  17976. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) {
  17977. // levelDuration was the last value we set.
  17978. // not using mediaSource.duration as the browser may tweak this value
  17979. // only update Media Source duration if its value increase, this is to avoid
  17980. // flushing already buffered portion when switching between quality level
  17981. this.log(`Updating Media Source duration to ${levelDuration.toFixed(3)}`);
  17982. mediaSource.duration = levelDuration;
  17983. }
  17984. }
  17985. updateSeekableRange(levelDetails) {
  17986. const mediaSource = this.mediaSource;
  17987. const fragments = levelDetails.fragments;
  17988. const len = fragments.length;
  17989. if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) {
  17990. const start = Math.max(0, fragments[0].start);
  17991. const end = Math.max(start, start + levelDetails.totalduration);
  17992. this.log(`Media Source duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);
  17993. mediaSource.setLiveSeekableRange(start, end);
  17994. }
  17995. }
  17996. checkPendingTracks() {
  17997. const {
  17998. bufferCodecEventsExpected,
  17999. operationQueue,
  18000. pendingTracks
  18001. } = this;
  18002. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  18003. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  18004. // data has been appended to existing ones.
  18005. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  18006. const pendingTracksCount = Object.keys(pendingTracks).length;
  18007. if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || 'audiovideo' in pendingTracks)) {
  18008. // ok, let's create them now !
  18009. this.createSourceBuffers(pendingTracks);
  18010. this.pendingTracks = {};
  18011. // append any pending segments now !
  18012. const buffers = this.getSourceBufferTypes();
  18013. if (buffers.length) {
  18014. this.hls.trigger(Events.BUFFER_CREATED, {
  18015. tracks: this.tracks
  18016. });
  18017. buffers.forEach(type => {
  18018. operationQueue.executeNext(type);
  18019. });
  18020. } else {
  18021. const error = new Error('could not create source buffer for media codec(s)');
  18022. this.hls.trigger(Events.ERROR, {
  18023. type: ErrorTypes.MEDIA_ERROR,
  18024. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  18025. fatal: true,
  18026. error,
  18027. reason: error.message
  18028. });
  18029. }
  18030. }
  18031. }
  18032. createSourceBuffers(tracks) {
  18033. const {
  18034. sourceBuffer,
  18035. mediaSource
  18036. } = this;
  18037. if (!mediaSource) {
  18038. throw Error('createSourceBuffers called when mediaSource was null');
  18039. }
  18040. for (const trackName in tracks) {
  18041. if (!sourceBuffer[trackName]) {
  18042. var _track$levelCodec;
  18043. const track = tracks[trackName];
  18044. if (!track) {
  18045. throw Error(`source buffer exists for track ${trackName}, however track does not`);
  18046. }
  18047. // use levelCodec as first priority unless it contains multiple comma-separated codec values
  18048. let codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(',')) === -1 ? track.levelCodec : track.codec;
  18049. if (codec) {
  18050. if (trackName.slice(0, 5) === 'audio') {
  18051. codec = getCodecCompatibleName(codec, this.appendSource);
  18052. }
  18053. }
  18054. const mimeType = `${track.container};codecs=${codec}`;
  18055. this.log(`creating sourceBuffer(${mimeType})`);
  18056. try {
  18057. const sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  18058. const sbName = trackName;
  18059. this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
  18060. this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
  18061. this.addBufferListener(sbName, 'error', this._onSBUpdateError);
  18062. // ManagedSourceBuffer bufferedchange event
  18063. if (this.appendSource) {
  18064. this.addBufferListener(sbName, 'bufferedchange', (type, event) => {
  18065. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  18066. const removedRanges = event.removedRanges;
  18067. if (removedRanges != null && removedRanges.length) {
  18068. this.hls.trigger(Events.BUFFER_FLUSHED, {
  18069. type: trackName
  18070. });
  18071. }
  18072. });
  18073. }
  18074. this.tracks[trackName] = {
  18075. buffer: sb,
  18076. codec: codec,
  18077. container: track.container,
  18078. levelCodec: track.levelCodec,
  18079. metadata: track.metadata,
  18080. id: track.id
  18081. };
  18082. } catch (err) {
  18083. this.error(`error while trying to add sourceBuffer: ${err.message}`);
  18084. this.hls.trigger(Events.ERROR, {
  18085. type: ErrorTypes.MEDIA_ERROR,
  18086. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  18087. fatal: false,
  18088. error: err,
  18089. sourceBufferName: trackName,
  18090. mimeType: mimeType
  18091. });
  18092. }
  18093. }
  18094. }
  18095. }
  18096. get mediaSrc() {
  18097. var _this$media;
  18098. const media = ((_this$media = this.media) == null ? void 0 : _this$media.firstChild) || this.media;
  18099. return media == null ? void 0 : media.src;
  18100. }
  18101. _onSBUpdateStart(type) {
  18102. const {
  18103. operationQueue
  18104. } = this;
  18105. const operation = operationQueue.current(type);
  18106. operation.onStart();
  18107. }
  18108. _onSBUpdateEnd(type) {
  18109. var _this$mediaSource2;
  18110. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  18111. this.resetBuffer(type);
  18112. return;
  18113. }
  18114. const {
  18115. operationQueue
  18116. } = this;
  18117. const operation = operationQueue.current(type);
  18118. operation.onComplete();
  18119. operationQueue.shiftAndExecuteNext(type);
  18120. }
  18121. _onSBUpdateError(type, event) {
  18122. var _this$mediaSource3;
  18123. const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState}`);
  18124. this.error(`${error}`, event);
  18125. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  18126. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  18127. this.hls.trigger(Events.ERROR, {
  18128. type: ErrorTypes.MEDIA_ERROR,
  18129. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  18130. sourceBufferName: type,
  18131. error,
  18132. fatal: false
  18133. });
  18134. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  18135. const operation = this.operationQueue.current(type);
  18136. if (operation) {
  18137. operation.onError(error);
  18138. }
  18139. }
  18140. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  18141. removeExecutor(type, startOffset, endOffset) {
  18142. const {
  18143. media,
  18144. mediaSource,
  18145. operationQueue,
  18146. sourceBuffer
  18147. } = this;
  18148. const sb = sourceBuffer[type];
  18149. if (!media || !mediaSource || !sb) {
  18150. this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);
  18151. operationQueue.shiftAndExecuteNext(type);
  18152. return;
  18153. }
  18154. const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  18155. const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  18156. const removeStart = Math.max(0, startOffset);
  18157. const removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  18158. if (removeEnd > removeStart && (!sb.ending || sb.ended)) {
  18159. sb.ended = false;
  18160. this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);
  18161. sb.remove(removeStart, removeEnd);
  18162. } else {
  18163. // Cycle the queue
  18164. operationQueue.shiftAndExecuteNext(type);
  18165. }
  18166. }
  18167. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  18168. appendExecutor(data, type) {
  18169. const sb = this.sourceBuffer[type];
  18170. if (!sb) {
  18171. if (!this.pendingTracks[type]) {
  18172. throw new Error(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);
  18173. }
  18174. return;
  18175. }
  18176. sb.ended = false;
  18177. sb.appendBuffer(data);
  18178. }
  18179. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  18180. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  18181. // upon completion, since we already do it here
  18182. blockBuffers(onUnblocked, buffers = this.getSourceBufferTypes()) {
  18183. if (!buffers.length) {
  18184. this.log('Blocking operation requested, but no SourceBuffers exist');
  18185. Promise.resolve().then(onUnblocked);
  18186. return;
  18187. }
  18188. const {
  18189. operationQueue
  18190. } = this;
  18191. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  18192. const blockingOperations = buffers.map(type => operationQueue.appendBlocker(type));
  18193. Promise.all(blockingOperations).then(() => {
  18194. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  18195. onUnblocked();
  18196. buffers.forEach(type => {
  18197. const sb = this.sourceBuffer[type];
  18198. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  18199. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  18200. // While this is a workaround, it's probably useful to have around
  18201. if (!(sb != null && sb.updating)) {
  18202. operationQueue.shiftAndExecuteNext(type);
  18203. }
  18204. });
  18205. });
  18206. }
  18207. getSourceBufferTypes() {
  18208. return Object.keys(this.sourceBuffer);
  18209. }
  18210. addBufferListener(type, event, fn) {
  18211. const buffer = this.sourceBuffer[type];
  18212. if (!buffer) {
  18213. return;
  18214. }
  18215. const listener = fn.bind(this, type);
  18216. this.listeners[type].push({
  18217. event,
  18218. listener
  18219. });
  18220. buffer.addEventListener(event, listener);
  18221. }
  18222. removeBufferListeners(type) {
  18223. const buffer = this.sourceBuffer[type];
  18224. if (!buffer) {
  18225. return;
  18226. }
  18227. this.listeners[type].forEach(l => {
  18228. buffer.removeEventListener(l.event, l.listener);
  18229. });
  18230. }
  18231. }
  18232. function removeSourceChildren(node) {
  18233. const sourceChildren = node.querySelectorAll('source');
  18234. [].slice.call(sourceChildren).forEach(source => {
  18235. node.removeChild(source);
  18236. });
  18237. }
  18238. function addSource(media, url) {
  18239. const source = self.document.createElement('source');
  18240. source.type = 'video/mp4';
  18241. source.src = url;
  18242. media.appendChild(source);
  18243. }
  18244. /**
  18245. *
  18246. * This code was ported from the dash.js project at:
  18247. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  18248. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  18249. *
  18250. * The original copyright appears below:
  18251. *
  18252. * The copyright in this software is being made available under the BSD License,
  18253. * included below. This software may be subject to other third party and contributor
  18254. * rights, including patent rights, and no such rights are granted under this license.
  18255. *
  18256. * Copyright (c) 2015-2016, DASH Industry Forum.
  18257. * All rights reserved.
  18258. *
  18259. * Redistribution and use in source and binary forms, with or without modification,
  18260. * are permitted provided that the following conditions are met:
  18261. * 1. Redistributions of source code must retain the above copyright notice, this
  18262. * list of conditions and the following disclaimer.
  18263. * * Redistributions in binary form must reproduce the above copyright notice,
  18264. * this list of conditions and the following disclaimer in the documentation and/or
  18265. * other materials provided with the distribution.
  18266. * 2. Neither the name of Dash Industry Forum nor the names of its
  18267. * contributors may be used to endorse or promote products derived from this software
  18268. * without specific prior written permission.
  18269. *
  18270. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  18271. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18272. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18273. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  18274. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  18275. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18276. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  18277. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  18278. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  18279. * POSSIBILITY OF SUCH DAMAGE.
  18280. */
  18281. /**
  18282. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  18283. */
  18284. const specialCea608CharsCodes = {
  18285. 0x2a: 0xe1,
  18286. // lowercase a, acute accent
  18287. 0x5c: 0xe9,
  18288. // lowercase e, acute accent
  18289. 0x5e: 0xed,
  18290. // lowercase i, acute accent
  18291. 0x5f: 0xf3,
  18292. // lowercase o, acute accent
  18293. 0x60: 0xfa,
  18294. // lowercase u, acute accent
  18295. 0x7b: 0xe7,
  18296. // lowercase c with cedilla
  18297. 0x7c: 0xf7,
  18298. // division symbol
  18299. 0x7d: 0xd1,
  18300. // uppercase N tilde
  18301. 0x7e: 0xf1,
  18302. // lowercase n tilde
  18303. 0x7f: 0x2588,
  18304. // Full block
  18305. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18306. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  18307. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  18308. 0x80: 0xae,
  18309. // Registered symbol (R)
  18310. 0x81: 0xb0,
  18311. // degree sign
  18312. 0x82: 0xbd,
  18313. // 1/2 symbol
  18314. 0x83: 0xbf,
  18315. // Inverted (open) question mark
  18316. 0x84: 0x2122,
  18317. // Trademark symbol (TM)
  18318. 0x85: 0xa2,
  18319. // Cents symbol
  18320. 0x86: 0xa3,
  18321. // Pounds sterling
  18322. 0x87: 0x266a,
  18323. // Music 8'th note
  18324. 0x88: 0xe0,
  18325. // lowercase a, grave accent
  18326. 0x89: 0x20,
  18327. // transparent space (regular)
  18328. 0x8a: 0xe8,
  18329. // lowercase e, grave accent
  18330. 0x8b: 0xe2,
  18331. // lowercase a, circumflex accent
  18332. 0x8c: 0xea,
  18333. // lowercase e, circumflex accent
  18334. 0x8d: 0xee,
  18335. // lowercase i, circumflex accent
  18336. 0x8e: 0xf4,
  18337. // lowercase o, circumflex accent
  18338. 0x8f: 0xfb,
  18339. // lowercase u, circumflex accent
  18340. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18341. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  18342. 0x90: 0xc1,
  18343. // capital letter A with acute
  18344. 0x91: 0xc9,
  18345. // capital letter E with acute
  18346. 0x92: 0xd3,
  18347. // capital letter O with acute
  18348. 0x93: 0xda,
  18349. // capital letter U with acute
  18350. 0x94: 0xdc,
  18351. // capital letter U with diaresis
  18352. 0x95: 0xfc,
  18353. // lowercase letter U with diaeresis
  18354. 0x96: 0x2018,
  18355. // opening single quote
  18356. 0x97: 0xa1,
  18357. // inverted exclamation mark
  18358. 0x98: 0x2a,
  18359. // asterisk
  18360. 0x99: 0x2019,
  18361. // closing single quote
  18362. 0x9a: 0x2501,
  18363. // box drawings heavy horizontal
  18364. 0x9b: 0xa9,
  18365. // copyright sign
  18366. 0x9c: 0x2120,
  18367. // Service mark
  18368. 0x9d: 0x2022,
  18369. // (round) bullet
  18370. 0x9e: 0x201c,
  18371. // Left double quotation mark
  18372. 0x9f: 0x201d,
  18373. // Right double quotation mark
  18374. 0xa0: 0xc0,
  18375. // uppercase A, grave accent
  18376. 0xa1: 0xc2,
  18377. // uppercase A, circumflex
  18378. 0xa2: 0xc7,
  18379. // uppercase C with cedilla
  18380. 0xa3: 0xc8,
  18381. // uppercase E, grave accent
  18382. 0xa4: 0xca,
  18383. // uppercase E, circumflex
  18384. 0xa5: 0xcb,
  18385. // capital letter E with diaresis
  18386. 0xa6: 0xeb,
  18387. // lowercase letter e with diaresis
  18388. 0xa7: 0xce,
  18389. // uppercase I, circumflex
  18390. 0xa8: 0xcf,
  18391. // uppercase I, with diaresis
  18392. 0xa9: 0xef,
  18393. // lowercase i, with diaresis
  18394. 0xaa: 0xd4,
  18395. // uppercase O, circumflex
  18396. 0xab: 0xd9,
  18397. // uppercase U, grave accent
  18398. 0xac: 0xf9,
  18399. // lowercase u, grave accent
  18400. 0xad: 0xdb,
  18401. // uppercase U, circumflex
  18402. 0xae: 0xab,
  18403. // left-pointing double angle quotation mark
  18404. 0xaf: 0xbb,
  18405. // right-pointing double angle quotation mark
  18406. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  18407. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  18408. 0xb0: 0xc3,
  18409. // Uppercase A, tilde
  18410. 0xb1: 0xe3,
  18411. // Lowercase a, tilde
  18412. 0xb2: 0xcd,
  18413. // Uppercase I, acute accent
  18414. 0xb3: 0xcc,
  18415. // Uppercase I, grave accent
  18416. 0xb4: 0xec,
  18417. // Lowercase i, grave accent
  18418. 0xb5: 0xd2,
  18419. // Uppercase O, grave accent
  18420. 0xb6: 0xf2,
  18421. // Lowercase o, grave accent
  18422. 0xb7: 0xd5,
  18423. // Uppercase O, tilde
  18424. 0xb8: 0xf5,
  18425. // Lowercase o, tilde
  18426. 0xb9: 0x7b,
  18427. // Open curly brace
  18428. 0xba: 0x7d,
  18429. // Closing curly brace
  18430. 0xbb: 0x5c,
  18431. // Backslash
  18432. 0xbc: 0x5e,
  18433. // Caret
  18434. 0xbd: 0x5f,
  18435. // Underscore
  18436. 0xbe: 0x7c,
  18437. // Pipe (vertical line)
  18438. 0xbf: 0x223c,
  18439. // Tilde operator
  18440. 0xc0: 0xc4,
  18441. // Uppercase A, umlaut
  18442. 0xc1: 0xe4,
  18443. // Lowercase A, umlaut
  18444. 0xc2: 0xd6,
  18445. // Uppercase O, umlaut
  18446. 0xc3: 0xf6,
  18447. // Lowercase o, umlaut
  18448. 0xc4: 0xdf,
  18449. // Esszett (sharp S)
  18450. 0xc5: 0xa5,
  18451. // Yen symbol
  18452. 0xc6: 0xa4,
  18453. // Generic currency sign
  18454. 0xc7: 0x2503,
  18455. // Box drawings heavy vertical
  18456. 0xc8: 0xc5,
  18457. // Uppercase A, ring
  18458. 0xc9: 0xe5,
  18459. // Lowercase A, ring
  18460. 0xca: 0xd8,
  18461. // Uppercase O, stroke
  18462. 0xcb: 0xf8,
  18463. // Lowercase o, strok
  18464. 0xcc: 0x250f,
  18465. // Box drawings heavy down and right
  18466. 0xcd: 0x2513,
  18467. // Box drawings heavy down and left
  18468. 0xce: 0x2517,
  18469. // Box drawings heavy up and right
  18470. 0xcf: 0x251b // Box drawings heavy up and left
  18471. };
  18472. /**
  18473. * Utils
  18474. */
  18475. const getCharForByte = byte => String.fromCharCode(specialCea608CharsCodes[byte] || byte);
  18476. const NR_ROWS = 15;
  18477. const NR_COLS = 100;
  18478. // Tables to look up row from PAC data
  18479. const rowsLowCh1 = {
  18480. 0x11: 1,
  18481. 0x12: 3,
  18482. 0x15: 5,
  18483. 0x16: 7,
  18484. 0x17: 9,
  18485. 0x10: 11,
  18486. 0x13: 12,
  18487. 0x14: 14
  18488. };
  18489. const rowsHighCh1 = {
  18490. 0x11: 2,
  18491. 0x12: 4,
  18492. 0x15: 6,
  18493. 0x16: 8,
  18494. 0x17: 10,
  18495. 0x13: 13,
  18496. 0x14: 15
  18497. };
  18498. const rowsLowCh2 = {
  18499. 0x19: 1,
  18500. 0x1a: 3,
  18501. 0x1d: 5,
  18502. 0x1e: 7,
  18503. 0x1f: 9,
  18504. 0x18: 11,
  18505. 0x1b: 12,
  18506. 0x1c: 14
  18507. };
  18508. const rowsHighCh2 = {
  18509. 0x19: 2,
  18510. 0x1a: 4,
  18511. 0x1d: 6,
  18512. 0x1e: 8,
  18513. 0x1f: 10,
  18514. 0x1b: 13,
  18515. 0x1c: 15
  18516. };
  18517. const backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  18518. class CaptionsLogger {
  18519. constructor() {
  18520. this.time = null;
  18521. this.verboseLevel = 0;
  18522. }
  18523. log(severity, msg) {
  18524. if (this.verboseLevel >= severity) {
  18525. const m = typeof msg === 'function' ? msg() : msg;
  18526. logger.log(`${this.time} [${severity}] ${m}`);
  18527. }
  18528. }
  18529. }
  18530. const numArrayToHexArray = function numArrayToHexArray(numArray) {
  18531. const hexArray = [];
  18532. for (let j = 0; j < numArray.length; j++) {
  18533. hexArray.push(numArray[j].toString(16));
  18534. }
  18535. return hexArray;
  18536. };
  18537. class PenState {
  18538. constructor() {
  18539. this.foreground = 'white';
  18540. this.underline = false;
  18541. this.italics = false;
  18542. this.background = 'black';
  18543. this.flash = false;
  18544. }
  18545. reset() {
  18546. this.foreground = 'white';
  18547. this.underline = false;
  18548. this.italics = false;
  18549. this.background = 'black';
  18550. this.flash = false;
  18551. }
  18552. setStyles(styles) {
  18553. const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  18554. for (let i = 0; i < attribs.length; i++) {
  18555. const style = attribs[i];
  18556. if (styles.hasOwnProperty(style)) {
  18557. this[style] = styles[style];
  18558. }
  18559. }
  18560. }
  18561. isDefault() {
  18562. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  18563. }
  18564. equals(other) {
  18565. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  18566. }
  18567. copy(newPenState) {
  18568. this.foreground = newPenState.foreground;
  18569. this.underline = newPenState.underline;
  18570. this.italics = newPenState.italics;
  18571. this.background = newPenState.background;
  18572. this.flash = newPenState.flash;
  18573. }
  18574. toString() {
  18575. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  18576. }
  18577. }
  18578. /**
  18579. * Unicode character with styling and background.
  18580. * @constructor
  18581. */
  18582. class StyledUnicodeChar {
  18583. constructor() {
  18584. this.uchar = ' ';
  18585. this.penState = new PenState();
  18586. }
  18587. reset() {
  18588. this.uchar = ' ';
  18589. this.penState.reset();
  18590. }
  18591. setChar(uchar, newPenState) {
  18592. this.uchar = uchar;
  18593. this.penState.copy(newPenState);
  18594. }
  18595. setPenState(newPenState) {
  18596. this.penState.copy(newPenState);
  18597. }
  18598. equals(other) {
  18599. return this.uchar === other.uchar && this.penState.equals(other.penState);
  18600. }
  18601. copy(newChar) {
  18602. this.uchar = newChar.uchar;
  18603. this.penState.copy(newChar.penState);
  18604. }
  18605. isEmpty() {
  18606. return this.uchar === ' ' && this.penState.isDefault();
  18607. }
  18608. }
  18609. /**
  18610. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  18611. * @constructor
  18612. */
  18613. class Row {
  18614. constructor(logger) {
  18615. this.chars = [];
  18616. this.pos = 0;
  18617. this.currPenState = new PenState();
  18618. this.cueStartTime = null;
  18619. this.logger = void 0;
  18620. for (let i = 0; i < NR_COLS; i++) {
  18621. this.chars.push(new StyledUnicodeChar());
  18622. }
  18623. this.logger = logger;
  18624. }
  18625. equals(other) {
  18626. for (let i = 0; i < NR_COLS; i++) {
  18627. if (!this.chars[i].equals(other.chars[i])) {
  18628. return false;
  18629. }
  18630. }
  18631. return true;
  18632. }
  18633. copy(other) {
  18634. for (let i = 0; i < NR_COLS; i++) {
  18635. this.chars[i].copy(other.chars[i]);
  18636. }
  18637. }
  18638. isEmpty() {
  18639. let empty = true;
  18640. for (let i = 0; i < NR_COLS; i++) {
  18641. if (!this.chars[i].isEmpty()) {
  18642. empty = false;
  18643. break;
  18644. }
  18645. }
  18646. return empty;
  18647. }
  18648. /**
  18649. * Set the cursor to a valid column.
  18650. */
  18651. setCursor(absPos) {
  18652. if (this.pos !== absPos) {
  18653. this.pos = absPos;
  18654. }
  18655. if (this.pos < 0) {
  18656. this.logger.log(3, 'Negative cursor position ' + this.pos);
  18657. this.pos = 0;
  18658. } else if (this.pos > NR_COLS) {
  18659. this.logger.log(3, 'Too large cursor position ' + this.pos);
  18660. this.pos = NR_COLS;
  18661. }
  18662. }
  18663. /**
  18664. * Move the cursor relative to current position.
  18665. */
  18666. moveCursor(relPos) {
  18667. const newPos = this.pos + relPos;
  18668. if (relPos > 1) {
  18669. for (let i = this.pos + 1; i < newPos + 1; i++) {
  18670. this.chars[i].setPenState(this.currPenState);
  18671. }
  18672. }
  18673. this.setCursor(newPos);
  18674. }
  18675. /**
  18676. * Backspace, move one step back and clear character.
  18677. */
  18678. backSpace() {
  18679. this.moveCursor(-1);
  18680. this.chars[this.pos].setChar(' ', this.currPenState);
  18681. }
  18682. insertChar(byte) {
  18683. if (byte >= 0x90) {
  18684. // Extended char
  18685. this.backSpace();
  18686. }
  18687. const char = getCharForByte(byte);
  18688. if (this.pos >= NR_COLS) {
  18689. this.logger.log(0, () => 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  18690. return;
  18691. }
  18692. this.chars[this.pos].setChar(char, this.currPenState);
  18693. this.moveCursor(1);
  18694. }
  18695. clearFromPos(startPos) {
  18696. let i;
  18697. for (i = startPos; i < NR_COLS; i++) {
  18698. this.chars[i].reset();
  18699. }
  18700. }
  18701. clear() {
  18702. this.clearFromPos(0);
  18703. this.pos = 0;
  18704. this.currPenState.reset();
  18705. }
  18706. clearToEndOfRow() {
  18707. this.clearFromPos(this.pos);
  18708. }
  18709. getTextString() {
  18710. const chars = [];
  18711. let empty = true;
  18712. for (let i = 0; i < NR_COLS; i++) {
  18713. const char = this.chars[i].uchar;
  18714. if (char !== ' ') {
  18715. empty = false;
  18716. }
  18717. chars.push(char);
  18718. }
  18719. if (empty) {
  18720. return '';
  18721. } else {
  18722. return chars.join('');
  18723. }
  18724. }
  18725. setPenStyles(styles) {
  18726. this.currPenState.setStyles(styles);
  18727. const currChar = this.chars[this.pos];
  18728. currChar.setPenState(this.currPenState);
  18729. }
  18730. }
  18731. /**
  18732. * Keep a CEA-608 screen of 32x15 styled characters
  18733. * @constructor
  18734. */
  18735. class CaptionScreen {
  18736. constructor(logger) {
  18737. this.rows = [];
  18738. this.currRow = NR_ROWS - 1;
  18739. this.nrRollUpRows = null;
  18740. this.lastOutputScreen = null;
  18741. this.logger = void 0;
  18742. for (let i = 0; i < NR_ROWS; i++) {
  18743. this.rows.push(new Row(logger));
  18744. }
  18745. this.logger = logger;
  18746. }
  18747. reset() {
  18748. for (let i = 0; i < NR_ROWS; i++) {
  18749. this.rows[i].clear();
  18750. }
  18751. this.currRow = NR_ROWS - 1;
  18752. }
  18753. equals(other) {
  18754. let equal = true;
  18755. for (let i = 0; i < NR_ROWS; i++) {
  18756. if (!this.rows[i].equals(other.rows[i])) {
  18757. equal = false;
  18758. break;
  18759. }
  18760. }
  18761. return equal;
  18762. }
  18763. copy(other) {
  18764. for (let i = 0; i < NR_ROWS; i++) {
  18765. this.rows[i].copy(other.rows[i]);
  18766. }
  18767. }
  18768. isEmpty() {
  18769. let empty = true;
  18770. for (let i = 0; i < NR_ROWS; i++) {
  18771. if (!this.rows[i].isEmpty()) {
  18772. empty = false;
  18773. break;
  18774. }
  18775. }
  18776. return empty;
  18777. }
  18778. backSpace() {
  18779. const row = this.rows[this.currRow];
  18780. row.backSpace();
  18781. }
  18782. clearToEndOfRow() {
  18783. const row = this.rows[this.currRow];
  18784. row.clearToEndOfRow();
  18785. }
  18786. /**
  18787. * Insert a character (without styling) in the current row.
  18788. */
  18789. insertChar(char) {
  18790. const row = this.rows[this.currRow];
  18791. row.insertChar(char);
  18792. }
  18793. setPen(styles) {
  18794. const row = this.rows[this.currRow];
  18795. row.setPenStyles(styles);
  18796. }
  18797. moveCursor(relPos) {
  18798. const row = this.rows[this.currRow];
  18799. row.moveCursor(relPos);
  18800. }
  18801. setCursor(absPos) {
  18802. this.logger.log(2, 'setCursor: ' + absPos);
  18803. const row = this.rows[this.currRow];
  18804. row.setCursor(absPos);
  18805. }
  18806. setPAC(pacData) {
  18807. this.logger.log(2, () => 'pacData = ' + JSON.stringify(pacData));
  18808. let newRow = pacData.row - 1;
  18809. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  18810. newRow = this.nrRollUpRows - 1;
  18811. }
  18812. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  18813. if (this.nrRollUpRows && this.currRow !== newRow) {
  18814. // clear all rows first
  18815. for (let i = 0; i < NR_ROWS; i++) {
  18816. this.rows[i].clear();
  18817. }
  18818. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  18819. // topRowIndex - the start of rows to copy (inclusive index)
  18820. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  18821. // We only copy if the last position was already shown.
  18822. // We use the cueStartTime value to check this.
  18823. const lastOutputScreen = this.lastOutputScreen;
  18824. if (lastOutputScreen) {
  18825. const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  18826. const time = this.logger.time;
  18827. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  18828. for (let i = 0; i < this.nrRollUpRows; i++) {
  18829. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  18830. }
  18831. }
  18832. }
  18833. }
  18834. this.currRow = newRow;
  18835. const row = this.rows[this.currRow];
  18836. if (pacData.indent !== null) {
  18837. const indent = pacData.indent;
  18838. const prevPos = Math.max(indent - 1, 0);
  18839. row.setCursor(pacData.indent);
  18840. pacData.color = row.chars[prevPos].penState.foreground;
  18841. }
  18842. const styles = {
  18843. foreground: pacData.color,
  18844. underline: pacData.underline,
  18845. italics: pacData.italics,
  18846. background: 'black',
  18847. flash: false
  18848. };
  18849. this.setPen(styles);
  18850. }
  18851. /**
  18852. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  18853. */
  18854. setBkgData(bkgData) {
  18855. this.logger.log(2, () => 'bkgData = ' + JSON.stringify(bkgData));
  18856. this.backSpace();
  18857. this.setPen(bkgData);
  18858. this.insertChar(0x20); // Space
  18859. }
  18860. setRollUpRows(nrRows) {
  18861. this.nrRollUpRows = nrRows;
  18862. }
  18863. rollUp() {
  18864. if (this.nrRollUpRows === null) {
  18865. this.logger.log(3, 'roll_up but nrRollUpRows not set yet');
  18866. return; // Not properly setup
  18867. }
  18868. this.logger.log(1, () => this.getDisplayText());
  18869. const topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  18870. const topRow = this.rows.splice(topRowIndex, 1)[0];
  18871. topRow.clear();
  18872. this.rows.splice(this.currRow, 0, topRow);
  18873. this.logger.log(2, 'Rolling up');
  18874. // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
  18875. }
  18876. /**
  18877. * Get all non-empty rows with as unicode text.
  18878. */
  18879. getDisplayText(asOneRow) {
  18880. asOneRow = asOneRow || false;
  18881. const displayText = [];
  18882. let text = '';
  18883. let rowNr = -1;
  18884. for (let i = 0; i < NR_ROWS; i++) {
  18885. const rowText = this.rows[i].getTextString();
  18886. if (rowText) {
  18887. rowNr = i + 1;
  18888. if (asOneRow) {
  18889. displayText.push('Row ' + rowNr + ": '" + rowText + "'");
  18890. } else {
  18891. displayText.push(rowText.trim());
  18892. }
  18893. }
  18894. }
  18895. if (displayText.length > 0) {
  18896. if (asOneRow) {
  18897. text = '[' + displayText.join(' | ') + ']';
  18898. } else {
  18899. text = displayText.join('\n');
  18900. }
  18901. }
  18902. return text;
  18903. }
  18904. getTextAndFormat() {
  18905. return this.rows;
  18906. }
  18907. }
  18908. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  18909. class Cea608Channel {
  18910. constructor(channelNumber, outputFilter, logger) {
  18911. this.chNr = void 0;
  18912. this.outputFilter = void 0;
  18913. this.mode = void 0;
  18914. this.verbose = void 0;
  18915. this.displayedMemory = void 0;
  18916. this.nonDisplayedMemory = void 0;
  18917. this.lastOutputScreen = void 0;
  18918. this.currRollUpRow = void 0;
  18919. this.writeScreen = void 0;
  18920. this.cueStartTime = void 0;
  18921. this.logger = void 0;
  18922. this.chNr = channelNumber;
  18923. this.outputFilter = outputFilter;
  18924. this.mode = null;
  18925. this.verbose = 0;
  18926. this.displayedMemory = new CaptionScreen(logger);
  18927. this.nonDisplayedMemory = new CaptionScreen(logger);
  18928. this.lastOutputScreen = new CaptionScreen(logger);
  18929. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  18930. this.writeScreen = this.displayedMemory;
  18931. this.mode = null;
  18932. this.cueStartTime = null; // Keeps track of where a cue started.
  18933. this.logger = logger;
  18934. }
  18935. reset() {
  18936. this.mode = null;
  18937. this.displayedMemory.reset();
  18938. this.nonDisplayedMemory.reset();
  18939. this.lastOutputScreen.reset();
  18940. this.outputFilter.reset();
  18941. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  18942. this.writeScreen = this.displayedMemory;
  18943. this.mode = null;
  18944. this.cueStartTime = null;
  18945. }
  18946. getHandler() {
  18947. return this.outputFilter;
  18948. }
  18949. setHandler(newHandler) {
  18950. this.outputFilter = newHandler;
  18951. }
  18952. setPAC(pacData) {
  18953. this.writeScreen.setPAC(pacData);
  18954. }
  18955. setBkgData(bkgData) {
  18956. this.writeScreen.setBkgData(bkgData);
  18957. }
  18958. setMode(newMode) {
  18959. if (newMode === this.mode) {
  18960. return;
  18961. }
  18962. this.mode = newMode;
  18963. this.logger.log(2, () => 'MODE=' + newMode);
  18964. if (this.mode === 'MODE_POP-ON') {
  18965. this.writeScreen = this.nonDisplayedMemory;
  18966. } else {
  18967. this.writeScreen = this.displayedMemory;
  18968. this.writeScreen.reset();
  18969. }
  18970. if (this.mode !== 'MODE_ROLL-UP') {
  18971. this.displayedMemory.nrRollUpRows = null;
  18972. this.nonDisplayedMemory.nrRollUpRows = null;
  18973. }
  18974. this.mode = newMode;
  18975. }
  18976. insertChars(chars) {
  18977. for (let i = 0; i < chars.length; i++) {
  18978. this.writeScreen.insertChar(chars[i]);
  18979. }
  18980. const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  18981. this.logger.log(2, () => screen + ': ' + this.writeScreen.getDisplayText(true));
  18982. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  18983. this.logger.log(1, () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  18984. this.outputDataUpdate();
  18985. }
  18986. }
  18987. ccRCL() {
  18988. // Resume Caption Loading (switch mode to Pop On)
  18989. this.logger.log(2, 'RCL - Resume Caption Loading');
  18990. this.setMode('MODE_POP-ON');
  18991. }
  18992. ccBS() {
  18993. // BackSpace
  18994. this.logger.log(2, 'BS - BackSpace');
  18995. if (this.mode === 'MODE_TEXT') {
  18996. return;
  18997. }
  18998. this.writeScreen.backSpace();
  18999. if (this.writeScreen === this.displayedMemory) {
  19000. this.outputDataUpdate();
  19001. }
  19002. }
  19003. ccAOF() {
  19004. // Reserved (formerly Alarm Off)
  19005. }
  19006. ccAON() {
  19007. // Reserved (formerly Alarm On)
  19008. }
  19009. ccDER() {
  19010. // Delete to End of Row
  19011. this.logger.log(2, 'DER- Delete to End of Row');
  19012. this.writeScreen.clearToEndOfRow();
  19013. this.outputDataUpdate();
  19014. }
  19015. ccRU(nrRows) {
  19016. // Roll-Up Captions-2,3,or 4 Rows
  19017. this.logger.log(2, 'RU(' + nrRows + ') - Roll Up');
  19018. this.writeScreen = this.displayedMemory;
  19019. this.setMode('MODE_ROLL-UP');
  19020. this.writeScreen.setRollUpRows(nrRows);
  19021. }
  19022. ccFON() {
  19023. // Flash On
  19024. this.logger.log(2, 'FON - Flash On');
  19025. this.writeScreen.setPen({
  19026. flash: true
  19027. });
  19028. }
  19029. ccRDC() {
  19030. // Resume Direct Captioning (switch mode to PaintOn)
  19031. this.logger.log(2, 'RDC - Resume Direct Captioning');
  19032. this.setMode('MODE_PAINT-ON');
  19033. }
  19034. ccTR() {
  19035. // Text Restart in text mode (not supported, however)
  19036. this.logger.log(2, 'TR');
  19037. this.setMode('MODE_TEXT');
  19038. }
  19039. ccRTD() {
  19040. // Resume Text Display in Text mode (not supported, however)
  19041. this.logger.log(2, 'RTD');
  19042. this.setMode('MODE_TEXT');
  19043. }
  19044. ccEDM() {
  19045. // Erase Displayed Memory
  19046. this.logger.log(2, 'EDM - Erase Displayed Memory');
  19047. this.displayedMemory.reset();
  19048. this.outputDataUpdate(true);
  19049. }
  19050. ccCR() {
  19051. // Carriage Return
  19052. this.logger.log(2, 'CR - Carriage Return');
  19053. this.writeScreen.rollUp();
  19054. this.outputDataUpdate(true);
  19055. }
  19056. ccENM() {
  19057. // Erase Non-Displayed Memory
  19058. this.logger.log(2, 'ENM - Erase Non-displayed Memory');
  19059. this.nonDisplayedMemory.reset();
  19060. }
  19061. ccEOC() {
  19062. // End of Caption (Flip Memories)
  19063. this.logger.log(2, 'EOC - End Of Caption');
  19064. if (this.mode === 'MODE_POP-ON') {
  19065. const tmp = this.displayedMemory;
  19066. this.displayedMemory = this.nonDisplayedMemory;
  19067. this.nonDisplayedMemory = tmp;
  19068. this.writeScreen = this.nonDisplayedMemory;
  19069. this.logger.log(1, () => 'DISP: ' + this.displayedMemory.getDisplayText());
  19070. }
  19071. this.outputDataUpdate(true);
  19072. }
  19073. ccTO(nrCols) {
  19074. // Tab Offset 1,2, or 3 columns
  19075. this.logger.log(2, 'TO(' + nrCols + ') - Tab Offset');
  19076. this.writeScreen.moveCursor(nrCols);
  19077. }
  19078. ccMIDROW(secondByte) {
  19079. // Parse MIDROW command
  19080. const styles = {
  19081. flash: false
  19082. };
  19083. styles.underline = secondByte % 2 === 1;
  19084. styles.italics = secondByte >= 0x2e;
  19085. if (!styles.italics) {
  19086. const colorIndex = Math.floor(secondByte / 2) - 0x10;
  19087. const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  19088. styles.foreground = colors[colorIndex];
  19089. } else {
  19090. styles.foreground = 'white';
  19091. }
  19092. this.logger.log(2, 'MIDROW: ' + JSON.stringify(styles));
  19093. this.writeScreen.setPen(styles);
  19094. }
  19095. outputDataUpdate(dispatch = false) {
  19096. const time = this.logger.time;
  19097. if (time === null) {
  19098. return;
  19099. }
  19100. if (this.outputFilter) {
  19101. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  19102. // Start of a new cue
  19103. this.cueStartTime = time;
  19104. } else {
  19105. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  19106. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  19107. if (dispatch && this.outputFilter.dispatchCue) {
  19108. this.outputFilter.dispatchCue();
  19109. }
  19110. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  19111. }
  19112. }
  19113. this.lastOutputScreen.copy(this.displayedMemory);
  19114. }
  19115. }
  19116. cueSplitAtTime(t) {
  19117. if (this.outputFilter) {
  19118. if (!this.displayedMemory.isEmpty()) {
  19119. if (this.outputFilter.newCue) {
  19120. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  19121. }
  19122. this.cueStartTime = t;
  19123. }
  19124. }
  19125. }
  19126. }
  19127. // Will be 1 or 2 when parsing captions
  19128. class Cea608Parser {
  19129. constructor(field, out1, out2) {
  19130. this.channels = void 0;
  19131. this.currentChannel = 0;
  19132. this.cmdHistory = createCmdHistory();
  19133. this.logger = void 0;
  19134. const logger = this.logger = new CaptionsLogger();
  19135. this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
  19136. }
  19137. getHandler(channel) {
  19138. return this.channels[channel].getHandler();
  19139. }
  19140. setHandler(channel, newHandler) {
  19141. this.channels[channel].setHandler(newHandler);
  19142. }
  19143. /**
  19144. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  19145. */
  19146. addData(time, byteList) {
  19147. this.logger.time = time;
  19148. for (let i = 0; i < byteList.length; i += 2) {
  19149. const a = byteList[i] & 0x7f;
  19150. const b = byteList[i + 1] & 0x7f;
  19151. let cmdFound = false;
  19152. let charsFound = null;
  19153. if (a === 0 && b === 0) {
  19154. continue;
  19155. } else {
  19156. this.logger.log(3, () => '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  19157. }
  19158. const cmdHistory = this.cmdHistory;
  19159. const isControlCode = a >= 0x10 && a <= 0x1f;
  19160. if (isControlCode) {
  19161. // Skip redundant control codes
  19162. if (hasCmdRepeated(a, b, cmdHistory)) {
  19163. setLastCmd(null, null, cmdHistory);
  19164. this.logger.log(3, () => 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  19165. continue;
  19166. }
  19167. setLastCmd(a, b, this.cmdHistory);
  19168. cmdFound = this.parseCmd(a, b);
  19169. if (!cmdFound) {
  19170. cmdFound = this.parseMidrow(a, b);
  19171. }
  19172. if (!cmdFound) {
  19173. cmdFound = this.parsePAC(a, b);
  19174. }
  19175. if (!cmdFound) {
  19176. cmdFound = this.parseBackgroundAttributes(a, b);
  19177. }
  19178. } else {
  19179. setLastCmd(null, null, cmdHistory);
  19180. }
  19181. if (!cmdFound) {
  19182. charsFound = this.parseChars(a, b);
  19183. if (charsFound) {
  19184. const currChNr = this.currentChannel;
  19185. if (currChNr && currChNr > 0) {
  19186. const channel = this.channels[currChNr];
  19187. channel.insertChars(charsFound);
  19188. } else {
  19189. this.logger.log(2, 'No channel found yet. TEXT-MODE?');
  19190. }
  19191. }
  19192. }
  19193. if (!cmdFound && !charsFound) {
  19194. this.logger.log(2, () => "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  19195. }
  19196. }
  19197. }
  19198. /**
  19199. * Parse Command.
  19200. * @returns True if a command was found
  19201. */
  19202. parseCmd(a, b) {
  19203. const cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
  19204. const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
  19205. if (!(cond1 || cond2)) {
  19206. return false;
  19207. }
  19208. const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
  19209. const channel = this.channels[chNr];
  19210. if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
  19211. if (b === 0x20) {
  19212. channel.ccRCL();
  19213. } else if (b === 0x21) {
  19214. channel.ccBS();
  19215. } else if (b === 0x22) {
  19216. channel.ccAOF();
  19217. } else if (b === 0x23) {
  19218. channel.ccAON();
  19219. } else if (b === 0x24) {
  19220. channel.ccDER();
  19221. } else if (b === 0x25) {
  19222. channel.ccRU(2);
  19223. } else if (b === 0x26) {
  19224. channel.ccRU(3);
  19225. } else if (b === 0x27) {
  19226. channel.ccRU(4);
  19227. } else if (b === 0x28) {
  19228. channel.ccFON();
  19229. } else if (b === 0x29) {
  19230. channel.ccRDC();
  19231. } else if (b === 0x2a) {
  19232. channel.ccTR();
  19233. } else if (b === 0x2b) {
  19234. channel.ccRTD();
  19235. } else if (b === 0x2c) {
  19236. channel.ccEDM();
  19237. } else if (b === 0x2d) {
  19238. channel.ccCR();
  19239. } else if (b === 0x2e) {
  19240. channel.ccENM();
  19241. } else if (b === 0x2f) {
  19242. channel.ccEOC();
  19243. }
  19244. } else {
  19245. // a == 0x17 || a == 0x1F
  19246. channel.ccTO(b - 0x20);
  19247. }
  19248. this.currentChannel = chNr;
  19249. return true;
  19250. }
  19251. /**
  19252. * Parse midrow styling command
  19253. */
  19254. parseMidrow(a, b) {
  19255. let chNr = 0;
  19256. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  19257. if (a === 0x11) {
  19258. chNr = 1;
  19259. } else {
  19260. chNr = 2;
  19261. }
  19262. if (chNr !== this.currentChannel) {
  19263. this.logger.log(0, 'Mismatch channel in midrow parsing');
  19264. return false;
  19265. }
  19266. const channel = this.channels[chNr];
  19267. if (!channel) {
  19268. return false;
  19269. }
  19270. channel.ccMIDROW(b);
  19271. this.logger.log(3, () => 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  19272. return true;
  19273. }
  19274. return false;
  19275. }
  19276. /**
  19277. * Parse Preable Access Codes (Table 53).
  19278. * @returns {Boolean} Tells if PAC found
  19279. */
  19280. parsePAC(a, b) {
  19281. let row;
  19282. const case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
  19283. const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
  19284. if (!(case1 || case2)) {
  19285. return false;
  19286. }
  19287. const chNr = a <= 0x17 ? 1 : 2;
  19288. if (b >= 0x40 && b <= 0x5f) {
  19289. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  19290. } else {
  19291. // 0x60 <= b <= 0x7F
  19292. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  19293. }
  19294. const channel = this.channels[chNr];
  19295. if (!channel) {
  19296. return false;
  19297. }
  19298. channel.setPAC(this.interpretPAC(row, b));
  19299. this.currentChannel = chNr;
  19300. return true;
  19301. }
  19302. /**
  19303. * Interpret the second byte of the pac, and return the information.
  19304. * @returns pacData with style parameters
  19305. */
  19306. interpretPAC(row, byte) {
  19307. let pacIndex;
  19308. const pacData = {
  19309. color: null,
  19310. italics: false,
  19311. indent: null,
  19312. underline: false,
  19313. row: row
  19314. };
  19315. if (byte > 0x5f) {
  19316. pacIndex = byte - 0x60;
  19317. } else {
  19318. pacIndex = byte - 0x40;
  19319. }
  19320. pacData.underline = (pacIndex & 1) === 1;
  19321. if (pacIndex <= 0xd) {
  19322. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  19323. } else if (pacIndex <= 0xf) {
  19324. pacData.italics = true;
  19325. pacData.color = 'white';
  19326. } else {
  19327. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  19328. }
  19329. return pacData; // Note that row has zero offset. The spec uses 1.
  19330. }
  19331. /**
  19332. * Parse characters.
  19333. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  19334. */
  19335. parseChars(a, b) {
  19336. let channelNr;
  19337. let charCodes = null;
  19338. let charCode1 = null;
  19339. if (a >= 0x19) {
  19340. channelNr = 2;
  19341. charCode1 = a - 8;
  19342. } else {
  19343. channelNr = 1;
  19344. charCode1 = a;
  19345. }
  19346. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  19347. // Special character
  19348. let oneCode;
  19349. if (charCode1 === 0x11) {
  19350. oneCode = b + 0x50;
  19351. } else if (charCode1 === 0x12) {
  19352. oneCode = b + 0x70;
  19353. } else {
  19354. oneCode = b + 0x90;
  19355. }
  19356. this.logger.log(2, () => "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
  19357. charCodes = [oneCode];
  19358. } else if (a >= 0x20 && a <= 0x7f) {
  19359. charCodes = b === 0 ? [a] : [a, b];
  19360. }
  19361. if (charCodes) {
  19362. this.logger.log(3, () => 'Char codes = ' + numArrayToHexArray(charCodes).join(','));
  19363. }
  19364. return charCodes;
  19365. }
  19366. /**
  19367. * Parse extended background attributes as well as new foreground color black.
  19368. * @returns True if background attributes are found
  19369. */
  19370. parseBackgroundAttributes(a, b) {
  19371. const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  19372. const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  19373. if (!(case1 || case2)) {
  19374. return false;
  19375. }
  19376. let index;
  19377. const bkgData = {};
  19378. if (a === 0x10 || a === 0x18) {
  19379. index = Math.floor((b - 0x20) / 2);
  19380. bkgData.background = backgroundColors[index];
  19381. if (b % 2 === 1) {
  19382. bkgData.background = bkgData.background + '_semi';
  19383. }
  19384. } else if (b === 0x2d) {
  19385. bkgData.background = 'transparent';
  19386. } else {
  19387. bkgData.foreground = 'black';
  19388. if (b === 0x2f) {
  19389. bkgData.underline = true;
  19390. }
  19391. }
  19392. const chNr = a <= 0x17 ? 1 : 2;
  19393. const channel = this.channels[chNr];
  19394. channel.setBkgData(bkgData);
  19395. return true;
  19396. }
  19397. /**
  19398. * Reset state of parser and its channels.
  19399. */
  19400. reset() {
  19401. for (let i = 0; i < Object.keys(this.channels).length; i++) {
  19402. const channel = this.channels[i];
  19403. if (channel) {
  19404. channel.reset();
  19405. }
  19406. }
  19407. setLastCmd(null, null, this.cmdHistory);
  19408. }
  19409. /**
  19410. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  19411. */
  19412. cueSplitAtTime(t) {
  19413. for (let i = 0; i < this.channels.length; i++) {
  19414. const channel = this.channels[i];
  19415. if (channel) {
  19416. channel.cueSplitAtTime(t);
  19417. }
  19418. }
  19419. }
  19420. }
  19421. function setLastCmd(a, b, cmdHistory) {
  19422. cmdHistory.a = a;
  19423. cmdHistory.b = b;
  19424. }
  19425. function hasCmdRepeated(a, b, cmdHistory) {
  19426. return cmdHistory.a === a && cmdHistory.b === b;
  19427. }
  19428. function createCmdHistory() {
  19429. return {
  19430. a: null,
  19431. b: null
  19432. };
  19433. }
  19434. class OutputFilter {
  19435. constructor(timelineController, trackName) {
  19436. this.timelineController = void 0;
  19437. this.cueRanges = [];
  19438. this.trackName = void 0;
  19439. this.startTime = null;
  19440. this.endTime = null;
  19441. this.screen = null;
  19442. this.timelineController = timelineController;
  19443. this.trackName = trackName;
  19444. }
  19445. dispatchCue() {
  19446. if (this.startTime === null) {
  19447. return;
  19448. }
  19449. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  19450. this.startTime = null;
  19451. }
  19452. newCue(startTime, endTime, screen) {
  19453. if (this.startTime === null || this.startTime > startTime) {
  19454. this.startTime = startTime;
  19455. }
  19456. this.endTime = endTime;
  19457. this.screen = screen;
  19458. this.timelineController.createCaptionsTrack(this.trackName);
  19459. }
  19460. reset() {
  19461. this.cueRanges = [];
  19462. this.startTime = null;
  19463. }
  19464. }
  19465. /**
  19466. * Copyright 2013 vtt.js Contributors
  19467. *
  19468. * Licensed under the Apache License, Version 2.0 (the 'License');
  19469. * you may not use this file except in compliance with the License.
  19470. * You may obtain a copy of the License at
  19471. *
  19472. * http://www.apache.org/licenses/LICENSE-2.0
  19473. *
  19474. * Unless required by applicable law or agreed to in writing, software
  19475. * distributed under the License is distributed on an 'AS IS' BASIS,
  19476. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19477. * See the License for the specific language governing permissions and
  19478. * limitations under the License.
  19479. */
  19480. var VTTCue = (function () {
  19481. if (optionalSelf != null && optionalSelf.VTTCue) {
  19482. return self.VTTCue;
  19483. }
  19484. const AllowedDirections = ['', 'lr', 'rl'];
  19485. const AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
  19486. function isAllowedValue(allowed, value) {
  19487. if (typeof value !== 'string') {
  19488. return false;
  19489. }
  19490. // necessary for assuring the generic conforms to the Array interface
  19491. if (!Array.isArray(allowed)) {
  19492. return false;
  19493. }
  19494. // reset the type so that the next narrowing works well
  19495. const lcValue = value.toLowerCase();
  19496. // use the allow list to narrow the type to a specific subset of strings
  19497. if (~allowed.indexOf(lcValue)) {
  19498. return lcValue;
  19499. }
  19500. return false;
  19501. }
  19502. function findDirectionSetting(value) {
  19503. return isAllowedValue(AllowedDirections, value);
  19504. }
  19505. function findAlignSetting(value) {
  19506. return isAllowedValue(AllowedAlignments, value);
  19507. }
  19508. function extend(obj, ...rest) {
  19509. let i = 1;
  19510. for (; i < arguments.length; i++) {
  19511. const cobj = arguments[i];
  19512. for (const p in cobj) {
  19513. obj[p] = cobj[p];
  19514. }
  19515. }
  19516. return obj;
  19517. }
  19518. function VTTCue(startTime, endTime, text) {
  19519. const cue = this;
  19520. const baseObj = {
  19521. enumerable: true
  19522. };
  19523. /**
  19524. * Shim implementation specific properties. These properties are not in
  19525. * the spec.
  19526. */
  19527. // Lets us know when the VTTCue's data has changed in such a way that we need
  19528. // to recompute its display state. This lets us compute its display state
  19529. // lazily.
  19530. cue.hasBeenReset = false;
  19531. /**
  19532. * VTTCue and TextTrackCue properties
  19533. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  19534. */
  19535. let _id = '';
  19536. let _pauseOnExit = false;
  19537. let _startTime = startTime;
  19538. let _endTime = endTime;
  19539. let _text = text;
  19540. let _region = null;
  19541. let _vertical = '';
  19542. let _snapToLines = true;
  19543. let _line = 'auto';
  19544. let _lineAlign = 'start';
  19545. let _position = 50;
  19546. let _positionAlign = 'middle';
  19547. let _size = 50;
  19548. let _align = 'middle';
  19549. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  19550. get: function () {
  19551. return _id;
  19552. },
  19553. set: function (value) {
  19554. _id = '' + value;
  19555. }
  19556. }));
  19557. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  19558. get: function () {
  19559. return _pauseOnExit;
  19560. },
  19561. set: function (value) {
  19562. _pauseOnExit = !!value;
  19563. }
  19564. }));
  19565. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  19566. get: function () {
  19567. return _startTime;
  19568. },
  19569. set: function (value) {
  19570. if (typeof value !== 'number') {
  19571. throw new TypeError('Start time must be set to a number.');
  19572. }
  19573. _startTime = value;
  19574. this.hasBeenReset = true;
  19575. }
  19576. }));
  19577. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  19578. get: function () {
  19579. return _endTime;
  19580. },
  19581. set: function (value) {
  19582. if (typeof value !== 'number') {
  19583. throw new TypeError('End time must be set to a number.');
  19584. }
  19585. _endTime = value;
  19586. this.hasBeenReset = true;
  19587. }
  19588. }));
  19589. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  19590. get: function () {
  19591. return _text;
  19592. },
  19593. set: function (value) {
  19594. _text = '' + value;
  19595. this.hasBeenReset = true;
  19596. }
  19597. }));
  19598. // todo: implement VTTRegion polyfill?
  19599. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  19600. get: function () {
  19601. return _region;
  19602. },
  19603. set: function (value) {
  19604. _region = value;
  19605. this.hasBeenReset = true;
  19606. }
  19607. }));
  19608. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  19609. get: function () {
  19610. return _vertical;
  19611. },
  19612. set: function (value) {
  19613. const setting = findDirectionSetting(value);
  19614. // Have to check for false because the setting an be an empty string.
  19615. if (setting === false) {
  19616. throw new SyntaxError('An invalid or illegal string was specified.');
  19617. }
  19618. _vertical = setting;
  19619. this.hasBeenReset = true;
  19620. }
  19621. }));
  19622. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  19623. get: function () {
  19624. return _snapToLines;
  19625. },
  19626. set: function (value) {
  19627. _snapToLines = !!value;
  19628. this.hasBeenReset = true;
  19629. }
  19630. }));
  19631. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  19632. get: function () {
  19633. return _line;
  19634. },
  19635. set: function (value) {
  19636. if (typeof value !== 'number' && value !== 'auto') {
  19637. throw new SyntaxError('An invalid number or illegal string was specified.');
  19638. }
  19639. _line = value;
  19640. this.hasBeenReset = true;
  19641. }
  19642. }));
  19643. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  19644. get: function () {
  19645. return _lineAlign;
  19646. },
  19647. set: function (value) {
  19648. const setting = findAlignSetting(value);
  19649. if (!setting) {
  19650. throw new SyntaxError('An invalid or illegal string was specified.');
  19651. }
  19652. _lineAlign = setting;
  19653. this.hasBeenReset = true;
  19654. }
  19655. }));
  19656. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  19657. get: function () {
  19658. return _position;
  19659. },
  19660. set: function (value) {
  19661. if (value < 0 || value > 100) {
  19662. throw new Error('Position must be between 0 and 100.');
  19663. }
  19664. _position = value;
  19665. this.hasBeenReset = true;
  19666. }
  19667. }));
  19668. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  19669. get: function () {
  19670. return _positionAlign;
  19671. },
  19672. set: function (value) {
  19673. const setting = findAlignSetting(value);
  19674. if (!setting) {
  19675. throw new SyntaxError('An invalid or illegal string was specified.');
  19676. }
  19677. _positionAlign = setting;
  19678. this.hasBeenReset = true;
  19679. }
  19680. }));
  19681. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  19682. get: function () {
  19683. return _size;
  19684. },
  19685. set: function (value) {
  19686. if (value < 0 || value > 100) {
  19687. throw new Error('Size must be between 0 and 100.');
  19688. }
  19689. _size = value;
  19690. this.hasBeenReset = true;
  19691. }
  19692. }));
  19693. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  19694. get: function () {
  19695. return _align;
  19696. },
  19697. set: function (value) {
  19698. const setting = findAlignSetting(value);
  19699. if (!setting) {
  19700. throw new SyntaxError('An invalid or illegal string was specified.');
  19701. }
  19702. _align = setting;
  19703. this.hasBeenReset = true;
  19704. }
  19705. }));
  19706. /**
  19707. * Other <track> spec defined properties
  19708. */
  19709. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  19710. cue.displayState = undefined;
  19711. }
  19712. /**
  19713. * VTTCue methods
  19714. */
  19715. VTTCue.prototype.getCueAsHTML = function () {
  19716. // Assume WebVTT.convertCueToDOMTree is on the global.
  19717. const WebVTT = self.WebVTT;
  19718. return WebVTT.convertCueToDOMTree(self, this.text);
  19719. };
  19720. // this is a polyfill hack
  19721. return VTTCue;
  19722. })();
  19723. /*
  19724. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
  19725. */
  19726. class StringDecoder {
  19727. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  19728. decode(data, options) {
  19729. if (!data) {
  19730. return '';
  19731. }
  19732. if (typeof data !== 'string') {
  19733. throw new Error('Error - expected string data.');
  19734. }
  19735. return decodeURIComponent(encodeURIComponent(data));
  19736. }
  19737. }
  19738. // Try to parse input as a time stamp.
  19739. function parseTimeStamp(input) {
  19740. function computeSeconds(h, m, s, f) {
  19741. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
  19742. }
  19743. const m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  19744. if (!m) {
  19745. return null;
  19746. }
  19747. if (parseFloat(m[2]) > 59) {
  19748. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  19749. // First position is hours as it's over 59.
  19750. return computeSeconds(m[2], m[3], 0, m[4]);
  19751. }
  19752. // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
  19753. return computeSeconds(m[1], m[2], m[3], m[4]);
  19754. }
  19755. // A settings object holds key/value pairs and will ignore anything but the first
  19756. // assignment to a specific key.
  19757. class Settings {
  19758. constructor() {
  19759. this.values = Object.create(null);
  19760. }
  19761. // Only accept the first assignment to any key.
  19762. set(k, v) {
  19763. if (!this.get(k) && v !== '') {
  19764. this.values[k] = v;
  19765. }
  19766. }
  19767. // Return the value for a key, or a default value.
  19768. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  19769. // a number of possible default values as properties where 'defaultKey' is
  19770. // the key of the property that will be chosen; otherwise it's assumed to be
  19771. // a single value.
  19772. get(k, dflt, defaultKey) {
  19773. if (defaultKey) {
  19774. return this.has(k) ? this.values[k] : dflt[defaultKey];
  19775. }
  19776. return this.has(k) ? this.values[k] : dflt;
  19777. }
  19778. // Check whether we have a value for a key.
  19779. has(k) {
  19780. return k in this.values;
  19781. }
  19782. // Accept a setting if its one of the given alternatives.
  19783. alt(k, v, a) {
  19784. for (let n = 0; n < a.length; ++n) {
  19785. if (v === a[n]) {
  19786. this.set(k, v);
  19787. break;
  19788. }
  19789. }
  19790. }
  19791. // Accept a setting if its a valid (signed) integer.
  19792. integer(k, v) {
  19793. if (/^-?\d+$/.test(v)) {
  19794. // integer
  19795. this.set(k, parseInt(v, 10));
  19796. }
  19797. }
  19798. // Accept a setting if its a valid percentage.
  19799. percent(k, v) {
  19800. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  19801. const percent = parseFloat(v);
  19802. if (percent >= 0 && percent <= 100) {
  19803. this.set(k, percent);
  19804. return true;
  19805. }
  19806. }
  19807. return false;
  19808. }
  19809. }
  19810. // Helper function to parse input into groups separated by 'groupDelim', and
  19811. // interpret each group as a key/value pair separated by 'keyValueDelim'.
  19812. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  19813. const groups = groupDelim ? input.split(groupDelim) : [input];
  19814. for (const i in groups) {
  19815. if (typeof groups[i] !== 'string') {
  19816. continue;
  19817. }
  19818. const kv = groups[i].split(keyValueDelim);
  19819. if (kv.length !== 2) {
  19820. continue;
  19821. }
  19822. const k = kv[0];
  19823. const v = kv[1];
  19824. callback(k, v);
  19825. }
  19826. }
  19827. const defaults = new VTTCue(0, 0, '');
  19828. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  19829. // Safari doesn't yet support this change, but FF and Chrome do.
  19830. const center = defaults.align === 'middle' ? 'middle' : 'center';
  19831. function parseCue(input, cue, regionList) {
  19832. // Remember the original input if we need to throw an error.
  19833. const oInput = input;
  19834. // 4.1 WebVTT timestamp
  19835. function consumeTimeStamp() {
  19836. const ts = parseTimeStamp(input);
  19837. if (ts === null) {
  19838. throw new Error('Malformed timestamp: ' + oInput);
  19839. }
  19840. // Remove time stamp from input.
  19841. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  19842. return ts;
  19843. }
  19844. // 4.4.2 WebVTT cue settings
  19845. function consumeCueSettings(input, cue) {
  19846. const settings = new Settings();
  19847. parseOptions(input, function (k, v) {
  19848. let vals;
  19849. switch (k) {
  19850. case 'region':
  19851. // Find the last region we parsed with the same region id.
  19852. for (let i = regionList.length - 1; i >= 0; i--) {
  19853. if (regionList[i].id === v) {
  19854. settings.set(k, regionList[i].region);
  19855. break;
  19856. }
  19857. }
  19858. break;
  19859. case 'vertical':
  19860. settings.alt(k, v, ['rl', 'lr']);
  19861. break;
  19862. case 'line':
  19863. vals = v.split(',');
  19864. settings.integer(k, vals[0]);
  19865. if (settings.percent(k, vals[0])) {
  19866. settings.set('snapToLines', false);
  19867. }
  19868. settings.alt(k, vals[0], ['auto']);
  19869. if (vals.length === 2) {
  19870. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  19871. }
  19872. break;
  19873. case 'position':
  19874. vals = v.split(',');
  19875. settings.percent(k, vals[0]);
  19876. if (vals.length === 2) {
  19877. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  19878. }
  19879. break;
  19880. case 'size':
  19881. settings.percent(k, v);
  19882. break;
  19883. case 'align':
  19884. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  19885. break;
  19886. }
  19887. }, /:/, /\s/);
  19888. // Apply default values for any missing fields.
  19889. cue.region = settings.get('region', null);
  19890. cue.vertical = settings.get('vertical', '');
  19891. let line = settings.get('line', 'auto');
  19892. if (line === 'auto' && defaults.line === -1) {
  19893. // set numeric line number for Safari
  19894. line = -1;
  19895. }
  19896. cue.line = line;
  19897. cue.lineAlign = settings.get('lineAlign', 'start');
  19898. cue.snapToLines = settings.get('snapToLines', true);
  19899. cue.size = settings.get('size', 100);
  19900. cue.align = settings.get('align', center);
  19901. let position = settings.get('position', 'auto');
  19902. if (position === 'auto' && defaults.position === 50) {
  19903. // set numeric position for Safari
  19904. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  19905. }
  19906. cue.position = position;
  19907. }
  19908. function skipWhitespace() {
  19909. input = input.replace(/^\s+/, '');
  19910. }
  19911. // 4.1 WebVTT cue timings.
  19912. skipWhitespace();
  19913. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  19914. skipWhitespace();
  19915. if (input.slice(0, 3) !== '-->') {
  19916. // (3) next characters must match '-->'
  19917. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  19918. }
  19919. input = input.slice(3);
  19920. skipWhitespace();
  19921. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  19922. // 4.1 WebVTT cue settings list.
  19923. skipWhitespace();
  19924. consumeCueSettings(input, cue);
  19925. }
  19926. function fixLineBreaks(input) {
  19927. return input.replace(/<br(?: \/)?>/gi, '\n');
  19928. }
  19929. class VTTParser {
  19930. constructor() {
  19931. this.state = 'INITIAL';
  19932. this.buffer = '';
  19933. this.decoder = new StringDecoder();
  19934. this.regionList = [];
  19935. this.cue = null;
  19936. this.oncue = void 0;
  19937. this.onparsingerror = void 0;
  19938. this.onflush = void 0;
  19939. }
  19940. parse(data) {
  19941. const _this = this;
  19942. // If there is no data then we won't decode it, but will just try to parse
  19943. // whatever is in buffer already. This may occur in circumstances, for
  19944. // example when flush() is called.
  19945. if (data) {
  19946. // Try to decode the data that we received.
  19947. _this.buffer += _this.decoder.decode(data, {
  19948. stream: true
  19949. });
  19950. }
  19951. function collectNextLine() {
  19952. let buffer = _this.buffer;
  19953. let pos = 0;
  19954. buffer = fixLineBreaks(buffer);
  19955. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  19956. ++pos;
  19957. }
  19958. const line = buffer.slice(0, pos);
  19959. // Advance the buffer early in case we fail below.
  19960. if (buffer[pos] === '\r') {
  19961. ++pos;
  19962. }
  19963. if (buffer[pos] === '\n') {
  19964. ++pos;
  19965. }
  19966. _this.buffer = buffer.slice(pos);
  19967. return line;
  19968. }
  19969. // 3.2 WebVTT metadata header syntax
  19970. function parseHeader(input) {
  19971. parseOptions(input, function (k, v) {
  19972. // switch (k) {
  19973. // case 'region':
  19974. // 3.3 WebVTT region metadata header syntax
  19975. // console.log('parse region', v);
  19976. // parseRegion(v);
  19977. // break;
  19978. // }
  19979. }, /:/);
  19980. }
  19981. // 5.1 WebVTT file parsing.
  19982. try {
  19983. let line = '';
  19984. if (_this.state === 'INITIAL') {
  19985. // We can't start parsing until we have the first line.
  19986. if (!/\r\n|\n/.test(_this.buffer)) {
  19987. return this;
  19988. }
  19989. line = collectNextLine();
  19990. // strip of UTF-8 BOM if any
  19991. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  19992. const m = line.match(/^()?WEBVTT([ \t].*)?$/);
  19993. if (!(m != null && m[0])) {
  19994. throw new Error('Malformed WebVTT signature.');
  19995. }
  19996. _this.state = 'HEADER';
  19997. }
  19998. let alreadyCollectedLine = false;
  19999. while (_this.buffer) {
  20000. // We can't parse a line until we have the full line.
  20001. if (!/\r\n|\n/.test(_this.buffer)) {
  20002. return this;
  20003. }
  20004. if (!alreadyCollectedLine) {
  20005. line = collectNextLine();
  20006. } else {
  20007. alreadyCollectedLine = false;
  20008. }
  20009. switch (_this.state) {
  20010. case 'HEADER':
  20011. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  20012. if (/:/.test(line)) {
  20013. parseHeader(line);
  20014. } else if (!line) {
  20015. // An empty line terminates the header and starts the body (cues).
  20016. _this.state = 'ID';
  20017. }
  20018. continue;
  20019. case 'NOTE':
  20020. // Ignore NOTE blocks.
  20021. if (!line) {
  20022. _this.state = 'ID';
  20023. }
  20024. continue;
  20025. case 'ID':
  20026. // Check for the start of NOTE blocks.
  20027. if (/^NOTE($|[ \t])/.test(line)) {
  20028. _this.state = 'NOTE';
  20029. break;
  20030. }
  20031. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  20032. if (!line) {
  20033. continue;
  20034. }
  20035. _this.cue = new VTTCue(0, 0, '');
  20036. _this.state = 'CUE';
  20037. // 30-39 - Check if self line contains an optional identifier or timing data.
  20038. if (line.indexOf('-->') === -1) {
  20039. _this.cue.id = line;
  20040. continue;
  20041. }
  20042. // Process line as start of a cue.
  20043. /* falls through */
  20044. case 'CUE':
  20045. // 40 - Collect cue timings and settings.
  20046. if (!_this.cue) {
  20047. _this.state = 'BADCUE';
  20048. continue;
  20049. }
  20050. try {
  20051. parseCue(line, _this.cue, _this.regionList);
  20052. } catch (e) {
  20053. // In case of an error ignore rest of the cue.
  20054. _this.cue = null;
  20055. _this.state = 'BADCUE';
  20056. continue;
  20057. }
  20058. _this.state = 'CUETEXT';
  20059. continue;
  20060. case 'CUETEXT':
  20061. {
  20062. const hasSubstring = line.indexOf('-->') !== -1;
  20063. // 34 - If we have an empty line then report the cue.
  20064. // 35 - If we have the special substring '-->' then report the cue,
  20065. // but do not collect the line as we need to process the current
  20066. // one as a new cue.
  20067. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  20068. // We are done parsing self cue.
  20069. if (_this.oncue && _this.cue) {
  20070. _this.oncue(_this.cue);
  20071. }
  20072. _this.cue = null;
  20073. _this.state = 'ID';
  20074. continue;
  20075. }
  20076. if (_this.cue === null) {
  20077. continue;
  20078. }
  20079. if (_this.cue.text) {
  20080. _this.cue.text += '\n';
  20081. }
  20082. _this.cue.text += line;
  20083. }
  20084. continue;
  20085. case 'BADCUE':
  20086. // 54-62 - Collect and discard the remaining cue.
  20087. if (!line) {
  20088. _this.state = 'ID';
  20089. }
  20090. }
  20091. }
  20092. } catch (e) {
  20093. // If we are currently parsing a cue, report what we have.
  20094. if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
  20095. _this.oncue(_this.cue);
  20096. }
  20097. _this.cue = null;
  20098. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  20099. // another exception occurred so enter BADCUE state.
  20100. _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  20101. }
  20102. return this;
  20103. }
  20104. flush() {
  20105. const _this = this;
  20106. try {
  20107. // Finish decoding the stream.
  20108. // _this.buffer += _this.decoder.decode();
  20109. // Synthesize the end of the current cue or region.
  20110. if (_this.cue || _this.state === 'HEADER') {
  20111. _this.buffer += '\n\n';
  20112. _this.parse();
  20113. }
  20114. // If we've flushed, parsed, and we're still on the INITIAL state then
  20115. // that means we don't have enough of the stream to parse the first
  20116. // line.
  20117. if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
  20118. throw new Error('Malformed WebVTT signature.');
  20119. }
  20120. } catch (e) {
  20121. if (_this.onparsingerror) {
  20122. _this.onparsingerror(e);
  20123. }
  20124. }
  20125. if (_this.onflush) {
  20126. _this.onflush();
  20127. }
  20128. return this;
  20129. }
  20130. }
  20131. const LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  20132. // String.prototype.startsWith is not supported in IE11
  20133. const startsWith = function startsWith(inputString, searchString, position = 0) {
  20134. return inputString.slice(position, position + searchString.length) === searchString;
  20135. };
  20136. const cueString2millis = function cueString2millis(timeString) {
  20137. let ts = parseInt(timeString.slice(-3));
  20138. const secs = parseInt(timeString.slice(-6, -4));
  20139. const mins = parseInt(timeString.slice(-9, -7));
  20140. const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(':'))) : 0;
  20141. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  20142. throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);
  20143. }
  20144. ts += 1000 * secs;
  20145. ts += 60 * 1000 * mins;
  20146. ts += 60 * 60 * 1000 * hours;
  20147. return ts;
  20148. };
  20149. // From https://github.com/darkskyapp/string-hash
  20150. const hash = function hash(text) {
  20151. let _hash = 5381;
  20152. let i = text.length;
  20153. while (i) {
  20154. _hash = _hash * 33 ^ text.charCodeAt(--i);
  20155. }
  20156. return (_hash >>> 0).toString();
  20157. };
  20158. // Create a unique hash id for a cue based on start/end times and text.
  20159. // This helps timeline-controller to avoid showing repeated captions.
  20160. function generateCueId(startTime, endTime, text) {
  20161. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  20162. }
  20163. const calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  20164. let currCC = vttCCs[cc];
  20165. let prevCC = vttCCs[currCC.prevCC];
  20166. // This is the first discontinuity or cues have been processed since the last discontinuity
  20167. // Offset = current discontinuity time
  20168. if (!prevCC || !prevCC.new && currCC.new) {
  20169. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  20170. currCC.new = false;
  20171. return;
  20172. }
  20173. // There have been discontinuities since cues were last parsed.
  20174. // Offset = time elapsed
  20175. while ((_prevCC = prevCC) != null && _prevCC.new) {
  20176. var _prevCC;
  20177. vttCCs.ccOffset += currCC.start - prevCC.start;
  20178. currCC.new = false;
  20179. currCC = prevCC;
  20180. prevCC = vttCCs[currCC.prevCC];
  20181. }
  20182. vttCCs.presentationOffset = presentationTime;
  20183. };
  20184. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  20185. const parser = new VTTParser();
  20186. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  20187. // Uint8Array.prototype.reduce is not implemented in IE11
  20188. const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
  20189. const cues = [];
  20190. const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  20191. let cueTime = '00:00.000';
  20192. let timestampMapMPEGTS = 0;
  20193. let timestampMapLOCAL = 0;
  20194. let parsingError;
  20195. let inHeader = true;
  20196. parser.oncue = function (cue) {
  20197. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  20198. const currCC = vttCCs[cc];
  20199. let cueOffset = vttCCs.ccOffset;
  20200. // Calculate subtitle PTS offset
  20201. const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;
  20202. // Update offsets for new discontinuities
  20203. if (currCC != null && currCC.new) {
  20204. if (timestampMapLOCAL !== undefined) {
  20205. // When local time is provided, offset = discontinuity start time - local time
  20206. cueOffset = vttCCs.ccOffset = currCC.start;
  20207. } else {
  20208. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  20209. }
  20210. }
  20211. if (webVttMpegTsMapOffset) {
  20212. if (!initPTS) {
  20213. parsingError = new Error('Missing initPTS for VTT MPEGTS');
  20214. return;
  20215. }
  20216. // If we have MPEGTS, offset = presentation time + discontinuity offset
  20217. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  20218. }
  20219. const duration = cue.endTime - cue.startTime;
  20220. const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
  20221. cue.startTime = Math.max(startTime, 0);
  20222. cue.endTime = Math.max(startTime + duration, 0);
  20223. //trim trailing webvtt block whitespaces
  20224. const text = cue.text.trim();
  20225. // Fix encoding of special characters
  20226. cue.text = decodeURIComponent(encodeURIComponent(text));
  20227. // If the cue was not assigned an id from the VTT file (line above the content), create one.
  20228. if (!cue.id) {
  20229. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  20230. }
  20231. if (cue.endTime > 0) {
  20232. cues.push(cue);
  20233. }
  20234. };
  20235. parser.onparsingerror = function (error) {
  20236. parsingError = error;
  20237. };
  20238. parser.onflush = function () {
  20239. if (parsingError) {
  20240. errorCallBack(parsingError);
  20241. return;
  20242. }
  20243. callBack(cues);
  20244. };
  20245. // Go through contents line by line.
  20246. vttLines.forEach(line => {
  20247. if (inHeader) {
  20248. // Look for X-TIMESTAMP-MAP in header.
  20249. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  20250. // Once found, no more are allowed anyway, so stop searching.
  20251. inHeader = false;
  20252. // Extract LOCAL and MPEGTS.
  20253. line.slice(16).split(',').forEach(timestamp => {
  20254. if (startsWith(timestamp, 'LOCAL:')) {
  20255. cueTime = timestamp.slice(6);
  20256. } else if (startsWith(timestamp, 'MPEGTS:')) {
  20257. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  20258. }
  20259. });
  20260. try {
  20261. // Convert cue time to seconds
  20262. timestampMapLOCAL = cueString2millis(cueTime) / 1000;
  20263. } catch (error) {
  20264. parsingError = error;
  20265. }
  20266. // Return without parsing X-TIMESTAMP-MAP line.
  20267. return;
  20268. } else if (line === '') {
  20269. inHeader = false;
  20270. }
  20271. }
  20272. // Parse line by default.
  20273. parser.parse(line + '\n');
  20274. });
  20275. parser.flush();
  20276. }
  20277. const IMSC1_CODEC = 'stpp.ttml.im1t';
  20278. // Time format: h:m:s:frames(.subframes)
  20279. const HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  20280. // Time format: hours, minutes, seconds, milliseconds, frames, ticks
  20281. const TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  20282. const textAlignToLineAlign = {
  20283. left: 'start',
  20284. center: 'center',
  20285. right: 'end',
  20286. start: 'start',
  20287. end: 'end'
  20288. };
  20289. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  20290. const results = findBox(new Uint8Array(payload), ['mdat']);
  20291. if (results.length === 0) {
  20292. errorCallBack(new Error('Could not parse IMSC1 mdat'));
  20293. return;
  20294. }
  20295. const ttmlList = results.map(mdat => utf8ArrayToStr(mdat));
  20296. const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  20297. try {
  20298. ttmlList.forEach(ttml => callBack(parseTTML(ttml, syncTime)));
  20299. } catch (error) {
  20300. errorCallBack(error);
  20301. }
  20302. }
  20303. function parseTTML(ttml, syncTime) {
  20304. const parser = new DOMParser();
  20305. const xmlDoc = parser.parseFromString(ttml, 'text/xml');
  20306. const tt = xmlDoc.getElementsByTagName('tt')[0];
  20307. if (!tt) {
  20308. throw new Error('Invalid ttml');
  20309. }
  20310. const defaultRateInfo = {
  20311. frameRate: 30,
  20312. subFrameRate: 1,
  20313. frameRateMultiplier: 0,
  20314. tickRate: 0
  20315. };
  20316. const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {
  20317. result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];
  20318. return result;
  20319. }, {});
  20320. const trim = tt.getAttribute('xml:space') !== 'preserve';
  20321. const styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
  20322. const regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
  20323. const cueElements = getElementCollection(tt, 'body', '[begin]');
  20324. return [].map.call(cueElements, cueElement => {
  20325. const cueText = getTextContent(cueElement, trim);
  20326. if (!cueText || !cueElement.hasAttribute('begin')) {
  20327. return null;
  20328. }
  20329. const startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
  20330. const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
  20331. let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
  20332. if (startTime === null) {
  20333. throw timestampParsingError(cueElement);
  20334. }
  20335. if (endTime === null) {
  20336. if (duration === null) {
  20337. throw timestampParsingError(cueElement);
  20338. }
  20339. endTime = startTime + duration;
  20340. }
  20341. const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  20342. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  20343. const region = regionElements[cueElement.getAttribute('region')];
  20344. const style = styleElements[cueElement.getAttribute('style')];
  20345. // Apply styles to cue
  20346. const styles = getTtmlStyles(region, style, styleElements);
  20347. const {
  20348. textAlign
  20349. } = styles;
  20350. if (textAlign) {
  20351. // cue.positionAlign not settable in FF~2016
  20352. const lineAlign = textAlignToLineAlign[textAlign];
  20353. if (lineAlign) {
  20354. cue.lineAlign = lineAlign;
  20355. }
  20356. cue.align = textAlign;
  20357. }
  20358. _extends(cue, styles);
  20359. return cue;
  20360. }).filter(cue => cue !== null);
  20361. }
  20362. function getElementCollection(fromElement, parentName, childName) {
  20363. const parent = fromElement.getElementsByTagName(parentName)[0];
  20364. if (parent) {
  20365. return [].slice.call(parent.querySelectorAll(childName));
  20366. }
  20367. return [];
  20368. }
  20369. function collectionToDictionary(elementsWithId) {
  20370. return elementsWithId.reduce((dict, element) => {
  20371. const id = element.getAttribute('xml:id');
  20372. if (id) {
  20373. dict[id] = element;
  20374. }
  20375. return dict;
  20376. }, {});
  20377. }
  20378. function getTextContent(element, trim) {
  20379. return [].slice.call(element.childNodes).reduce((str, node, i) => {
  20380. var _node$childNodes;
  20381. if (node.nodeName === 'br' && i) {
  20382. return str + '\n';
  20383. }
  20384. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  20385. return getTextContent(node, trim);
  20386. } else if (trim) {
  20387. return str + node.textContent.trim().replace(/\s+/g, ' ');
  20388. }
  20389. return str + node.textContent;
  20390. }, '');
  20391. }
  20392. function getTtmlStyles(region, style, styleElements) {
  20393. const ttsNs = 'http://www.w3.org/ns/ttml#styling';
  20394. let regionStyle = null;
  20395. const styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily'
  20396. // 'fontWeight',
  20397. // 'lineHeight',
  20398. // 'wrapOption',
  20399. // 'fontStyle',
  20400. // 'direction',
  20401. // 'writingMode'
  20402. ];
  20403. const regionStyleName = region != null && region.hasAttribute('style') ? region.getAttribute('style') : null;
  20404. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  20405. regionStyle = styleElements[regionStyleName];
  20406. }
  20407. return styleAttributes.reduce((styles, name) => {
  20408. const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  20409. if (value) {
  20410. styles[name] = value;
  20411. }
  20412. return styles;
  20413. }, {});
  20414. }
  20415. function getAttributeNS(element, ns, name) {
  20416. if (!element) {
  20417. return null;
  20418. }
  20419. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  20420. }
  20421. function timestampParsingError(node) {
  20422. return new Error(`Could not parse ttml timestamp ${node}`);
  20423. }
  20424. function parseTtmlTime(timeAttributeValue, rateInfo) {
  20425. if (!timeAttributeValue) {
  20426. return null;
  20427. }
  20428. let seconds = parseTimeStamp(timeAttributeValue);
  20429. if (seconds === null) {
  20430. if (HMSF_REGEX.test(timeAttributeValue)) {
  20431. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  20432. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  20433. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  20434. }
  20435. }
  20436. return seconds;
  20437. }
  20438. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  20439. const m = HMSF_REGEX.exec(timeAttributeValue);
  20440. const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  20441. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  20442. }
  20443. function parseTimeUnits(timeAttributeValue, rateInfo) {
  20444. const m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  20445. const value = Number(m[1]);
  20446. const unit = m[2];
  20447. switch (unit) {
  20448. case 'h':
  20449. return value * 3600;
  20450. case 'm':
  20451. return value * 60;
  20452. case 'ms':
  20453. return value * 1000;
  20454. case 'f':
  20455. return value / rateInfo.frameRate;
  20456. case 't':
  20457. return value / rateInfo.tickRate;
  20458. }
  20459. return value;
  20460. }
  20461. class TimelineController {
  20462. constructor(hls) {
  20463. this.hls = void 0;
  20464. this.media = null;
  20465. this.config = void 0;
  20466. this.enabled = true;
  20467. this.Cues = void 0;
  20468. this.textTracks = [];
  20469. this.tracks = [];
  20470. this.initPTS = [];
  20471. this.unparsedVttFrags = [];
  20472. this.captionsTracks = {};
  20473. this.nonNativeCaptionsTracks = {};
  20474. this.cea608Parser1 = void 0;
  20475. this.cea608Parser2 = void 0;
  20476. this.lastCc = -1;
  20477. // Last video (CEA-608) fragment CC
  20478. this.lastSn = -1;
  20479. // Last video (CEA-608) fragment MSN
  20480. this.lastPartIndex = -1;
  20481. // Last video (CEA-608) fragment Part Index
  20482. this.prevCC = -1;
  20483. // Last subtitle fragment CC
  20484. this.vttCCs = newVTTCCs();
  20485. this.captionsProperties = void 0;
  20486. this.hls = hls;
  20487. this.config = hls.config;
  20488. this.Cues = hls.config.cueHandler;
  20489. this.captionsProperties = {
  20490. textTrack1: {
  20491. label: this.config.captionsTextTrack1Label,
  20492. languageCode: this.config.captionsTextTrack1LanguageCode
  20493. },
  20494. textTrack2: {
  20495. label: this.config.captionsTextTrack2Label,
  20496. languageCode: this.config.captionsTextTrack2LanguageCode
  20497. },
  20498. textTrack3: {
  20499. label: this.config.captionsTextTrack3Label,
  20500. languageCode: this.config.captionsTextTrack3LanguageCode
  20501. },
  20502. textTrack4: {
  20503. label: this.config.captionsTextTrack4Label,
  20504. languageCode: this.config.captionsTextTrack4LanguageCode
  20505. }
  20506. };
  20507. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20508. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20509. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20510. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20511. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  20512. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  20513. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  20514. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  20515. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  20516. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  20517. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  20518. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  20519. }
  20520. destroy() {
  20521. const {
  20522. hls
  20523. } = this;
  20524. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  20525. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  20526. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  20527. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  20528. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  20529. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  20530. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  20531. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  20532. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  20533. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  20534. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  20535. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  20536. // @ts-ignore
  20537. this.hls = this.config = null;
  20538. this.cea608Parser1 = this.cea608Parser2 = undefined;
  20539. }
  20540. initCea608Parsers() {
  20541. if (this.config.enableCEA708Captions && (!this.cea608Parser1 || !this.cea608Parser2)) {
  20542. const channel1 = new OutputFilter(this, 'textTrack1');
  20543. const channel2 = new OutputFilter(this, 'textTrack2');
  20544. const channel3 = new OutputFilter(this, 'textTrack3');
  20545. const channel4 = new OutputFilter(this, 'textTrack4');
  20546. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  20547. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  20548. }
  20549. }
  20550. addCues(trackName, startTime, endTime, screen, cueRanges) {
  20551. // skip cues which overlap more than 50% with previously parsed time ranges
  20552. let merged = false;
  20553. for (let i = cueRanges.length; i--;) {
  20554. const cueRange = cueRanges[i];
  20555. const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  20556. if (overlap >= 0) {
  20557. cueRange[0] = Math.min(cueRange[0], startTime);
  20558. cueRange[1] = Math.max(cueRange[1], endTime);
  20559. merged = true;
  20560. if (overlap / (endTime - startTime) > 0.5) {
  20561. return;
  20562. }
  20563. }
  20564. }
  20565. if (!merged) {
  20566. cueRanges.push([startTime, endTime]);
  20567. }
  20568. if (this.config.renderTextTracksNatively) {
  20569. const track = this.captionsTracks[trackName];
  20570. this.Cues.newCue(track, startTime, endTime, screen);
  20571. } else {
  20572. const cues = this.Cues.newCue(null, startTime, endTime, screen);
  20573. this.hls.trigger(Events.CUES_PARSED, {
  20574. type: 'captions',
  20575. cues,
  20576. track: trackName
  20577. });
  20578. }
  20579. }
  20580. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  20581. onInitPtsFound(event, {
  20582. frag,
  20583. id,
  20584. initPTS,
  20585. timescale
  20586. }) {
  20587. const {
  20588. unparsedVttFrags
  20589. } = this;
  20590. if (id === 'main') {
  20591. this.initPTS[frag.cc] = {
  20592. baseTime: initPTS,
  20593. timescale
  20594. };
  20595. }
  20596. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  20597. // Parse any unparsed fragments upon receiving the initial PTS.
  20598. if (unparsedVttFrags.length) {
  20599. this.unparsedVttFrags = [];
  20600. unparsedVttFrags.forEach(frag => {
  20601. this.onFragLoaded(Events.FRAG_LOADED, frag);
  20602. });
  20603. }
  20604. }
  20605. getExistingTrack(label, language) {
  20606. const {
  20607. media
  20608. } = this;
  20609. if (media) {
  20610. for (let i = 0; i < media.textTracks.length; i++) {
  20611. const textTrack = media.textTracks[i];
  20612. if (canReuseVttTextTrack(textTrack, {
  20613. name: label,
  20614. lang: language,
  20615. attrs: {}
  20616. })) {
  20617. return textTrack;
  20618. }
  20619. }
  20620. }
  20621. return null;
  20622. }
  20623. createCaptionsTrack(trackName) {
  20624. if (this.config.renderTextTracksNatively) {
  20625. this.createNativeTrack(trackName);
  20626. } else {
  20627. this.createNonNativeTrack(trackName);
  20628. }
  20629. }
  20630. createNativeTrack(trackName) {
  20631. if (this.captionsTracks[trackName]) {
  20632. return;
  20633. }
  20634. const {
  20635. captionsProperties,
  20636. captionsTracks,
  20637. media
  20638. } = this;
  20639. const {
  20640. label,
  20641. languageCode
  20642. } = captionsProperties[trackName];
  20643. // Enable reuse of existing text track.
  20644. const existingTrack = this.getExistingTrack(label, languageCode);
  20645. if (!existingTrack) {
  20646. const textTrack = this.createTextTrack('captions', label, languageCode);
  20647. if (textTrack) {
  20648. // Set a special property on the track so we know it's managed by Hls.js
  20649. textTrack[trackName] = true;
  20650. captionsTracks[trackName] = textTrack;
  20651. }
  20652. } else {
  20653. captionsTracks[trackName] = existingTrack;
  20654. clearCurrentCues(captionsTracks[trackName]);
  20655. sendAddTrackEvent(captionsTracks[trackName], media);
  20656. }
  20657. }
  20658. createNonNativeTrack(trackName) {
  20659. if (this.nonNativeCaptionsTracks[trackName]) {
  20660. return;
  20661. }
  20662. // Create a list of a single track for the provider to consume
  20663. const trackProperties = this.captionsProperties[trackName];
  20664. if (!trackProperties) {
  20665. return;
  20666. }
  20667. const label = trackProperties.label;
  20668. const track = {
  20669. _id: trackName,
  20670. label,
  20671. kind: 'captions',
  20672. default: trackProperties.media ? !!trackProperties.media.default : false,
  20673. closedCaptions: trackProperties.media
  20674. };
  20675. this.nonNativeCaptionsTracks[trackName] = track;
  20676. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  20677. tracks: [track]
  20678. });
  20679. }
  20680. createTextTrack(kind, label, lang) {
  20681. const media = this.media;
  20682. if (!media) {
  20683. return;
  20684. }
  20685. return media.addTextTrack(kind, label, lang);
  20686. }
  20687. onMediaAttaching(event, data) {
  20688. this.media = data.media;
  20689. this._cleanTracks();
  20690. }
  20691. onMediaDetaching() {
  20692. const {
  20693. captionsTracks
  20694. } = this;
  20695. Object.keys(captionsTracks).forEach(trackName => {
  20696. clearCurrentCues(captionsTracks[trackName]);
  20697. delete captionsTracks[trackName];
  20698. });
  20699. this.nonNativeCaptionsTracks = {};
  20700. }
  20701. onManifestLoading() {
  20702. // Detect discontinuity in video fragment (CEA-608) parsing
  20703. this.lastCc = -1;
  20704. this.lastSn = -1;
  20705. this.lastPartIndex = -1;
  20706. // Detect discontinuity in subtitle manifests
  20707. this.prevCC = -1;
  20708. this.vttCCs = newVTTCCs();
  20709. // Reset tracks
  20710. this._cleanTracks();
  20711. this.tracks = [];
  20712. this.captionsTracks = {};
  20713. this.nonNativeCaptionsTracks = {};
  20714. this.textTracks = [];
  20715. this.unparsedVttFrags = [];
  20716. this.initPTS = [];
  20717. if (this.cea608Parser1 && this.cea608Parser2) {
  20718. this.cea608Parser1.reset();
  20719. this.cea608Parser2.reset();
  20720. }
  20721. }
  20722. _cleanTracks() {
  20723. // clear outdated subtitles
  20724. const {
  20725. media
  20726. } = this;
  20727. if (!media) {
  20728. return;
  20729. }
  20730. const textTracks = media.textTracks;
  20731. if (textTracks) {
  20732. for (let i = 0; i < textTracks.length; i++) {
  20733. clearCurrentCues(textTracks[i]);
  20734. }
  20735. }
  20736. }
  20737. onSubtitleTracksUpdated(event, data) {
  20738. const tracks = data.subtitleTracks || [];
  20739. const hasIMSC1 = tracks.some(track => track.textCodec === IMSC1_CODEC);
  20740. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  20741. const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  20742. if (listIsIdentical) {
  20743. this.tracks = tracks;
  20744. return;
  20745. }
  20746. this.textTracks = [];
  20747. this.tracks = tracks;
  20748. if (this.config.renderTextTracksNatively) {
  20749. const media = this.media;
  20750. const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  20751. this.tracks.forEach((track, index) => {
  20752. // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks
  20753. let textTrack;
  20754. if (inUseTracks) {
  20755. let inUseTrack = null;
  20756. for (let i = 0; i < inUseTracks.length; i++) {
  20757. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  20758. inUseTrack = inUseTracks[i];
  20759. inUseTracks[i] = null;
  20760. break;
  20761. }
  20762. }
  20763. if (inUseTrack) {
  20764. textTrack = inUseTrack;
  20765. }
  20766. }
  20767. if (textTrack) {
  20768. clearCurrentCues(textTrack);
  20769. } else {
  20770. const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  20771. textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);
  20772. if (textTrack) {
  20773. textTrack.mode = 'disabled';
  20774. }
  20775. }
  20776. if (textTrack) {
  20777. this.textTracks.push(textTrack);
  20778. }
  20779. });
  20780. // Warn when video element has captions or subtitle TextTracks carried over from another source
  20781. if (inUseTracks != null && inUseTracks.length) {
  20782. const unusedTextTracks = inUseTracks.filter(t => t !== null).map(t => t.label);
  20783. if (unusedTextTracks.length) {
  20784. logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(', ')}. Replace media element for each source to clear TextTracks and captions menu.`);
  20785. }
  20786. }
  20787. } else if (this.tracks.length) {
  20788. // Create a list of tracks for the provider to consume
  20789. const tracksList = this.tracks.map(track => {
  20790. return {
  20791. label: track.name,
  20792. kind: track.type.toLowerCase(),
  20793. default: track.default,
  20794. subtitleTrack: track
  20795. };
  20796. });
  20797. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  20798. tracks: tracksList
  20799. });
  20800. }
  20801. }
  20802. }
  20803. onManifestLoaded(event, data) {
  20804. if (this.config.enableCEA708Captions && data.captions) {
  20805. data.captions.forEach(captionsTrack => {
  20806. const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  20807. if (!instreamIdMatch) {
  20808. return;
  20809. }
  20810. const trackName = `textTrack${instreamIdMatch[1]}`;
  20811. const trackProperties = this.captionsProperties[trackName];
  20812. if (!trackProperties) {
  20813. return;
  20814. }
  20815. trackProperties.label = captionsTrack.name;
  20816. if (captionsTrack.lang) {
  20817. // optional attribute
  20818. trackProperties.languageCode = captionsTrack.lang;
  20819. }
  20820. trackProperties.media = captionsTrack;
  20821. });
  20822. }
  20823. }
  20824. closedCaptionsForLevel(frag) {
  20825. const level = this.hls.levels[frag.level];
  20826. return level == null ? void 0 : level.attrs['CLOSED-CAPTIONS'];
  20827. }
  20828. onFragLoading(event, data) {
  20829. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  20830. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  20831. var _data$part$index, _data$part;
  20832. const {
  20833. cea608Parser1,
  20834. cea608Parser2,
  20835. lastSn
  20836. } = this;
  20837. const {
  20838. cc,
  20839. sn
  20840. } = data.frag;
  20841. const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  20842. if (cea608Parser1 && cea608Parser2) {
  20843. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  20844. cea608Parser1.reset();
  20845. cea608Parser2.reset();
  20846. }
  20847. }
  20848. this.lastCc = cc;
  20849. this.lastSn = sn;
  20850. this.lastPartIndex = partIndex;
  20851. }
  20852. }
  20853. onFragLoaded(event, data) {
  20854. const {
  20855. frag,
  20856. payload
  20857. } = data;
  20858. if (frag.type === PlaylistLevelType.SUBTITLE) {
  20859. // If fragment is subtitle type, parse as WebVTT.
  20860. if (payload.byteLength) {
  20861. const decryptData = frag.decryptdata;
  20862. // fragment after decryption has a stats object
  20863. const decrypted = ('stats' in data);
  20864. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  20865. if (decryptData == null || !decryptData.encrypted || decrypted) {
  20866. const trackPlaylistMedia = this.tracks[frag.level];
  20867. const vttCCs = this.vttCCs;
  20868. if (!vttCCs[frag.cc]) {
  20869. vttCCs[frag.cc] = {
  20870. start: frag.start,
  20871. prevCC: this.prevCC,
  20872. new: true
  20873. };
  20874. this.prevCC = frag.cc;
  20875. }
  20876. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  20877. this._parseIMSC1(frag, payload);
  20878. } else {
  20879. this._parseVTTs(data);
  20880. }
  20881. }
  20882. } else {
  20883. // In case there is no payload, finish unsuccessfully.
  20884. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20885. success: false,
  20886. frag,
  20887. error: new Error('Empty subtitle payload')
  20888. });
  20889. }
  20890. }
  20891. }
  20892. _parseIMSC1(frag, payload) {
  20893. const hls = this.hls;
  20894. parseIMSC1(payload, this.initPTS[frag.cc], cues => {
  20895. this._appendCues(cues, frag.level);
  20896. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20897. success: true,
  20898. frag: frag
  20899. });
  20900. }, error => {
  20901. logger.log(`Failed to parse IMSC1: ${error}`);
  20902. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20903. success: false,
  20904. frag: frag,
  20905. error
  20906. });
  20907. });
  20908. }
  20909. _parseVTTs(data) {
  20910. var _frag$initSegment;
  20911. const {
  20912. frag,
  20913. payload
  20914. } = data;
  20915. // We need an initial synchronisation PTS. Store fragments as long as none has arrived
  20916. const {
  20917. initPTS,
  20918. unparsedVttFrags
  20919. } = this;
  20920. const maxAvCC = initPTS.length - 1;
  20921. if (!initPTS[frag.cc] && maxAvCC === -1) {
  20922. unparsedVttFrags.push(data);
  20923. return;
  20924. }
  20925. const hls = this.hls;
  20926. // Parse the WebVTT file contents.
  20927. const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)) : payload;
  20928. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, cues => {
  20929. this._appendCues(cues, frag.level);
  20930. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20931. success: true,
  20932. frag: frag
  20933. });
  20934. }, error => {
  20935. const missingInitPTS = error.message === 'Missing initPTS for VTT MPEGTS';
  20936. if (missingInitPTS) {
  20937. unparsedVttFrags.push(data);
  20938. } else {
  20939. this._fallbackToIMSC1(frag, payload);
  20940. }
  20941. // Something went wrong while parsing. Trigger event with success false.
  20942. logger.log(`Failed to parse VTT cue: ${error}`);
  20943. if (missingInitPTS && maxAvCC > frag.cc) {
  20944. return;
  20945. }
  20946. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  20947. success: false,
  20948. frag: frag,
  20949. error
  20950. });
  20951. });
  20952. }
  20953. _fallbackToIMSC1(frag, payload) {
  20954. // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
  20955. const trackPlaylistMedia = this.tracks[frag.level];
  20956. if (!trackPlaylistMedia.textCodec) {
  20957. parseIMSC1(payload, this.initPTS[frag.cc], () => {
  20958. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  20959. this._parseIMSC1(frag, payload);
  20960. }, () => {
  20961. trackPlaylistMedia.textCodec = 'wvtt';
  20962. });
  20963. }
  20964. }
  20965. _appendCues(cues, fragLevel) {
  20966. const hls = this.hls;
  20967. if (this.config.renderTextTracksNatively) {
  20968. const textTrack = this.textTracks[fragLevel];
  20969. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  20970. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  20971. // and trying to access getCueById method of cues will throw an exception
  20972. // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
  20973. if (!textTrack || textTrack.mode === 'disabled') {
  20974. return;
  20975. }
  20976. cues.forEach(cue => addCueToTrack(textTrack, cue));
  20977. } else {
  20978. const currentTrack = this.tracks[fragLevel];
  20979. if (!currentTrack) {
  20980. return;
  20981. }
  20982. const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
  20983. hls.trigger(Events.CUES_PARSED, {
  20984. type: 'subtitles',
  20985. cues,
  20986. track
  20987. });
  20988. }
  20989. }
  20990. onFragDecrypted(event, data) {
  20991. const {
  20992. frag
  20993. } = data;
  20994. if (frag.type === PlaylistLevelType.SUBTITLE) {
  20995. this.onFragLoaded(Events.FRAG_LOADED, data);
  20996. }
  20997. }
  20998. onSubtitleTracksCleared() {
  20999. this.tracks = [];
  21000. this.captionsTracks = {};
  21001. }
  21002. onFragParsingUserdata(event, data) {
  21003. this.initCea608Parsers();
  21004. const {
  21005. cea608Parser1,
  21006. cea608Parser2
  21007. } = this;
  21008. if (!this.enabled || !cea608Parser1 || !cea608Parser2) {
  21009. return;
  21010. }
  21011. const {
  21012. frag,
  21013. samples
  21014. } = data;
  21015. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === 'NONE') {
  21016. return;
  21017. }
  21018. // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  21019. // It will create the proper timestamps based on the PTS value
  21020. for (let i = 0; i < samples.length; i++) {
  21021. const ccBytes = samples[i].bytes;
  21022. if (ccBytes) {
  21023. const ccdatas = this.extractCea608Data(ccBytes);
  21024. cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  21025. cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  21026. }
  21027. }
  21028. }
  21029. onBufferFlushing(event, {
  21030. startOffset,
  21031. endOffset,
  21032. endOffsetSubtitles,
  21033. type
  21034. }) {
  21035. const {
  21036. media
  21037. } = this;
  21038. if (!media || media.currentTime < endOffset) {
  21039. return;
  21040. }
  21041. // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
  21042. // Forward cues are never removed because we can loose streamed 608 content from recent fragments
  21043. if (!type || type === 'video') {
  21044. const {
  21045. captionsTracks
  21046. } = this;
  21047. Object.keys(captionsTracks).forEach(trackName => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));
  21048. }
  21049. if (this.config.renderTextTracksNatively) {
  21050. // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
  21051. if (startOffset === 0 && endOffsetSubtitles !== undefined) {
  21052. const {
  21053. textTracks
  21054. } = this;
  21055. Object.keys(textTracks).forEach(trackName => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));
  21056. }
  21057. }
  21058. }
  21059. extractCea608Data(byteArray) {
  21060. const actualCCBytes = [[], []];
  21061. const count = byteArray[0] & 0x1f;
  21062. let position = 2;
  21063. for (let j = 0; j < count; j++) {
  21064. const tmpByte = byteArray[position++];
  21065. const ccbyte1 = 0x7f & byteArray[position++];
  21066. const ccbyte2 = 0x7f & byteArray[position++];
  21067. if (ccbyte1 === 0 && ccbyte2 === 0) {
  21068. continue;
  21069. }
  21070. const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels
  21071. if (ccValid) {
  21072. const ccType = 0x03 & tmpByte;
  21073. if (0x00 /* CEA608 field1*/ === ccType || 0x01 /* CEA608 field2*/ === ccType) {
  21074. // Exclude CEA708 CC data.
  21075. actualCCBytes[ccType].push(ccbyte1);
  21076. actualCCBytes[ccType].push(ccbyte2);
  21077. }
  21078. }
  21079. }
  21080. return actualCCBytes;
  21081. }
  21082. }
  21083. function captionsOrSubtitlesFromCharacteristics(track) {
  21084. if (track.characteristics) {
  21085. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  21086. return 'captions';
  21087. }
  21088. }
  21089. return 'subtitles';
  21090. }
  21091. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  21092. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  21093. }
  21094. function intersection(x1, x2, y1, y2) {
  21095. return Math.min(x2, y2) - Math.max(x1, y1);
  21096. }
  21097. function newVTTCCs() {
  21098. return {
  21099. ccOffset: 0,
  21100. presentationOffset: 0,
  21101. 0: {
  21102. start: 0,
  21103. prevCC: -1,
  21104. new: true
  21105. }
  21106. };
  21107. }
  21108. class CapLevelController {
  21109. constructor(hls) {
  21110. this.hls = void 0;
  21111. this.autoLevelCapping = void 0;
  21112. this.firstLevel = void 0;
  21113. this.media = void 0;
  21114. this.restrictedLevels = void 0;
  21115. this.timer = void 0;
  21116. this.clientRect = void 0;
  21117. this.streamController = void 0;
  21118. this.hls = hls;
  21119. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21120. this.firstLevel = -1;
  21121. this.media = null;
  21122. this.restrictedLevels = [];
  21123. this.timer = undefined;
  21124. this.clientRect = null;
  21125. this.registerListeners();
  21126. }
  21127. setStreamController(streamController) {
  21128. this.streamController = streamController;
  21129. }
  21130. destroy() {
  21131. if (this.hls) {
  21132. this.unregisterListener();
  21133. }
  21134. if (this.timer) {
  21135. this.stopCapping();
  21136. }
  21137. this.media = null;
  21138. this.clientRect = null;
  21139. // @ts-ignore
  21140. this.hls = this.streamController = null;
  21141. }
  21142. registerListeners() {
  21143. const {
  21144. hls
  21145. } = this;
  21146. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  21147. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21148. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21149. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21150. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21151. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21152. }
  21153. unregisterListener() {
  21154. const {
  21155. hls
  21156. } = this;
  21157. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  21158. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21159. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21160. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  21161. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  21162. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  21163. }
  21164. onFpsDropLevelCapping(event, data) {
  21165. // Don't add a restricted level more than once
  21166. const level = this.hls.levels[data.droppedLevel];
  21167. if (this.isLevelAllowed(level)) {
  21168. this.restrictedLevels.push({
  21169. bitrate: level.bitrate,
  21170. height: level.height,
  21171. width: level.width
  21172. });
  21173. }
  21174. }
  21175. onMediaAttaching(event, data) {
  21176. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  21177. this.clientRect = null;
  21178. if (this.timer && this.hls.levels.length) {
  21179. this.detectPlayerSize();
  21180. }
  21181. }
  21182. onManifestParsed(event, data) {
  21183. const hls = this.hls;
  21184. this.restrictedLevels = [];
  21185. this.firstLevel = data.firstLevel;
  21186. if (hls.config.capLevelToPlayerSize && data.video) {
  21187. // Start capping immediately if the manifest has signaled video codecs
  21188. this.startCapping();
  21189. }
  21190. }
  21191. onLevelsUpdated(event, data) {
  21192. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  21193. this.detectPlayerSize();
  21194. }
  21195. }
  21196. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  21197. // to the first level
  21198. onBufferCodecs(event, data) {
  21199. const hls = this.hls;
  21200. if (hls.config.capLevelToPlayerSize && data.video) {
  21201. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  21202. this.startCapping();
  21203. }
  21204. }
  21205. onMediaDetaching() {
  21206. this.stopCapping();
  21207. }
  21208. detectPlayerSize() {
  21209. if (this.media) {
  21210. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  21211. this.clientRect = null;
  21212. return;
  21213. }
  21214. const levels = this.hls.levels;
  21215. if (levels.length) {
  21216. const hls = this.hls;
  21217. const maxLevel = this.getMaxLevel(levels.length - 1);
  21218. if (maxLevel !== this.autoLevelCapping) {
  21219. logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);
  21220. }
  21221. hls.autoLevelCapping = maxLevel;
  21222. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  21223. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  21224. // usually happen when the user go to the fullscreen mode.
  21225. this.streamController.nextLevelSwitch();
  21226. }
  21227. this.autoLevelCapping = hls.autoLevelCapping;
  21228. }
  21229. }
  21230. }
  21231. /*
  21232. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  21233. */
  21234. getMaxLevel(capLevelIndex) {
  21235. const levels = this.hls.levels;
  21236. if (!levels.length) {
  21237. return -1;
  21238. }
  21239. const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);
  21240. this.clientRect = null;
  21241. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  21242. }
  21243. startCapping() {
  21244. if (this.timer) {
  21245. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  21246. return;
  21247. }
  21248. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21249. self.clearInterval(this.timer);
  21250. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  21251. this.detectPlayerSize();
  21252. }
  21253. stopCapping() {
  21254. this.restrictedLevels = [];
  21255. this.firstLevel = -1;
  21256. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  21257. if (this.timer) {
  21258. self.clearInterval(this.timer);
  21259. this.timer = undefined;
  21260. }
  21261. }
  21262. getDimensions() {
  21263. if (this.clientRect) {
  21264. return this.clientRect;
  21265. }
  21266. const media = this.media;
  21267. const boundsRect = {
  21268. width: 0,
  21269. height: 0
  21270. };
  21271. if (media) {
  21272. const clientRect = media.getBoundingClientRect();
  21273. boundsRect.width = clientRect.width;
  21274. boundsRect.height = clientRect.height;
  21275. if (!boundsRect.width && !boundsRect.height) {
  21276. // When the media element has no width or height (equivalent to not being in the DOM),
  21277. // then use its width and height attributes (media.width, media.height)
  21278. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  21279. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  21280. }
  21281. }
  21282. this.clientRect = boundsRect;
  21283. return boundsRect;
  21284. }
  21285. get mediaWidth() {
  21286. return this.getDimensions().width * this.contentScaleFactor;
  21287. }
  21288. get mediaHeight() {
  21289. return this.getDimensions().height * this.contentScaleFactor;
  21290. }
  21291. get contentScaleFactor() {
  21292. let pixelRatio = 1;
  21293. if (!this.hls.config.ignoreDevicePixelRatio) {
  21294. try {
  21295. pixelRatio = self.devicePixelRatio;
  21296. } catch (e) {
  21297. /* no-op */
  21298. }
  21299. }
  21300. return pixelRatio;
  21301. }
  21302. isLevelAllowed(level) {
  21303. const restrictedLevels = this.restrictedLevels;
  21304. return !restrictedLevels.some(restrictedLevel => {
  21305. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  21306. });
  21307. }
  21308. static getMaxLevelByMediaSize(levels, width, height) {
  21309. if (!(levels != null && levels.length)) {
  21310. return -1;
  21311. }
  21312. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  21313. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  21314. const atGreatestBandwidth = (curLevel, nextLevel) => {
  21315. if (!nextLevel) {
  21316. return true;
  21317. }
  21318. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  21319. };
  21320. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  21321. // the max level
  21322. let maxLevelIndex = levels.length - 1;
  21323. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  21324. const squareSize = Math.max(width, height);
  21325. for (let i = 0; i < levels.length; i += 1) {
  21326. const level = levels[i];
  21327. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  21328. maxLevelIndex = i;
  21329. break;
  21330. }
  21331. }
  21332. return maxLevelIndex;
  21333. }
  21334. }
  21335. class FPSController {
  21336. constructor(hls) {
  21337. this.hls = void 0;
  21338. this.isVideoPlaybackQualityAvailable = false;
  21339. this.timer = void 0;
  21340. this.media = null;
  21341. this.lastTime = void 0;
  21342. this.lastDroppedFrames = 0;
  21343. this.lastDecodedFrames = 0;
  21344. // stream controller must be provided as a dependency!
  21345. this.streamController = void 0;
  21346. this.hls = hls;
  21347. this.registerListeners();
  21348. }
  21349. setStreamController(streamController) {
  21350. this.streamController = streamController;
  21351. }
  21352. registerListeners() {
  21353. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21354. }
  21355. unregisterListeners() {
  21356. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  21357. }
  21358. destroy() {
  21359. if (this.timer) {
  21360. clearInterval(this.timer);
  21361. }
  21362. this.unregisterListeners();
  21363. this.isVideoPlaybackQualityAvailable = false;
  21364. this.media = null;
  21365. }
  21366. onMediaAttaching(event, data) {
  21367. const config = this.hls.config;
  21368. if (config.capLevelOnFPSDrop) {
  21369. const media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  21370. this.media = media;
  21371. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  21372. this.isVideoPlaybackQualityAvailable = true;
  21373. }
  21374. self.clearInterval(this.timer);
  21375. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  21376. }
  21377. }
  21378. checkFPS(video, decodedFrames, droppedFrames) {
  21379. const currentTime = performance.now();
  21380. if (decodedFrames) {
  21381. if (this.lastTime) {
  21382. const currentPeriod = currentTime - this.lastTime;
  21383. const currentDropped = droppedFrames - this.lastDroppedFrames;
  21384. const currentDecoded = decodedFrames - this.lastDecodedFrames;
  21385. const droppedFPS = 1000 * currentDropped / currentPeriod;
  21386. const hls = this.hls;
  21387. hls.trigger(Events.FPS_DROP, {
  21388. currentDropped: currentDropped,
  21389. currentDecoded: currentDecoded,
  21390. totalDroppedFrames: droppedFrames
  21391. });
  21392. if (droppedFPS > 0) {
  21393. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  21394. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  21395. let currentLevel = hls.currentLevel;
  21396. logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  21397. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  21398. currentLevel = currentLevel - 1;
  21399. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  21400. level: currentLevel,
  21401. droppedLevel: hls.currentLevel
  21402. });
  21403. hls.autoLevelCapping = currentLevel;
  21404. this.streamController.nextLevelSwitch();
  21405. }
  21406. }
  21407. }
  21408. }
  21409. this.lastTime = currentTime;
  21410. this.lastDroppedFrames = droppedFrames;
  21411. this.lastDecodedFrames = decodedFrames;
  21412. }
  21413. }
  21414. checkFPSInterval() {
  21415. const video = this.media;
  21416. if (video) {
  21417. if (this.isVideoPlaybackQualityAvailable) {
  21418. const videoPlaybackQuality = video.getVideoPlaybackQuality();
  21419. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  21420. } else {
  21421. // HTMLVideoElement doesn't include the webkit types
  21422. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  21423. }
  21424. }
  21425. }
  21426. }
  21427. const LOGGER_PREFIX = '[eme]';
  21428. /**
  21429. * Controller to deal with encrypted media extensions (EME)
  21430. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  21431. *
  21432. * @class
  21433. * @constructor
  21434. */
  21435. class EMEController {
  21436. constructor(hls) {
  21437. this.hls = void 0;
  21438. this.config = void 0;
  21439. this.media = null;
  21440. this.keyFormatPromise = null;
  21441. this.keySystemAccessPromises = {};
  21442. this._requestLicenseFailureCount = 0;
  21443. this.mediaKeySessions = [];
  21444. this.keyIdToKeySessionPromise = {};
  21445. this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  21446. this.onMediaEncrypted = this._onMediaEncrypted.bind(this);
  21447. this.onWaitingForKey = this._onWaitingForKey.bind(this);
  21448. this.debug = logger.debug.bind(logger, LOGGER_PREFIX);
  21449. this.log = logger.log.bind(logger, LOGGER_PREFIX);
  21450. this.warn = logger.warn.bind(logger, LOGGER_PREFIX);
  21451. this.error = logger.error.bind(logger, LOGGER_PREFIX);
  21452. this.hls = hls;
  21453. this.config = hls.config;
  21454. this.registerListeners();
  21455. }
  21456. destroy() {
  21457. this.unregisterListeners();
  21458. this.onMediaDetached();
  21459. // Remove any references that could be held in config options or callbacks
  21460. const config = this.config;
  21461. config.requestMediaKeySystemAccessFunc = null;
  21462. config.licenseXhrSetup = config.licenseResponseCallback = undefined;
  21463. config.drmSystems = config.drmSystemOptions = {};
  21464. // @ts-ignore
  21465. this.hls = this.onMediaEncrypted = this.onWaitingForKey = this.keyIdToKeySessionPromise = null;
  21466. // @ts-ignore
  21467. this.config = null;
  21468. }
  21469. registerListeners() {
  21470. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21471. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21472. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21473. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21474. }
  21475. unregisterListeners() {
  21476. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21477. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21478. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21479. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21480. }
  21481. getLicenseServerUrl(keySystem) {
  21482. const {
  21483. drmSystems,
  21484. widevineLicenseUrl
  21485. } = this.config;
  21486. const keySystemConfiguration = drmSystems[keySystem];
  21487. if (keySystemConfiguration) {
  21488. return keySystemConfiguration.licenseUrl;
  21489. }
  21490. // For backward compatibility
  21491. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  21492. return widevineLicenseUrl;
  21493. }
  21494. throw new Error(`no license server URL configured for key-system "${keySystem}"`);
  21495. }
  21496. getServerCertificateUrl(keySystem) {
  21497. const {
  21498. drmSystems
  21499. } = this.config;
  21500. const keySystemConfiguration = drmSystems[keySystem];
  21501. if (keySystemConfiguration) {
  21502. return keySystemConfiguration.serverCertificateUrl;
  21503. } else {
  21504. this.log(`No Server Certificate in config.drmSystems["${keySystem}"]`);
  21505. }
  21506. }
  21507. attemptKeySystemAccess(keySystemsToAttempt) {
  21508. const levels = this.hls.levels;
  21509. const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;
  21510. const audioCodecs = levels.map(level => level.audioCodec).filter(uniqueCodec);
  21511. const videoCodecs = levels.map(level => level.videoCodec).filter(uniqueCodec);
  21512. if (audioCodecs.length + videoCodecs.length === 0) {
  21513. videoCodecs.push('avc1.42e01e');
  21514. }
  21515. return new Promise((resolve, reject) => {
  21516. const attempt = keySystems => {
  21517. const keySystem = keySystems.shift();
  21518. this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then(mediaKeys => resolve({
  21519. keySystem,
  21520. mediaKeys
  21521. })).catch(error => {
  21522. if (keySystems.length) {
  21523. attempt(keySystems);
  21524. } else if (error instanceof EMEKeyError) {
  21525. reject(error);
  21526. } else {
  21527. reject(new EMEKeyError({
  21528. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21529. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  21530. error,
  21531. fatal: true
  21532. }, error.message));
  21533. }
  21534. });
  21535. };
  21536. attempt(keySystemsToAttempt);
  21537. });
  21538. }
  21539. requestMediaKeySystemAccess(keySystem, supportedConfigurations) {
  21540. const {
  21541. requestMediaKeySystemAccessFunc
  21542. } = this.config;
  21543. if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {
  21544. let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;
  21545. if (requestMediaKeySystemAccess === null && self.location.protocol === 'http:') {
  21546. errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;
  21547. }
  21548. return Promise.reject(new Error(errMessage));
  21549. }
  21550. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  21551. }
  21552. getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  21553. // This can throw, but is caught in event handler callpath
  21554. const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  21555. const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  21556. let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  21557. if (!keySystemAccess) {
  21558. this.log(`Requesting encrypted media "${keySystem}" key-system access with config: ${JSON.stringify(mediaKeySystemConfigs)}`);
  21559. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  21560. const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  21561. keySystemAccess
  21562. };
  21563. keySystemAccess.catch(error => {
  21564. this.log(`Failed to obtain access to key-system "${keySystem}": ${error}`);
  21565. });
  21566. return keySystemAccess.then(mediaKeySystemAccess => {
  21567. this.log(`Access for key-system "${mediaKeySystemAccess.keySystem}" obtained`);
  21568. const certificateRequest = this.fetchServerCertificate(keySystem);
  21569. this.log(`Create media-keys for "${keySystem}"`);
  21570. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then(mediaKeys => {
  21571. this.log(`Media-keys created for "${keySystem}"`);
  21572. return certificateRequest.then(certificate => {
  21573. if (certificate) {
  21574. return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  21575. }
  21576. return mediaKeys;
  21577. });
  21578. });
  21579. _keySystemAccessPromises.mediaKeys.catch(error => {
  21580. this.error(`Failed to create media-keys for "${keySystem}"}: ${error}`);
  21581. });
  21582. return _keySystemAccessPromises.mediaKeys;
  21583. });
  21584. }
  21585. return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);
  21586. }
  21587. createMediaKeySessionContext({
  21588. decryptdata,
  21589. keySystem,
  21590. mediaKeys
  21591. }) {
  21592. this.log(`Creating key-system session "${keySystem}" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);
  21593. const mediaKeysSession = mediaKeys.createSession();
  21594. const mediaKeySessionContext = {
  21595. decryptdata,
  21596. keySystem,
  21597. mediaKeys,
  21598. mediaKeysSession,
  21599. keyStatus: 'status-pending'
  21600. };
  21601. this.mediaKeySessions.push(mediaKeySessionContext);
  21602. return mediaKeySessionContext;
  21603. }
  21604. renewKeySession(mediaKeySessionContext) {
  21605. const decryptdata = mediaKeySessionContext.decryptdata;
  21606. if (decryptdata.pssh) {
  21607. const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  21608. const keyId = this.getKeyIdString(decryptdata);
  21609. const scheme = 'cenc';
  21610. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, 'expired');
  21611. } else {
  21612. this.warn(`Could not renew expired session. Missing pssh initData.`);
  21613. }
  21614. this.removeSession(mediaKeySessionContext);
  21615. }
  21616. getKeyIdString(decryptdata) {
  21617. if (!decryptdata) {
  21618. throw new Error('Could not read keyId of undefined decryptdata');
  21619. }
  21620. if (decryptdata.keyId === null) {
  21621. throw new Error('keyId is null');
  21622. }
  21623. return Hex.hexDump(decryptdata.keyId);
  21624. }
  21625. updateKeySession(mediaKeySessionContext, data) {
  21626. var _mediaKeySessionConte;
  21627. const keySession = mediaKeySessionContext.mediaKeysSession;
  21628. this.log(`Updating key-session "${keySession.sessionId}" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}
  21629. } (data length: ${data ? data.byteLength : data})`);
  21630. return keySession.update(data);
  21631. }
  21632. selectKeySystemFormat(frag) {
  21633. const keyFormats = Object.keys(frag.levelkeys || {});
  21634. if (!this.keyFormatPromise) {
  21635. this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(', ')}`);
  21636. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  21637. }
  21638. return this.keyFormatPromise;
  21639. }
  21640. getKeyFormatPromise(keyFormats) {
  21641. return new Promise((resolve, reject) => {
  21642. const keySystemsInConfig = getKeySystemsForConfig(this.config);
  21643. const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter(value => !!value && keySystemsInConfig.indexOf(value) !== -1);
  21644. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({
  21645. keySystem
  21646. }) => {
  21647. const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  21648. if (keySystemFormat) {
  21649. resolve(keySystemFormat);
  21650. } else {
  21651. reject(new Error(`Unable to find format for key-system "${keySystem}"`));
  21652. }
  21653. }).catch(reject);
  21654. });
  21655. }
  21656. loadKey(data) {
  21657. const decryptdata = data.keyInfo.decryptdata;
  21658. const keyId = this.getKeyIdString(decryptdata);
  21659. const keyDetails = `(keyId: ${keyId} format: "${decryptdata.keyFormat}" method: ${decryptdata.method} uri: ${decryptdata.uri})`;
  21660. this.log(`Starting session for key ${keyDetails}`);
  21661. let keySessionContextPromise = this.keyIdToKeySessionPromise[keyId];
  21662. if (!keySessionContextPromise) {
  21663. keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = this.getKeySystemForKeyPromise(decryptdata).then(({
  21664. keySystem,
  21665. mediaKeys
  21666. }) => {
  21667. this.throwIfDestroyed();
  21668. this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);
  21669. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  21670. this.throwIfDestroyed();
  21671. const keySessionContext = this.createMediaKeySessionContext({
  21672. keySystem,
  21673. mediaKeys,
  21674. decryptdata
  21675. });
  21676. const scheme = 'cenc';
  21677. return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh, 'playlist-key');
  21678. });
  21679. });
  21680. keySessionContextPromise.catch(error => this.handleError(error));
  21681. }
  21682. return keySessionContextPromise;
  21683. }
  21684. throwIfDestroyed(message = 'Invalid state') {
  21685. if (!this.hls) {
  21686. throw new Error('invalid state');
  21687. }
  21688. }
  21689. handleError(error) {
  21690. if (!this.hls) {
  21691. return;
  21692. }
  21693. this.error(error.message);
  21694. if (error instanceof EMEKeyError) {
  21695. this.hls.trigger(Events.ERROR, error.data);
  21696. } else {
  21697. this.hls.trigger(Events.ERROR, {
  21698. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21699. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  21700. error,
  21701. fatal: true
  21702. });
  21703. }
  21704. }
  21705. getKeySystemForKeyPromise(decryptdata) {
  21706. const keyId = this.getKeyIdString(decryptdata);
  21707. const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  21708. if (!mediaKeySessionContext) {
  21709. const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  21710. const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  21711. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21712. }
  21713. return mediaKeySessionContext;
  21714. }
  21715. getKeySystemSelectionPromise(keySystemsToAttempt) {
  21716. if (!keySystemsToAttempt.length) {
  21717. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  21718. }
  21719. if (keySystemsToAttempt.length === 0) {
  21720. throw new EMEKeyError({
  21721. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21722. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  21723. fatal: true
  21724. }, `Missing key-system license configuration options ${JSON.stringify({
  21725. drmSystems: this.config.drmSystems
  21726. })}`);
  21727. }
  21728. return this.attemptKeySystemAccess(keySystemsToAttempt);
  21729. }
  21730. _onMediaEncrypted(event) {
  21731. const {
  21732. initDataType,
  21733. initData
  21734. } = event;
  21735. this.debug(`"${event.type}" event: init data type: "${initDataType}"`);
  21736. // Ignore event when initData is null
  21737. if (initData === null) {
  21738. return;
  21739. }
  21740. let keyId;
  21741. let keySystemDomain;
  21742. if (initDataType === 'sinf' && this.config.drmSystems[KeySystems.FAIRPLAY]) {
  21743. // Match sinf keyId to playlist skd://keyId=
  21744. const json = bin2str(new Uint8Array(initData));
  21745. try {
  21746. const sinf = base64Decode(JSON.parse(json).sinf);
  21747. const tenc = parseSinf(new Uint8Array(sinf));
  21748. if (!tenc) {
  21749. return;
  21750. }
  21751. keyId = tenc.subarray(8, 24);
  21752. keySystemDomain = KeySystems.FAIRPLAY;
  21753. } catch (error) {
  21754. this.warn('Failed to parse sinf "encrypted" event message initData');
  21755. return;
  21756. }
  21757. } else {
  21758. // Support clear-lead key-session creation (otherwise depend on playlist keys)
  21759. const psshInfo = parsePssh(initData);
  21760. if (psshInfo === null) {
  21761. return;
  21762. }
  21763. if (psshInfo.version === 0 && psshInfo.systemId === KeySystemIds.WIDEVINE && psshInfo.data) {
  21764. keyId = psshInfo.data.subarray(8, 24);
  21765. }
  21766. keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId);
  21767. }
  21768. if (!keySystemDomain || !keyId) {
  21769. return;
  21770. }
  21771. const keyIdHex = Hex.hexDump(keyId);
  21772. const {
  21773. keyIdToKeySessionPromise,
  21774. mediaKeySessions
  21775. } = this;
  21776. let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];
  21777. for (let i = 0; i < mediaKeySessions.length; i++) {
  21778. // Match playlist key
  21779. const keyContext = mediaKeySessions[i];
  21780. const decryptdata = keyContext.decryptdata;
  21781. if (decryptdata.pssh || !decryptdata.keyId) {
  21782. continue;
  21783. }
  21784. const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);
  21785. if (keyIdHex === oldKeyIdHex || decryptdata.uri.replace(/-/g, '').indexOf(keyIdHex) !== -1) {
  21786. keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];
  21787. delete keyIdToKeySessionPromise[oldKeyIdHex];
  21788. decryptdata.pssh = new Uint8Array(initData);
  21789. decryptdata.keyId = keyId;
  21790. keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => {
  21791. return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, 'encrypted-event-key-match');
  21792. });
  21793. break;
  21794. }
  21795. }
  21796. if (!keySessionContextPromise) {
  21797. // Clear-lead key (not encountered in playlist)
  21798. keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = this.getKeySystemSelectionPromise([keySystemDomain]).then(({
  21799. keySystem,
  21800. mediaKeys
  21801. }) => {
  21802. var _keySystemToKeySystem;
  21803. this.throwIfDestroyed();
  21804. const decryptdata = new LevelKey('ISO-23001-7', keyIdHex, (_keySystemToKeySystem = keySystemDomainToKeySystemFormat(keySystem)) != null ? _keySystemToKeySystem : '');
  21805. decryptdata.pssh = new Uint8Array(initData);
  21806. decryptdata.keyId = keyId;
  21807. return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {
  21808. this.throwIfDestroyed();
  21809. const keySessionContext = this.createMediaKeySessionContext({
  21810. decryptdata,
  21811. keySystem,
  21812. mediaKeys
  21813. });
  21814. return this.generateRequestWithPreferredKeySession(keySessionContext, initDataType, initData, 'encrypted-event-no-match');
  21815. });
  21816. });
  21817. }
  21818. keySessionContextPromise.catch(error => this.handleError(error));
  21819. }
  21820. _onWaitingForKey(event) {
  21821. this.log(`"${event.type}" event`);
  21822. }
  21823. attemptSetMediaKeys(keySystem, mediaKeys) {
  21824. const queue = this.setMediaKeysQueue.slice();
  21825. this.log(`Setting media-keys for "${keySystem}"`);
  21826. // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations
  21827. // can be queued for execution for multiple key sessions.
  21828. const setMediaKeysPromise = Promise.all(queue).then(() => {
  21829. if (!this.media) {
  21830. throw new Error('Attempted to set mediaKeys without media element attached');
  21831. }
  21832. return this.media.setMediaKeys(mediaKeys);
  21833. });
  21834. this.setMediaKeysQueue.push(setMediaKeysPromise);
  21835. return setMediaKeysPromise.then(() => {
  21836. this.log(`Media-keys set for "${keySystem}"`);
  21837. queue.push(setMediaKeysPromise);
  21838. this.setMediaKeysQueue = this.setMediaKeysQueue.filter(p => queue.indexOf(p) === -1);
  21839. });
  21840. }
  21841. generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  21842. var _this$config$drmSyste, _this$config$drmSyste2;
  21843. 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;
  21844. if (generateRequestFilter) {
  21845. try {
  21846. const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  21847. if (!mappedInitData) {
  21848. throw new Error('Invalid response from configured generateRequest filter');
  21849. }
  21850. initDataType = mappedInitData.initDataType;
  21851. initData = context.decryptdata.pssh = mappedInitData.initData ? new Uint8Array(mappedInitData.initData) : null;
  21852. } catch (error) {
  21853. var _this$hls;
  21854. this.warn(error.message);
  21855. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  21856. throw error;
  21857. }
  21858. }
  21859. }
  21860. if (initData === null) {
  21861. this.log(`Skipping key-session request for "${reason}" (no initData)`);
  21862. return Promise.resolve(context);
  21863. }
  21864. const keyId = this.getKeyIdString(context.decryptdata);
  21865. this.log(`Generating key-session request for "${reason}": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);
  21866. const licenseStatus = new EventEmitter();
  21867. const onmessage = context._onmessage = event => {
  21868. const keySession = context.mediaKeysSession;
  21869. if (!keySession) {
  21870. licenseStatus.emit('error', new Error('invalid state'));
  21871. return;
  21872. }
  21873. const {
  21874. messageType,
  21875. message
  21876. } = event;
  21877. this.log(`"${messageType}" message event for session "${keySession.sessionId}" message size: ${message.byteLength}`);
  21878. if (messageType === 'license-request' || messageType === 'license-renewal') {
  21879. this.renewLicense(context, message).catch(error => {
  21880. this.handleError(error);
  21881. licenseStatus.emit('error', error);
  21882. });
  21883. } else if (messageType === 'license-release') {
  21884. if (context.keySystem === KeySystems.FAIRPLAY) {
  21885. this.updateKeySession(context, strToUtf8array('acknowledged'));
  21886. this.removeSession(context);
  21887. }
  21888. } else {
  21889. this.warn(`unhandled media key message type "${messageType}"`);
  21890. }
  21891. };
  21892. const onkeystatuseschange = context._onkeystatuseschange = event => {
  21893. const keySession = context.mediaKeysSession;
  21894. if (!keySession) {
  21895. licenseStatus.emit('error', new Error('invalid state'));
  21896. return;
  21897. }
  21898. this.onKeyStatusChange(context);
  21899. const keyStatus = context.keyStatus;
  21900. licenseStatus.emit('keyStatus', keyStatus);
  21901. if (keyStatus === 'expired') {
  21902. this.warn(`${context.keySystem} expired for key ${keyId}`);
  21903. this.renewKeySession(context);
  21904. }
  21905. };
  21906. context.mediaKeysSession.addEventListener('message', onmessage);
  21907. context.mediaKeysSession.addEventListener('keystatuseschange', onkeystatuseschange);
  21908. const keyUsablePromise = new Promise((resolve, reject) => {
  21909. licenseStatus.on('error', reject);
  21910. licenseStatus.on('keyStatus', keyStatus => {
  21911. if (keyStatus.startsWith('usable')) {
  21912. resolve();
  21913. } else if (keyStatus === 'output-restricted') {
  21914. reject(new EMEKeyError({
  21915. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21916. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  21917. fatal: false
  21918. }, 'HDCP level output restricted'));
  21919. } else if (keyStatus === 'internal-error') {
  21920. reject(new EMEKeyError({
  21921. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21922. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  21923. fatal: true
  21924. }, `key status changed to "${keyStatus}"`));
  21925. } else if (keyStatus === 'expired') {
  21926. reject(new Error('key expired while generating request'));
  21927. } else {
  21928. this.warn(`unhandled key status change "${keyStatus}"`);
  21929. }
  21930. });
  21931. });
  21932. return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {
  21933. var _context$mediaKeysSes;
  21934. this.log(`Request generated for key-session "${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}" keyId: ${keyId}`);
  21935. }).catch(error => {
  21936. throw new EMEKeyError({
  21937. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21938. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  21939. error,
  21940. fatal: false
  21941. }, `Error generating key-session request: ${error}`);
  21942. }).then(() => keyUsablePromise).catch(error => {
  21943. licenseStatus.removeAllListeners();
  21944. this.removeSession(context);
  21945. throw error;
  21946. }).then(() => {
  21947. licenseStatus.removeAllListeners();
  21948. return context;
  21949. });
  21950. }
  21951. onKeyStatusChange(mediaKeySessionContext) {
  21952. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status, keyId) => {
  21953. 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}`);
  21954. mediaKeySessionContext.keyStatus = status;
  21955. });
  21956. }
  21957. fetchServerCertificate(keySystem) {
  21958. const config = this.config;
  21959. const Loader = config.loader;
  21960. const certLoader = new Loader(config);
  21961. const url = this.getServerCertificateUrl(keySystem);
  21962. if (!url) {
  21963. return Promise.resolve();
  21964. }
  21965. this.log(`Fetching server certificate for "${keySystem}"`);
  21966. return new Promise((resolve, reject) => {
  21967. const loaderContext = {
  21968. responseType: 'arraybuffer',
  21969. url
  21970. };
  21971. const loadPolicy = config.certLoadPolicy.default;
  21972. const loaderConfig = {
  21973. loadPolicy,
  21974. timeout: loadPolicy.maxLoadTimeMs,
  21975. maxRetry: 0,
  21976. retryDelay: 0,
  21977. maxRetryDelay: 0
  21978. };
  21979. const loaderCallbacks = {
  21980. onSuccess: (response, stats, context, networkDetails) => {
  21981. resolve(response.data);
  21982. },
  21983. onError: (response, contex, networkDetails, stats) => {
  21984. reject(new EMEKeyError({
  21985. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21986. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  21987. fatal: true,
  21988. networkDetails,
  21989. response: _objectSpread2({
  21990. url: loaderContext.url,
  21991. data: undefined
  21992. }, response)
  21993. }, `"${keySystem}" certificate request failed (${url}). Status: ${response.code} (${response.text})`));
  21994. },
  21995. onTimeout: (stats, context, networkDetails) => {
  21996. reject(new EMEKeyError({
  21997. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21998. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  21999. fatal: true,
  22000. networkDetails,
  22001. response: {
  22002. url: loaderContext.url,
  22003. data: undefined
  22004. }
  22005. }, `"${keySystem}" certificate request timed out (${url})`));
  22006. },
  22007. onAbort: (stats, context, networkDetails) => {
  22008. reject(new Error('aborted'));
  22009. }
  22010. };
  22011. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  22012. });
  22013. }
  22014. setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  22015. return new Promise((resolve, reject) => {
  22016. mediaKeys.setServerCertificate(cert).then(success => {
  22017. this.log(`setServerCertificate ${success ? 'success' : 'not supported by CDM'} (${cert == null ? void 0 : cert.byteLength}) on "${keySystem}"`);
  22018. resolve(mediaKeys);
  22019. }).catch(error => {
  22020. reject(new EMEKeyError({
  22021. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22022. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  22023. error,
  22024. fatal: true
  22025. }, error.message));
  22026. });
  22027. });
  22028. }
  22029. renewLicense(context, keyMessage) {
  22030. return this.requestLicense(context, new Uint8Array(keyMessage)).then(data => {
  22031. return this.updateKeySession(context, new Uint8Array(data)).catch(error => {
  22032. throw new EMEKeyError({
  22033. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22034. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  22035. error,
  22036. fatal: true
  22037. }, error.message);
  22038. });
  22039. });
  22040. }
  22041. unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  22042. // On Edge, the raw license message is UTF-16-encoded XML. We need
  22043. // to unpack the Challenge element (base64-encoded string containing the
  22044. // actual license request) and any HttpHeader elements (sent as request
  22045. // headers).
  22046. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  22047. const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  22048. if (!xmlString.includes('PlayReadyKeyMessage')) {
  22049. // This does not appear to be a wrapped message as on Edge. Some
  22050. // clients do not need this unwrapping, so we will assume this is one of
  22051. // them. Note that "xml" at this point probably looks like random
  22052. // garbage, since we interpreted UTF-8 as UTF-16.
  22053. xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
  22054. return licenseChallenge;
  22055. }
  22056. const keyMessageXml = new DOMParser().parseFromString(xmlString, 'application/xml');
  22057. // Set request headers.
  22058. const headers = keyMessageXml.querySelectorAll('HttpHeader');
  22059. if (headers.length > 0) {
  22060. let header;
  22061. for (let i = 0, len = headers.length; i < len; i++) {
  22062. var _header$querySelector, _header$querySelector2;
  22063. header = headers[i];
  22064. const name = (_header$querySelector = header.querySelector('name')) == null ? void 0 : _header$querySelector.textContent;
  22065. const value = (_header$querySelector2 = header.querySelector('value')) == null ? void 0 : _header$querySelector2.textContent;
  22066. if (name && value) {
  22067. xhr.setRequestHeader(name, value);
  22068. }
  22069. }
  22070. }
  22071. const challengeElement = keyMessageXml.querySelector('Challenge');
  22072. const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  22073. if (!challengeText) {
  22074. throw new Error(`Cannot find <Challenge> in key message`);
  22075. }
  22076. return strToUtf8array(atob(challengeText));
  22077. }
  22078. setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  22079. const licenseXhrSetup = this.config.licenseXhrSetup;
  22080. if (!licenseXhrSetup) {
  22081. xhr.open('POST', url, true);
  22082. return Promise.resolve({
  22083. xhr,
  22084. licenseChallenge
  22085. });
  22086. }
  22087. return Promise.resolve().then(() => {
  22088. if (!keysListItem.decryptdata) {
  22089. throw new Error('Key removed');
  22090. }
  22091. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  22092. }).catch(error => {
  22093. if (!keysListItem.decryptdata) {
  22094. // Key session removed. Cancel license request.
  22095. throw error;
  22096. }
  22097. // let's try to open before running setup
  22098. xhr.open('POST', url, true);
  22099. return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);
  22100. }).then(licenseXhrSetupResult => {
  22101. // if licenseXhrSetup did not yet call open, let's do it now
  22102. if (!xhr.readyState) {
  22103. xhr.open('POST', url, true);
  22104. }
  22105. const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  22106. return {
  22107. xhr,
  22108. licenseChallenge: finalLicenseChallenge
  22109. };
  22110. });
  22111. }
  22112. requestLicense(keySessionContext, licenseChallenge) {
  22113. const keyLoadPolicy = this.config.keyLoadPolicy.default;
  22114. return new Promise((resolve, reject) => {
  22115. const url = this.getLicenseServerUrl(keySessionContext.keySystem);
  22116. this.log(`Sending license request to URL: ${url}`);
  22117. const xhr = new XMLHttpRequest();
  22118. xhr.responseType = 'arraybuffer';
  22119. xhr.onreadystatechange = () => {
  22120. if (!this.hls || !keySessionContext.mediaKeysSession) {
  22121. return reject(new Error('invalid state'));
  22122. }
  22123. if (xhr.readyState === 4) {
  22124. if (xhr.status === 200) {
  22125. this._requestLicenseFailureCount = 0;
  22126. let data = xhr.response;
  22127. this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);
  22128. const licenseResponseCallback = this.config.licenseResponseCallback;
  22129. if (licenseResponseCallback) {
  22130. try {
  22131. data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);
  22132. } catch (error) {
  22133. this.error(error);
  22134. }
  22135. }
  22136. resolve(data);
  22137. } else {
  22138. const retryConfig = keyLoadPolicy.errorRetry;
  22139. const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  22140. this._requestLicenseFailureCount++;
  22141. if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  22142. reject(new EMEKeyError({
  22143. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22144. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  22145. fatal: true,
  22146. networkDetails: xhr,
  22147. response: {
  22148. url,
  22149. data: undefined,
  22150. code: xhr.status,
  22151. text: xhr.statusText
  22152. }
  22153. }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));
  22154. } else {
  22155. const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;
  22156. this.warn(`Retrying license request, ${attemptsLeft} attempts left`);
  22157. this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  22158. }
  22159. }
  22160. }
  22161. };
  22162. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22163. keySessionContext.licenseXhr.abort();
  22164. }
  22165. keySessionContext.licenseXhr = xhr;
  22166. this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({
  22167. xhr,
  22168. licenseChallenge
  22169. }) => {
  22170. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  22171. licenseChallenge = this.unpackPlayReadyKeyMessage(xhr, licenseChallenge);
  22172. }
  22173. xhr.send(licenseChallenge);
  22174. });
  22175. });
  22176. }
  22177. onMediaAttached(event, data) {
  22178. if (!this.config.emeEnabled) {
  22179. return;
  22180. }
  22181. const media = data.media;
  22182. // keep reference of media
  22183. this.media = media;
  22184. media.addEventListener('encrypted', this.onMediaEncrypted);
  22185. media.addEventListener('waitingforkey', this.onWaitingForKey);
  22186. }
  22187. onMediaDetached() {
  22188. const media = this.media;
  22189. const mediaKeysList = this.mediaKeySessions;
  22190. if (media) {
  22191. media.removeEventListener('encrypted', this.onMediaEncrypted);
  22192. media.removeEventListener('waitingforkey', this.onWaitingForKey);
  22193. this.media = null;
  22194. }
  22195. this._requestLicenseFailureCount = 0;
  22196. this.setMediaKeysQueue = [];
  22197. this.mediaKeySessions = [];
  22198. this.keyIdToKeySessionPromise = {};
  22199. LevelKey.clearKeyUriToKeyIdMap();
  22200. // Close all sessions and remove media keys from the video element.
  22201. const keySessionCount = mediaKeysList.length;
  22202. EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map(mediaKeySessionContext => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : media.setMediaKeys(null).catch(error => {
  22203. this.log(`Could not clear media keys: ${error}`);
  22204. }))).then(() => {
  22205. if (keySessionCount) {
  22206. this.log('finished closing key sessions and clearing media keys');
  22207. mediaKeysList.length = 0;
  22208. }
  22209. }).catch(error => {
  22210. this.log(`Could not close sessions and clear media keys: ${error}`);
  22211. });
  22212. }
  22213. onManifestLoading() {
  22214. this.keyFormatPromise = null;
  22215. }
  22216. onManifestLoaded(event, {
  22217. sessionKeys
  22218. }) {
  22219. if (!sessionKeys || !this.config.emeEnabled) {
  22220. return;
  22221. }
  22222. if (!this.keyFormatPromise) {
  22223. const keyFormats = sessionKeys.reduce((formats, sessionKey) => {
  22224. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  22225. formats.push(sessionKey.keyFormat);
  22226. }
  22227. return formats;
  22228. }, []);
  22229. this.log(`Selecting key-system from session-keys ${keyFormats.join(', ')}`);
  22230. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  22231. }
  22232. }
  22233. removeSession(mediaKeySessionContext) {
  22234. const {
  22235. mediaKeysSession,
  22236. licenseXhr
  22237. } = mediaKeySessionContext;
  22238. if (mediaKeysSession) {
  22239. this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);
  22240. if (mediaKeySessionContext._onmessage) {
  22241. mediaKeysSession.removeEventListener('message', mediaKeySessionContext._onmessage);
  22242. mediaKeySessionContext._onmessage = undefined;
  22243. }
  22244. if (mediaKeySessionContext._onkeystatuseschange) {
  22245. mediaKeysSession.removeEventListener('keystatuseschange', mediaKeySessionContext._onkeystatuseschange);
  22246. mediaKeySessionContext._onkeystatuseschange = undefined;
  22247. }
  22248. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22249. licenseXhr.abort();
  22250. }
  22251. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = undefined;
  22252. const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  22253. if (index > -1) {
  22254. this.mediaKeySessions.splice(index, 1);
  22255. }
  22256. return mediaKeysSession.remove().catch(error => {
  22257. this.log(`Could not remove session: ${error}`);
  22258. }).then(() => {
  22259. return mediaKeysSession.close();
  22260. }).catch(error => {
  22261. this.log(`Could not close session: ${error}`);
  22262. });
  22263. }
  22264. }
  22265. }
  22266. EMEController.CDMCleanupPromise = void 0;
  22267. class EMEKeyError extends Error {
  22268. constructor(data, message) {
  22269. super(message);
  22270. this.data = void 0;
  22271. data.error || (data.error = new Error(message));
  22272. this.data = data;
  22273. data.err = data.error;
  22274. }
  22275. }
  22276. /**
  22277. * Common Media Object Type
  22278. *
  22279. * @group CMCD
  22280. * @group CMSD
  22281. *
  22282. * @beta
  22283. */
  22284. var CmObjectType;
  22285. (function (CmObjectType) {
  22286. /**
  22287. * text file, such as a manifest or playlist
  22288. */
  22289. CmObjectType["MANIFEST"] = "m";
  22290. /**
  22291. * audio only
  22292. */
  22293. CmObjectType["AUDIO"] = "a";
  22294. /**
  22295. * video only
  22296. */
  22297. CmObjectType["VIDEO"] = "v";
  22298. /**
  22299. * muxed audio and video
  22300. */
  22301. CmObjectType["MUXED"] = "av";
  22302. /**
  22303. * init segment
  22304. */
  22305. CmObjectType["INIT"] = "i";
  22306. /**
  22307. * caption or subtitle
  22308. */
  22309. CmObjectType["CAPTION"] = "c";
  22310. /**
  22311. * ISOBMFF timed text track
  22312. */
  22313. CmObjectType["TIMED_TEXT"] = "tt";
  22314. /**
  22315. * cryptographic key, license or certificate.
  22316. */
  22317. CmObjectType["KEY"] = "k";
  22318. /**
  22319. * other
  22320. */
  22321. CmObjectType["OTHER"] = "o";
  22322. })(CmObjectType || (CmObjectType = {}));
  22323. /**
  22324. * Common Media Streaming Format
  22325. *
  22326. * @group CMCD
  22327. * @group CMSD
  22328. *
  22329. * @beta
  22330. */
  22331. var CmStreamingFormat;
  22332. (function (CmStreamingFormat) {
  22333. /**
  22334. * MPEG DASH
  22335. */
  22336. CmStreamingFormat["DASH"] = "d";
  22337. /**
  22338. * HTTP Live Streaming (HLS)
  22339. */
  22340. CmStreamingFormat["HLS"] = "h";
  22341. /**
  22342. * Smooth Streaming
  22343. */
  22344. CmStreamingFormat["SMOOTH"] = "s";
  22345. /**
  22346. * Other
  22347. */
  22348. CmStreamingFormat["OTHER"] = "o";
  22349. })(CmStreamingFormat || (CmStreamingFormat = {}));
  22350. /**
  22351. * CMCD header fields.
  22352. *
  22353. * @group CMCD
  22354. *
  22355. * @beta
  22356. */
  22357. var CmcdHeaderField;
  22358. (function (CmcdHeaderField) {
  22359. /**
  22360. * keys whose values vary with the object being requested.
  22361. */
  22362. CmcdHeaderField["OBJECT"] = "CMCD-Object";
  22363. /**
  22364. * keys whose values vary with each request.
  22365. */
  22366. CmcdHeaderField["REQUEST"] = "CMCD-Request";
  22367. /**
  22368. * keys whose values are expected to be invariant over the life of the session.
  22369. */
  22370. CmcdHeaderField["SESSION"] = "CMCD-Session";
  22371. /**
  22372. * keys whose values do not vary with every request or object.
  22373. */
  22374. CmcdHeaderField["STATUS"] = "CMCD-Status";
  22375. })(CmcdHeaderField || (CmcdHeaderField = {}));
  22376. /**
  22377. * The map of CMCD header fields to official CMCD keys.
  22378. *
  22379. * @internal
  22380. *
  22381. * @group CMCD
  22382. */
  22383. const CmcdHeaderMap = {
  22384. [CmcdHeaderField.OBJECT]: ['br', 'd', 'ot', 'tb'],
  22385. [CmcdHeaderField.REQUEST]: ['bl', 'dl', 'mtp', 'nor', 'nrr', 'su'],
  22386. [CmcdHeaderField.SESSION]: ['cid', 'pr', 'sf', 'sid', 'st', 'v'],
  22387. [CmcdHeaderField.STATUS]: ['bs', 'rtp']
  22388. };
  22389. /**
  22390. * Structured Field Item
  22391. *
  22392. * @group Structured Field
  22393. *
  22394. * @beta
  22395. */
  22396. class SfItem {
  22397. constructor(value, params) {
  22398. this.value = void 0;
  22399. this.params = void 0;
  22400. if (Array.isArray(value)) {
  22401. value = value.map(v => v instanceof SfItem ? v : new SfItem(v));
  22402. }
  22403. this.value = value;
  22404. this.params = params;
  22405. }
  22406. }
  22407. /**
  22408. * A class to represent structured field tokens when `Symbol` is not available.
  22409. *
  22410. * @group Structured Field
  22411. *
  22412. * @beta
  22413. */
  22414. class SfToken {
  22415. constructor(description) {
  22416. this.description = void 0;
  22417. this.description = description;
  22418. }
  22419. }
  22420. const DICT = 'Dict';
  22421. function format(value) {
  22422. if (Array.isArray(value)) {
  22423. return JSON.stringify(value);
  22424. }
  22425. if (value instanceof Map) {
  22426. return 'Map{}';
  22427. }
  22428. if (value instanceof Set) {
  22429. return 'Set{}';
  22430. }
  22431. if (typeof value === 'object') {
  22432. return JSON.stringify(value);
  22433. }
  22434. return String(value);
  22435. }
  22436. function throwError(action, src, type, cause) {
  22437. return new Error(`failed to ${action} "${format(src)}" as ${type}`, {
  22438. cause
  22439. });
  22440. }
  22441. const BARE_ITEM = 'Bare Item';
  22442. const BOOLEAN = 'Boolean';
  22443. const BYTES = 'Byte Sequence';
  22444. const DECIMAL = 'Decimal';
  22445. const INTEGER = 'Integer';
  22446. function isInvalidInt(value) {
  22447. return value < -999999999999999 || 999999999999999 < value;
  22448. }
  22449. const STRING_REGEX = /[\x00-\x1f\x7f]+/; // eslint-disable-line no-control-regex
  22450. const TOKEN = 'Token';
  22451. const KEY = 'Key';
  22452. function serializeError(src, type, cause) {
  22453. return throwError('serialize', src, type, cause);
  22454. }
  22455. // 4.1.9. Serializing a Boolean
  22456. //
  22457. // Given a Boolean as input_boolean, return an ASCII string suitable for
  22458. // use in a HTTP field value.
  22459. //
  22460. // 1. If input_boolean is not a boolean, fail serialization.
  22461. //
  22462. // 2. Let output be an empty string.
  22463. //
  22464. // 3. Append "?" to output.
  22465. //
  22466. // 4. If input_boolean is true, append "1" to output.
  22467. //
  22468. // 5. If input_boolean is false, append "0" to output.
  22469. //
  22470. // 6. Return output.
  22471. function serializeBoolean(value) {
  22472. if (typeof value !== 'boolean') {
  22473. throw serializeError(value, BOOLEAN);
  22474. }
  22475. return value ? '?1' : '?0';
  22476. }
  22477. /**
  22478. * Encodes binary data to base64
  22479. *
  22480. * @param binary - The binary data to encode
  22481. * @returns The base64 encoded string
  22482. *
  22483. * @group Utils
  22484. *
  22485. * @beta
  22486. */
  22487. function base64encode(binary) {
  22488. return btoa(String.fromCharCode(...binary));
  22489. }
  22490. // 4.1.8. Serializing a Byte Sequence
  22491. //
  22492. // Given a Byte Sequence as input_bytes, return an ASCII string suitable
  22493. // for use in a HTTP field value.
  22494. //
  22495. // 1. If input_bytes is not a sequence of bytes, fail serialization.
  22496. //
  22497. // 2. Let output be an empty string.
  22498. //
  22499. // 3. Append ":" to output.
  22500. //
  22501. // 4. Append the result of base64-encoding input_bytes as per
  22502. // [RFC4648], Section 4, taking account of the requirements below.
  22503. //
  22504. // 5. Append ":" to output.
  22505. //
  22506. // 6. Return output.
  22507. //
  22508. // The encoded data is required to be padded with "=", as per [RFC4648],
  22509. // Section 3.2.
  22510. //
  22511. // Likewise, encoded data SHOULD have pad bits set to zero, as per
  22512. // [RFC4648], Section 3.5, unless it is not possible to do so due to
  22513. // implementation constraints.
  22514. function serializeByteSequence(value) {
  22515. if (ArrayBuffer.isView(value) === false) {
  22516. throw serializeError(value, BYTES);
  22517. }
  22518. return `:${base64encode(value)}:`;
  22519. }
  22520. // 4.1.4. Serializing an Integer
  22521. //
  22522. // Given an Integer as input_integer, return an ASCII string suitable
  22523. // for use in a HTTP field value.
  22524. //
  22525. // 1. If input_integer is not an integer in the range of
  22526. // -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
  22527. // serialization.
  22528. //
  22529. // 2. Let output be an empty string.
  22530. //
  22531. // 3. If input_integer is less than (but not equal to) 0, append "-" to
  22532. // output.
  22533. //
  22534. // 4. Append input_integer's numeric value represented in base 10 using
  22535. // only decimal digits to output.
  22536. //
  22537. // 5. Return output.
  22538. function serializeInteger(value) {
  22539. if (isInvalidInt(value)) {
  22540. throw serializeError(value, INTEGER);
  22541. }
  22542. return value.toString();
  22543. }
  22544. // 4.1.10. Serializing a Date
  22545. //
  22546. // Given a Date as input_integer, return an ASCII string suitable for
  22547. // use in an HTTP field value.
  22548. // 1. Let output be "@".
  22549. // 2. Append to output the result of running Serializing an Integer
  22550. // with input_date (Section 4.1.4).
  22551. // 3. Return output.
  22552. function serializeDate(value) {
  22553. return `@${serializeInteger(value.getTime() / 1000)}`;
  22554. }
  22555. /**
  22556. * This implements the rounding procedure described in step 2 of the "Serializing a Decimal" specification.
  22557. * This rounding style is known as "even rounding", "banker's rounding", or "commercial rounding".
  22558. *
  22559. * @param value - The value to round
  22560. * @param precision - The number of decimal places to round to
  22561. * @returns The rounded value
  22562. *
  22563. * @group Utils
  22564. *
  22565. * @beta
  22566. */
  22567. function roundToEven(value, precision) {
  22568. if (value < 0) {
  22569. return -roundToEven(-value, precision);
  22570. }
  22571. const decimalShift = Math.pow(10, precision);
  22572. const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  22573. if (isEquidistant) {
  22574. // If the tail of the decimal place is 'equidistant' we round to the nearest even value
  22575. const flooredValue = Math.floor(value * decimalShift);
  22576. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  22577. } else {
  22578. // Otherwise, proceed as normal
  22579. return Math.round(value * decimalShift) / decimalShift;
  22580. }
  22581. }
  22582. // 4.1.5. Serializing a Decimal
  22583. //
  22584. // Given a decimal number as input_decimal, return an ASCII string
  22585. // suitable for use in a HTTP field value.
  22586. //
  22587. // 1. If input_decimal is not a decimal number, fail serialization.
  22588. //
  22589. // 2. If input_decimal has more than three significant digits to the
  22590. // right of the decimal point, round it to three decimal places,
  22591. // rounding the final digit to the nearest value, or to the even
  22592. // value if it is equidistant.
  22593. //
  22594. // 3. If input_decimal has more than 12 significant digits to the left
  22595. // of the decimal point after rounding, fail serialization.
  22596. //
  22597. // 4. Let output be an empty string.
  22598. //
  22599. // 5. If input_decimal is less than (but not equal to) 0, append "-"
  22600. // to output.
  22601. //
  22602. // 6. Append input_decimal's integer component represented in base 10
  22603. // (using only decimal digits) to output; if it is zero, append
  22604. // "0".
  22605. //
  22606. // 7. Append "." to output.
  22607. //
  22608. // 8. If input_decimal's fractional component is zero, append "0" to
  22609. // output.
  22610. //
  22611. // 9. Otherwise, append the significant digits of input_decimal's
  22612. // fractional component represented in base 10 (using only decimal
  22613. // digits) to output.
  22614. //
  22615. // 10. Return output.
  22616. function serializeDecimal(value) {
  22617. const roundedValue = roundToEven(value, 3); // round to 3 decimal places
  22618. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  22619. throw serializeError(value, DECIMAL);
  22620. }
  22621. const stringValue = roundedValue.toString();
  22622. return stringValue.includes('.') ? stringValue : `${stringValue}.0`;
  22623. }
  22624. const STRING = 'String';
  22625. // 4.1.6. Serializing a String
  22626. //
  22627. // Given a String as input_string, return an ASCII string suitable for
  22628. // use in a HTTP field value.
  22629. //
  22630. // 1. Convert input_string into a sequence of ASCII characters; if
  22631. // conversion fails, fail serialization.
  22632. //
  22633. // 2. If input_string contains characters in the range %x00-1f or %x7f
  22634. // (i.e., not in VCHAR or SP), fail serialization.
  22635. //
  22636. // 3. Let output be the string DQUOTE.
  22637. //
  22638. // 4. For each character char in input_string:
  22639. //
  22640. // 1. If char is "\" or DQUOTE:
  22641. //
  22642. // 1. Append "\" to output.
  22643. //
  22644. // 2. Append char to output.
  22645. //
  22646. // 5. Append DQUOTE to output.
  22647. //
  22648. // 6. Return output.
  22649. function serializeString(value) {
  22650. if (STRING_REGEX.test(value)) {
  22651. throw serializeError(value, STRING);
  22652. }
  22653. return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`)}"`;
  22654. }
  22655. function symbolToStr(symbol) {
  22656. return symbol.description || symbol.toString().slice(7, -1);
  22657. }
  22658. function serializeToken(token) {
  22659. const value = symbolToStr(token);
  22660. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  22661. throw serializeError(value, TOKEN);
  22662. }
  22663. return value;
  22664. }
  22665. // 4.1.3.1. Serializing a Bare Item
  22666. //
  22667. // Given an Item as input_item, return an ASCII string suitable for use
  22668. // in a HTTP field value.
  22669. //
  22670. // 1. If input_item is an Integer, return the result of running
  22671. // Serializing an Integer (Section 4.1.4) with input_item.
  22672. //
  22673. // 2. If input_item is a Decimal, return the result of running
  22674. // Serializing a Decimal (Section 4.1.5) with input_item.
  22675. //
  22676. // 3. If input_item is a String, return the result of running
  22677. // Serializing a String (Section 4.1.6) with input_item.
  22678. //
  22679. // 4. If input_item is a Token, return the result of running
  22680. // Serializing a Token (Section 4.1.7) with input_item.
  22681. //
  22682. // 5. If input_item is a Boolean, return the result of running
  22683. // Serializing a Boolean (Section 4.1.9) with input_item.
  22684. //
  22685. // 6. If input_item is a Byte Sequence, return the result of running
  22686. // Serializing a Byte Sequence (Section 4.1.8) with input_item.
  22687. //
  22688. // 7. If input_item is a Date, return the result of running Serializing
  22689. // a Date (Section 4.1.10) with input_item.
  22690. //
  22691. // 8. Otherwise, fail serialization.
  22692. function serializeBareItem(value) {
  22693. switch (typeof value) {
  22694. case 'number':
  22695. if (!isFiniteNumber(value)) {
  22696. throw serializeError(value, BARE_ITEM);
  22697. }
  22698. if (Number.isInteger(value)) {
  22699. return serializeInteger(value);
  22700. }
  22701. return serializeDecimal(value);
  22702. case 'string':
  22703. return serializeString(value);
  22704. case 'symbol':
  22705. return serializeToken(value);
  22706. case 'boolean':
  22707. return serializeBoolean(value);
  22708. case 'object':
  22709. if (value instanceof Date) {
  22710. return serializeDate(value);
  22711. }
  22712. if (value instanceof Uint8Array) {
  22713. return serializeByteSequence(value);
  22714. }
  22715. if (value instanceof SfToken) {
  22716. return serializeToken(value);
  22717. }
  22718. default:
  22719. // fail
  22720. throw serializeError(value, BARE_ITEM);
  22721. }
  22722. }
  22723. // 4.1.1.3. Serializing a Key
  22724. //
  22725. // Given a key as input_key, return an ASCII string suitable for use in
  22726. // a HTTP field value.
  22727. //
  22728. // 1. Convert input_key into a sequence of ASCII characters; if
  22729. // conversion fails, fail serialization.
  22730. //
  22731. // 2. If input_key contains characters not in lcalpha, DIGIT, "_", "-",
  22732. // ".", or "*" fail serialization.
  22733. //
  22734. // 3. If the first character of input_key is not lcalpha or "*", fail
  22735. // serialization.
  22736. //
  22737. // 4. Let output be an empty string.
  22738. //
  22739. // 5. Append input_key to output.
  22740. //
  22741. // 6. Return output.
  22742. function serializeKey(value) {
  22743. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  22744. throw serializeError(value, KEY);
  22745. }
  22746. return value;
  22747. }
  22748. // 4.1.1.2. Serializing Parameters
  22749. //
  22750. // Given an ordered Dictionary as input_parameters (each member having a
  22751. // param_name and a param_value), return an ASCII string suitable for
  22752. // use in a HTTP field value.
  22753. //
  22754. // 1. Let output be an empty string.
  22755. //
  22756. // 2. For each param_name with a value of param_value in
  22757. // input_parameters:
  22758. //
  22759. // 1. Append ";" to output.
  22760. //
  22761. // 2. Append the result of running Serializing a Key
  22762. // (Section 4.1.1.3) with param_name to output.
  22763. //
  22764. // 3. If param_value is not Boolean true:
  22765. //
  22766. // 1. Append "=" to output.
  22767. //
  22768. // 2. Append the result of running Serializing a bare Item
  22769. // (Section 4.1.3.1) with param_value to output.
  22770. //
  22771. // 3. Return output.
  22772. function serializeParams(params) {
  22773. if (params == null) {
  22774. return '';
  22775. }
  22776. return Object.entries(params).map(([key, value]) => {
  22777. if (value === true) {
  22778. return `;${serializeKey(key)}`; // omit true
  22779. }
  22780. return `;${serializeKey(key)}=${serializeBareItem(value)}`;
  22781. }).join('');
  22782. }
  22783. // 4.1.3. Serializing an Item
  22784. //
  22785. // Given an Item as bare_item and Parameters as item_parameters, return
  22786. // an ASCII string suitable for use in a HTTP field value.
  22787. //
  22788. // 1. Let output be an empty string.
  22789. //
  22790. // 2. Append the result of running Serializing a Bare Item
  22791. // Section 4.1.3.1 with bare_item to output.
  22792. //
  22793. // 3. Append the result of running Serializing Parameters
  22794. // Section 4.1.1.2 with item_parameters to output.
  22795. //
  22796. // 4. Return output.
  22797. function serializeItem(value) {
  22798. if (value instanceof SfItem) {
  22799. return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;
  22800. } else {
  22801. return serializeBareItem(value);
  22802. }
  22803. }
  22804. // 4.1.1.1. Serializing an Inner List
  22805. //
  22806. // Given an array of (member_value, parameters) tuples as inner_list,
  22807. // and parameters as list_parameters, return an ASCII string suitable
  22808. // for use in a HTTP field value.
  22809. //
  22810. // 1. Let output be the string "(".
  22811. //
  22812. // 2. For each (member_value, parameters) of inner_list:
  22813. //
  22814. // 1. Append the result of running Serializing an Item
  22815. // (Section 4.1.3) with (member_value, parameters) to output.
  22816. //
  22817. // 2. If more values remain in inner_list, append a single SP to
  22818. // output.
  22819. //
  22820. // 3. Append ")" to output.
  22821. //
  22822. // 4. Append the result of running Serializing Parameters
  22823. // (Section 4.1.1.2) with list_parameters to output.
  22824. //
  22825. // 5. Return output.
  22826. function serializeInnerList(value) {
  22827. return `(${value.value.map(serializeItem).join(' ')})${serializeParams(value.params)}`;
  22828. }
  22829. // 4.1.2. Serializing a Dictionary
  22830. //
  22831. // Given an ordered Dictionary as input_dictionary (each member having a
  22832. // member_name and a tuple value of (member_value, parameters)), return
  22833. // an ASCII string suitable for use in a HTTP field value.
  22834. //
  22835. // 1. Let output be an empty string.
  22836. //
  22837. // 2. For each member_name with a value of (member_value, parameters)
  22838. // in input_dictionary:
  22839. //
  22840. // 1. Append the result of running Serializing a Key
  22841. // (Section 4.1.1.3) with member's member_name to output.
  22842. //
  22843. // 2. If member_value is Boolean true:
  22844. //
  22845. // 1. Append the result of running Serializing Parameters
  22846. // (Section 4.1.1.2) with parameters to output.
  22847. //
  22848. // 3. Otherwise:
  22849. //
  22850. // 1. Append "=" to output.
  22851. //
  22852. // 2. If member_value is an array, append the result of running
  22853. // Serializing an Inner List (Section 4.1.1.1) with
  22854. // (member_value, parameters) to output.
  22855. //
  22856. // 3. Otherwise, append the result of running Serializing an
  22857. // Item (Section 4.1.3) with (member_value, parameters) to
  22858. // output.
  22859. //
  22860. // 4. If more members remain in input_dictionary:
  22861. //
  22862. // 1. Append "," to output.
  22863. //
  22864. // 2. Append a single SP to output.
  22865. //
  22866. // 3. Return output.
  22867. function serializeDict(dict, options = {
  22868. whitespace: true
  22869. }) {
  22870. if (typeof dict !== 'object') {
  22871. throw serializeError(dict, DICT);
  22872. }
  22873. const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  22874. const optionalWhiteSpace = options != null && options.whitespace ? ' ' : '';
  22875. return Array.from(entries).map(([key, item]) => {
  22876. if (item instanceof SfItem === false) {
  22877. item = new SfItem(item);
  22878. }
  22879. let output = serializeKey(key);
  22880. if (item.value === true) {
  22881. output += serializeParams(item.params);
  22882. } else {
  22883. output += '=';
  22884. if (Array.isArray(item.value)) {
  22885. output += serializeInnerList(item);
  22886. } else {
  22887. output += serializeItem(item);
  22888. }
  22889. }
  22890. return output;
  22891. }).join(`,${optionalWhiteSpace}`);
  22892. }
  22893. /**
  22894. * Encode an object into a structured field dictionary
  22895. *
  22896. * @param input - The structured field dictionary to encode
  22897. * @returns The structured field string
  22898. *
  22899. * @group Structured Field
  22900. *
  22901. * @beta
  22902. */
  22903. function encodeSfDict(value, options) {
  22904. return serializeDict(value, options);
  22905. }
  22906. /**
  22907. * Checks if the given key is a token field.
  22908. *
  22909. * @param key - The key to check.
  22910. *
  22911. * @returns `true` if the key is a token field.
  22912. *
  22913. * @internal
  22914. *
  22915. * @group CMCD
  22916. */
  22917. const isTokenField = key => key === 'ot' || key === 'sf' || key === 'st';
  22918. const isValid = value => {
  22919. if (typeof value === 'number') {
  22920. return isFiniteNumber(value);
  22921. }
  22922. return value != null && value !== '' && value !== false;
  22923. };
  22924. /**
  22925. * Constructs a relative path from a URL.
  22926. *
  22927. * @param url - The destination URL
  22928. * @param base - The base URL
  22929. * @returns The relative path
  22930. *
  22931. * @group Utils
  22932. *
  22933. * @beta
  22934. */
  22935. function urlToRelativePath(url, base) {
  22936. const to = new URL(url);
  22937. const from = new URL(base);
  22938. if (to.origin !== from.origin) {
  22939. return url;
  22940. }
  22941. const toPath = to.pathname.split('/').slice(1);
  22942. const fromPath = from.pathname.split('/').slice(1, -1);
  22943. // remove common parents
  22944. while (toPath[0] === fromPath[0]) {
  22945. toPath.shift();
  22946. fromPath.shift();
  22947. }
  22948. // add back paths
  22949. while (fromPath.length) {
  22950. fromPath.shift();
  22951. toPath.unshift('..');
  22952. }
  22953. return toPath.join('/');
  22954. }
  22955. /**
  22956. * Generate a random v4 UUID
  22957. *
  22958. * @returns A random v4 UUID
  22959. *
  22960. * @group Utils
  22961. *
  22962. * @beta
  22963. */
  22964. function uuid() {
  22965. try {
  22966. return crypto.randomUUID();
  22967. } catch (error) {
  22968. try {
  22969. const url = URL.createObjectURL(new Blob());
  22970. const uuid = url.toString();
  22971. URL.revokeObjectURL(url);
  22972. return uuid.slice(uuid.lastIndexOf('/') + 1);
  22973. } catch (error) {
  22974. let dt = new Date().getTime();
  22975. const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  22976. const r = (dt + Math.random() * 16) % 16 | 0;
  22977. dt = Math.floor(dt / 16);
  22978. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  22979. });
  22980. return uuid;
  22981. }
  22982. }
  22983. }
  22984. const toRounded = value => Math.round(value);
  22985. const toUrlSafe = (value, options) => {
  22986. if (options != null && options.baseUrl) {
  22987. value = urlToRelativePath(value, options.baseUrl);
  22988. }
  22989. return encodeURIComponent(value);
  22990. };
  22991. const toHundred = value => toRounded(value / 100) * 100;
  22992. /**
  22993. * The default formatters for CMCD values.
  22994. *
  22995. * @group CMCD
  22996. *
  22997. * @beta
  22998. */
  22999. const CmcdFormatters = {
  23000. /**
  23001. * Bitrate (kbps) rounded integer
  23002. */
  23003. br: toRounded,
  23004. /**
  23005. * Duration (milliseconds) rounded integer
  23006. */
  23007. d: toRounded,
  23008. /**
  23009. * Buffer Length (milliseconds) rounded nearest 100ms
  23010. */
  23011. bl: toHundred,
  23012. /**
  23013. * Deadline (milliseconds) rounded nearest 100ms
  23014. */
  23015. dl: toHundred,
  23016. /**
  23017. * Measured Throughput (kbps) rounded nearest 100kbps
  23018. */
  23019. mtp: toHundred,
  23020. /**
  23021. * Next Object Request URL encoded
  23022. */
  23023. nor: toUrlSafe,
  23024. /**
  23025. * Requested maximum throughput (kbps) rounded nearest 100kbps
  23026. */
  23027. rtp: toHundred,
  23028. /**
  23029. * Top Bitrate (kbps) rounded integer
  23030. */
  23031. tb: toRounded
  23032. };
  23033. /**
  23034. * Internal CMCD processing function.
  23035. *
  23036. * @param obj - The CMCD object to process.
  23037. * @param map - The mapping function to use.
  23038. * @param options - Options for encoding.
  23039. *
  23040. * @internal
  23041. *
  23042. * @group CMCD
  23043. */
  23044. function processCmcd(obj, options) {
  23045. const results = {};
  23046. if (obj == null || typeof obj !== 'object') {
  23047. return results;
  23048. }
  23049. const keys = Object.keys(obj).sort();
  23050. const formatters = _extends({}, CmcdFormatters, options == null ? void 0 : options.formatters);
  23051. const filter = options == null ? void 0 : options.filter;
  23052. keys.forEach(key => {
  23053. if (filter != null && filter(key)) {
  23054. return;
  23055. }
  23056. let value = obj[key];
  23057. const formatter = formatters[key];
  23058. if (formatter) {
  23059. value = formatter(value, options);
  23060. }
  23061. // Version should only be reported if not equal to 1.
  23062. if (key === 'v' && value === 1) {
  23063. return;
  23064. }
  23065. // Playback rate should only be sent if not equal to 1.
  23066. if (key == 'pr' && value === 1) {
  23067. return;
  23068. }
  23069. // ignore invalid values
  23070. if (!isValid(value)) {
  23071. return;
  23072. }
  23073. if (isTokenField(key) && typeof value === 'string') {
  23074. value = new SfToken(value);
  23075. }
  23076. results[key] = value;
  23077. });
  23078. return results;
  23079. }
  23080. /**
  23081. * Encode a CMCD object to a string.
  23082. *
  23083. * @param cmcd - The CMCD object to encode.
  23084. * @param options - Options for encoding.
  23085. *
  23086. * @returns The encoded CMCD string.
  23087. *
  23088. * @group CMCD
  23089. *
  23090. * @beta
  23091. */
  23092. function encodeCmcd(cmcd, options = {}) {
  23093. if (!cmcd) {
  23094. return '';
  23095. }
  23096. return encodeSfDict(processCmcd(cmcd, options), _extends({
  23097. whitespace: false
  23098. }, options));
  23099. }
  23100. /**
  23101. * Convert a CMCD data object to request headers
  23102. *
  23103. * @param cmcd - The CMCD data object to convert.
  23104. * @param options - Options for encoding the CMCD object.
  23105. *
  23106. * @returns The CMCD header shards.
  23107. *
  23108. * @group CMCD
  23109. *
  23110. * @beta
  23111. */
  23112. function toCmcdHeaders(cmcd, options = {}) {
  23113. if (!cmcd) {
  23114. return {};
  23115. }
  23116. const entries = Object.entries(cmcd);
  23117. const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options == null ? void 0 : options.customHeaderMap) || {}));
  23118. const shards = entries.reduce((acc, entry) => {
  23119. var _headerMap$find, _acc$field;
  23120. const [key, value] = entry;
  23121. const field = ((_headerMap$find = headerMap.find(entry => entry[1].includes(key))) == null ? void 0 : _headerMap$find[0]) || CmcdHeaderField.REQUEST;
  23122. (_acc$field = acc[field]) != null ? _acc$field : acc[field] = {};
  23123. acc[field][key] = value;
  23124. return acc;
  23125. }, {});
  23126. return Object.entries(shards).reduce((acc, [field, value]) => {
  23127. acc[field] = encodeCmcd(value, options);
  23128. return acc;
  23129. }, {});
  23130. }
  23131. /**
  23132. * Append CMCD query args to a header object.
  23133. *
  23134. * @param headers - The headers to append to.
  23135. * @param cmcd - The CMCD object to append.
  23136. * @param customHeaderMap - A map of custom CMCD keys to header fields.
  23137. *
  23138. * @returns The headers with the CMCD header shards appended.
  23139. *
  23140. * @group CMCD
  23141. *
  23142. * @beta
  23143. */
  23144. function appendCmcdHeaders(headers, cmcd, options) {
  23145. return _extends(headers, toCmcdHeaders(cmcd, options));
  23146. }
  23147. /**
  23148. * CMCD parameter name.
  23149. *
  23150. * @group CMCD
  23151. *
  23152. * @beta
  23153. */
  23154. const CMCD_PARAM = 'CMCD';
  23155. /**
  23156. * Convert a CMCD data object to a query arg.
  23157. *
  23158. * @param cmcd - The CMCD object to convert.
  23159. * @param options - Options for encoding the CMCD object.
  23160. *
  23161. * @returns The CMCD query arg.
  23162. *
  23163. * @group CMCD
  23164. *
  23165. * @beta
  23166. */
  23167. function toCmcdQuery(cmcd, options = {}) {
  23168. if (!cmcd) {
  23169. return '';
  23170. }
  23171. const params = encodeCmcd(cmcd, options);
  23172. return `${CMCD_PARAM}=${encodeURIComponent(params)}`;
  23173. }
  23174. const REGEX = /CMCD=[^&#]+/;
  23175. /**
  23176. * Append CMCD query args to a URL.
  23177. *
  23178. * @param url - The URL to append to.
  23179. * @param cmcd - The CMCD object to append.
  23180. * @param options - Options for encoding the CMCD object.
  23181. *
  23182. * @returns The URL with the CMCD query args appended.
  23183. *
  23184. * @group CMCD
  23185. *
  23186. * @beta
  23187. */
  23188. function appendCmcdQuery(url, cmcd, options) {
  23189. // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.
  23190. // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
  23191. const query = toCmcdQuery(cmcd, options);
  23192. if (!query) {
  23193. return url;
  23194. }
  23195. if (REGEX.test(url)) {
  23196. return url.replace(REGEX, query);
  23197. }
  23198. const separator = url.includes('?') ? '&' : '?';
  23199. return `${url}${separator}${query}`;
  23200. }
  23201. /**
  23202. * Controller to deal with Common Media Client Data (CMCD)
  23203. * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
  23204. */
  23205. class CMCDController {
  23206. // eslint-disable-line no-restricted-globals
  23207. constructor(hls) {
  23208. this.hls = void 0;
  23209. this.config = void 0;
  23210. this.media = void 0;
  23211. this.sid = void 0;
  23212. this.cid = void 0;
  23213. this.useHeaders = false;
  23214. this.includeKeys = void 0;
  23215. this.initialized = false;
  23216. this.starved = false;
  23217. this.buffering = true;
  23218. this.audioBuffer = void 0;
  23219. // eslint-disable-line no-restricted-globals
  23220. this.videoBuffer = void 0;
  23221. this.onWaiting = () => {
  23222. if (this.initialized) {
  23223. this.starved = true;
  23224. }
  23225. this.buffering = true;
  23226. };
  23227. this.onPlaying = () => {
  23228. if (!this.initialized) {
  23229. this.initialized = true;
  23230. }
  23231. this.buffering = false;
  23232. };
  23233. /**
  23234. * Apply CMCD data to a manifest request.
  23235. */
  23236. this.applyPlaylistData = context => {
  23237. try {
  23238. this.apply(context, {
  23239. ot: CmObjectType.MANIFEST,
  23240. su: !this.initialized
  23241. });
  23242. } catch (error) {
  23243. logger.warn('Could not generate manifest CMCD data.', error);
  23244. }
  23245. };
  23246. /**
  23247. * Apply CMCD data to a segment request
  23248. */
  23249. this.applyFragmentData = context => {
  23250. try {
  23251. const fragment = context.frag;
  23252. const level = this.hls.levels[fragment.level];
  23253. const ot = this.getObjectType(fragment);
  23254. const data = {
  23255. d: fragment.duration * 1000,
  23256. ot
  23257. };
  23258. if (ot === CmObjectType.VIDEO || ot === CmObjectType.AUDIO || ot == CmObjectType.MUXED) {
  23259. data.br = level.bitrate / 1000;
  23260. data.tb = this.getTopBandwidth(ot) / 1000;
  23261. data.bl = this.getBufferLength(ot);
  23262. }
  23263. this.apply(context, data);
  23264. } catch (error) {
  23265. logger.warn('Could not generate segment CMCD data.', error);
  23266. }
  23267. };
  23268. this.hls = hls;
  23269. const config = this.config = hls.config;
  23270. const {
  23271. cmcd
  23272. } = config;
  23273. if (cmcd != null) {
  23274. config.pLoader = this.createPlaylistLoader();
  23275. config.fLoader = this.createFragmentLoader();
  23276. this.sid = cmcd.sessionId || uuid();
  23277. this.cid = cmcd.contentId;
  23278. this.useHeaders = cmcd.useHeaders === true;
  23279. this.includeKeys = cmcd.includeKeys;
  23280. this.registerListeners();
  23281. }
  23282. }
  23283. registerListeners() {
  23284. const hls = this.hls;
  23285. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23286. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23287. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23288. }
  23289. unregisterListeners() {
  23290. const hls = this.hls;
  23291. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  23292. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  23293. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  23294. }
  23295. destroy() {
  23296. this.unregisterListeners();
  23297. this.onMediaDetached();
  23298. // @ts-ignore
  23299. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  23300. // @ts-ignore
  23301. this.onWaiting = this.onPlaying = null;
  23302. }
  23303. onMediaAttached(event, data) {
  23304. this.media = data.media;
  23305. this.media.addEventListener('waiting', this.onWaiting);
  23306. this.media.addEventListener('playing', this.onPlaying);
  23307. }
  23308. onMediaDetached() {
  23309. if (!this.media) {
  23310. return;
  23311. }
  23312. this.media.removeEventListener('waiting', this.onWaiting);
  23313. this.media.removeEventListener('playing', this.onPlaying);
  23314. // @ts-ignore
  23315. this.media = null;
  23316. }
  23317. onBufferCreated(event, data) {
  23318. var _data$tracks$audio, _data$tracks$video;
  23319. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  23320. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  23321. }
  23322. /**
  23323. * Create baseline CMCD data
  23324. */
  23325. createData() {
  23326. var _this$media;
  23327. return {
  23328. v: 1,
  23329. sf: CmStreamingFormat.HLS,
  23330. sid: this.sid,
  23331. cid: this.cid,
  23332. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  23333. mtp: this.hls.bandwidthEstimate / 1000
  23334. };
  23335. }
  23336. /**
  23337. * Apply CMCD data to a request.
  23338. */
  23339. apply(context, data = {}) {
  23340. // apply baseline data
  23341. _extends(data, this.createData());
  23342. const isVideo = data.ot === CmObjectType.INIT || data.ot === CmObjectType.VIDEO || data.ot === CmObjectType.MUXED;
  23343. if (this.starved && isVideo) {
  23344. data.bs = true;
  23345. data.su = true;
  23346. this.starved = false;
  23347. }
  23348. if (data.su == null) {
  23349. data.su = this.buffering;
  23350. }
  23351. // TODO: Implement rtp, nrr, nor, dl
  23352. const {
  23353. includeKeys
  23354. } = this;
  23355. if (includeKeys) {
  23356. data = Object.keys(data).reduce((acc, key) => {
  23357. includeKeys.includes(key) && (acc[key] = data[key]);
  23358. return acc;
  23359. }, {});
  23360. }
  23361. if (this.useHeaders) {
  23362. if (!context.headers) {
  23363. context.headers = {};
  23364. }
  23365. appendCmcdHeaders(context.headers, data);
  23366. } else {
  23367. context.url = appendCmcdQuery(context.url, data);
  23368. }
  23369. }
  23370. /**
  23371. * The CMCD object type.
  23372. */
  23373. getObjectType(fragment) {
  23374. const {
  23375. type
  23376. } = fragment;
  23377. if (type === 'subtitle') {
  23378. return CmObjectType.TIMED_TEXT;
  23379. }
  23380. if (fragment.sn === 'initSegment') {
  23381. return CmObjectType.INIT;
  23382. }
  23383. if (type === 'audio') {
  23384. return CmObjectType.AUDIO;
  23385. }
  23386. if (type === 'main') {
  23387. if (!this.hls.audioTracks.length) {
  23388. return CmObjectType.MUXED;
  23389. }
  23390. return CmObjectType.VIDEO;
  23391. }
  23392. return undefined;
  23393. }
  23394. /**
  23395. * Get the highest bitrate.
  23396. */
  23397. getTopBandwidth(type) {
  23398. let bitrate = 0;
  23399. let levels;
  23400. const hls = this.hls;
  23401. if (type === CmObjectType.AUDIO) {
  23402. levels = hls.audioTracks;
  23403. } else {
  23404. const max = hls.maxAutoLevel;
  23405. const len = max > -1 ? max + 1 : hls.levels.length;
  23406. levels = hls.levels.slice(0, len);
  23407. }
  23408. for (const level of levels) {
  23409. if (level.bitrate > bitrate) {
  23410. bitrate = level.bitrate;
  23411. }
  23412. }
  23413. return bitrate > 0 ? bitrate : NaN;
  23414. }
  23415. /**
  23416. * Get the buffer length for a media type in milliseconds
  23417. */
  23418. getBufferLength(type) {
  23419. const media = this.hls.media;
  23420. const buffer = type === CmObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  23421. if (!buffer || !media) {
  23422. return NaN;
  23423. }
  23424. const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  23425. return info.len * 1000;
  23426. }
  23427. /**
  23428. * Create a playlist loader
  23429. */
  23430. createPlaylistLoader() {
  23431. const {
  23432. pLoader
  23433. } = this.config;
  23434. const apply = this.applyPlaylistData;
  23435. const Ctor = pLoader || this.config.loader;
  23436. return class CmcdPlaylistLoader {
  23437. constructor(config) {
  23438. this.loader = void 0;
  23439. this.loader = new Ctor(config);
  23440. }
  23441. get stats() {
  23442. return this.loader.stats;
  23443. }
  23444. get context() {
  23445. return this.loader.context;
  23446. }
  23447. destroy() {
  23448. this.loader.destroy();
  23449. }
  23450. abort() {
  23451. this.loader.abort();
  23452. }
  23453. load(context, config, callbacks) {
  23454. apply(context);
  23455. this.loader.load(context, config, callbacks);
  23456. }
  23457. };
  23458. }
  23459. /**
  23460. * Create a playlist loader
  23461. */
  23462. createFragmentLoader() {
  23463. const {
  23464. fLoader
  23465. } = this.config;
  23466. const apply = this.applyFragmentData;
  23467. const Ctor = fLoader || this.config.loader;
  23468. return class CmcdFragmentLoader {
  23469. constructor(config) {
  23470. this.loader = void 0;
  23471. this.loader = new Ctor(config);
  23472. }
  23473. get stats() {
  23474. return this.loader.stats;
  23475. }
  23476. get context() {
  23477. return this.loader.context;
  23478. }
  23479. destroy() {
  23480. this.loader.destroy();
  23481. }
  23482. abort() {
  23483. this.loader.abort();
  23484. }
  23485. load(context, config, callbacks) {
  23486. apply(context);
  23487. this.loader.load(context, config, callbacks);
  23488. }
  23489. };
  23490. }
  23491. }
  23492. const PATHWAY_PENALTY_DURATION_MS = 300000;
  23493. class ContentSteeringController {
  23494. constructor(hls) {
  23495. this.hls = void 0;
  23496. this.log = void 0;
  23497. this.loader = null;
  23498. this.uri = null;
  23499. this.pathwayId = '.';
  23500. this.pathwayPriority = null;
  23501. this.timeToLoad = 300;
  23502. this.reloadTimer = -1;
  23503. this.updated = 0;
  23504. this.started = false;
  23505. this.enabled = true;
  23506. this.levels = null;
  23507. this.audioTracks = null;
  23508. this.subtitleTracks = null;
  23509. this.penalizedPathways = {};
  23510. this.hls = hls;
  23511. this.log = logger.log.bind(logger, `[content-steering]:`);
  23512. this.registerListeners();
  23513. }
  23514. registerListeners() {
  23515. const hls = this.hls;
  23516. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23517. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23518. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23519. hls.on(Events.ERROR, this.onError, this);
  23520. }
  23521. unregisterListeners() {
  23522. const hls = this.hls;
  23523. if (!hls) {
  23524. return;
  23525. }
  23526. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  23527. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  23528. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  23529. hls.off(Events.ERROR, this.onError, this);
  23530. }
  23531. startLoad() {
  23532. this.started = true;
  23533. this.clearTimeout();
  23534. if (this.enabled && this.uri) {
  23535. if (this.updated) {
  23536. const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  23537. if (ttl > 0) {
  23538. this.scheduleRefresh(this.uri, ttl);
  23539. return;
  23540. }
  23541. }
  23542. this.loadSteeringManifest(this.uri);
  23543. }
  23544. }
  23545. stopLoad() {
  23546. this.started = false;
  23547. if (this.loader) {
  23548. this.loader.destroy();
  23549. this.loader = null;
  23550. }
  23551. this.clearTimeout();
  23552. }
  23553. clearTimeout() {
  23554. if (this.reloadTimer !== -1) {
  23555. self.clearTimeout(this.reloadTimer);
  23556. this.reloadTimer = -1;
  23557. }
  23558. }
  23559. destroy() {
  23560. this.unregisterListeners();
  23561. this.stopLoad();
  23562. // @ts-ignore
  23563. this.hls = null;
  23564. this.levels = this.audioTracks = this.subtitleTracks = null;
  23565. }
  23566. removeLevel(levelToRemove) {
  23567. const levels = this.levels;
  23568. if (levels) {
  23569. this.levels = levels.filter(level => level !== levelToRemove);
  23570. }
  23571. }
  23572. onManifestLoading() {
  23573. this.stopLoad();
  23574. this.enabled = true;
  23575. this.timeToLoad = 300;
  23576. this.updated = 0;
  23577. this.uri = null;
  23578. this.pathwayId = '.';
  23579. this.levels = this.audioTracks = this.subtitleTracks = null;
  23580. }
  23581. onManifestLoaded(event, data) {
  23582. const {
  23583. contentSteering
  23584. } = data;
  23585. if (contentSteering === null) {
  23586. return;
  23587. }
  23588. this.pathwayId = contentSteering.pathwayId;
  23589. this.uri = contentSteering.uri;
  23590. if (this.started) {
  23591. this.startLoad();
  23592. }
  23593. }
  23594. onManifestParsed(event, data) {
  23595. this.audioTracks = data.audioTracks;
  23596. this.subtitleTracks = data.subtitleTracks;
  23597. }
  23598. onError(event, data) {
  23599. const {
  23600. errorAction
  23601. } = data;
  23602. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  23603. const levels = this.levels;
  23604. let pathwayPriority = this.pathwayPriority;
  23605. let errorPathway = this.pathwayId;
  23606. if (data.context) {
  23607. const {
  23608. groupId,
  23609. pathwayId,
  23610. type
  23611. } = data.context;
  23612. if (groupId && levels) {
  23613. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  23614. } else if (pathwayId) {
  23615. errorPathway = pathwayId;
  23616. }
  23617. }
  23618. if (!(errorPathway in this.penalizedPathways)) {
  23619. this.penalizedPathways[errorPathway] = performance.now();
  23620. }
  23621. if (!pathwayPriority && levels) {
  23622. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  23623. pathwayPriority = levels.reduce((pathways, level) => {
  23624. if (pathways.indexOf(level.pathwayId) === -1) {
  23625. pathways.push(level.pathwayId);
  23626. }
  23627. return pathways;
  23628. }, []);
  23629. }
  23630. if (pathwayPriority && pathwayPriority.length > 1) {
  23631. this.updatePathwayPriority(pathwayPriority);
  23632. errorAction.resolved = this.pathwayId !== errorPathway;
  23633. }
  23634. if (!errorAction.resolved) {
  23635. 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)}`);
  23636. }
  23637. }
  23638. }
  23639. filterParsedLevels(levels) {
  23640. // Filter levels to only include those that are in the initial pathway
  23641. this.levels = levels;
  23642. let pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  23643. if (pathwayLevels.length === 0) {
  23644. const pathwayId = levels[0].pathwayId;
  23645. this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${pathwayId}"`);
  23646. pathwayLevels = this.getLevelsForPathway(pathwayId);
  23647. this.pathwayId = pathwayId;
  23648. }
  23649. if (pathwayLevels.length !== levels.length) {
  23650. this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway "${this.pathwayId}"`);
  23651. return pathwayLevels;
  23652. }
  23653. return levels;
  23654. }
  23655. getLevelsForPathway(pathwayId) {
  23656. if (this.levels === null) {
  23657. return [];
  23658. }
  23659. return this.levels.filter(level => pathwayId === level.pathwayId);
  23660. }
  23661. updatePathwayPriority(pathwayPriority) {
  23662. this.pathwayPriority = pathwayPriority;
  23663. let levels;
  23664. // Evaluate if we should remove the pathway from the penalized list
  23665. const penalizedPathways = this.penalizedPathways;
  23666. const now = performance.now();
  23667. Object.keys(penalizedPathways).forEach(pathwayId => {
  23668. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  23669. delete penalizedPathways[pathwayId];
  23670. }
  23671. });
  23672. for (let i = 0; i < pathwayPriority.length; i++) {
  23673. const pathwayId = pathwayPriority[i];
  23674. if (pathwayId in penalizedPathways) {
  23675. continue;
  23676. }
  23677. if (pathwayId === this.pathwayId) {
  23678. return;
  23679. }
  23680. const selectedIndex = this.hls.nextLoadLevel;
  23681. const selectedLevel = this.hls.levels[selectedIndex];
  23682. levels = this.getLevelsForPathway(pathwayId);
  23683. if (levels.length > 0) {
  23684. this.log(`Setting Pathway to "${pathwayId}"`);
  23685. this.pathwayId = pathwayId;
  23686. reassignFragmentLevelIndexes(levels);
  23687. this.hls.trigger(Events.LEVELS_UPDATED, {
  23688. levels
  23689. });
  23690. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  23691. const levelAfterChange = this.hls.levels[selectedIndex];
  23692. if (selectedLevel && levelAfterChange && this.levels) {
  23693. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  23694. this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);
  23695. }
  23696. this.hls.nextLoadLevel = selectedIndex;
  23697. }
  23698. break;
  23699. }
  23700. }
  23701. }
  23702. getPathwayForGroupId(groupId, type, defaultPathway) {
  23703. const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  23704. for (let i = 0; i < levels.length; i++) {
  23705. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  23706. return levels[i].pathwayId;
  23707. }
  23708. }
  23709. return defaultPathway;
  23710. }
  23711. clonePathways(pathwayClones) {
  23712. const levels = this.levels;
  23713. if (!levels) {
  23714. return;
  23715. }
  23716. const audioGroupCloneMap = {};
  23717. const subtitleGroupCloneMap = {};
  23718. pathwayClones.forEach(pathwayClone => {
  23719. const {
  23720. ID: cloneId,
  23721. 'BASE-ID': baseId,
  23722. 'URI-REPLACEMENT': uriReplacement
  23723. } = pathwayClone;
  23724. if (levels.some(level => level.pathwayId === cloneId)) {
  23725. return;
  23726. }
  23727. const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {
  23728. const attributes = new AttrList(baseLevel.attrs);
  23729. attributes['PATHWAY-ID'] = cloneId;
  23730. const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;
  23731. const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;
  23732. if (clonedAudioGroupId) {
  23733. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  23734. attributes.AUDIO = clonedAudioGroupId;
  23735. }
  23736. if (clonedSubtitleGroupId) {
  23737. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  23738. attributes.SUBTITLES = clonedSubtitleGroupId;
  23739. }
  23740. const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  23741. const clonedLevel = new Level({
  23742. attrs: attributes,
  23743. audioCodec: baseLevel.audioCodec,
  23744. bitrate: baseLevel.bitrate,
  23745. height: baseLevel.height,
  23746. name: baseLevel.name,
  23747. url,
  23748. videoCodec: baseLevel.videoCodec,
  23749. width: baseLevel.width
  23750. });
  23751. if (baseLevel.audioGroups) {
  23752. for (let i = 1; i < baseLevel.audioGroups.length; i++) {
  23753. clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);
  23754. }
  23755. }
  23756. if (baseLevel.subtitleGroups) {
  23757. for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {
  23758. clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);
  23759. }
  23760. }
  23761. return clonedLevel;
  23762. });
  23763. levels.push(...clonedVariants);
  23764. cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  23765. cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  23766. });
  23767. }
  23768. loadSteeringManifest(uri) {
  23769. const config = this.hls.config;
  23770. const Loader = config.loader;
  23771. if (this.loader) {
  23772. this.loader.destroy();
  23773. }
  23774. this.loader = new Loader(config);
  23775. let url;
  23776. try {
  23777. url = new self.URL(uri);
  23778. } catch (error) {
  23779. this.enabled = false;
  23780. this.log(`Failed to parse Steering Manifest URI: ${uri}`);
  23781. return;
  23782. }
  23783. if (url.protocol !== 'data:') {
  23784. const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  23785. url.searchParams.set('_HLS_pathway', this.pathwayId);
  23786. url.searchParams.set('_HLS_throughput', '' + throughput);
  23787. }
  23788. const context = {
  23789. responseType: 'json',
  23790. url: url.href
  23791. };
  23792. const loadPolicy = config.steeringManifestLoadPolicy.default;
  23793. const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  23794. const loaderConfig = {
  23795. loadPolicy,
  23796. timeout: loadPolicy.maxLoadTimeMs,
  23797. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  23798. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  23799. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  23800. };
  23801. const callbacks = {
  23802. onSuccess: (response, stats, context, networkDetails) => {
  23803. this.log(`Loaded steering manifest: "${url}"`);
  23804. const steeringData = response.data;
  23805. if (steeringData.VERSION !== 1) {
  23806. this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);
  23807. return;
  23808. }
  23809. this.updated = performance.now();
  23810. this.timeToLoad = steeringData.TTL;
  23811. const {
  23812. 'RELOAD-URI': reloadUri,
  23813. 'PATHWAY-CLONES': pathwayClones,
  23814. 'PATHWAY-PRIORITY': pathwayPriority
  23815. } = steeringData;
  23816. if (reloadUri) {
  23817. try {
  23818. this.uri = new self.URL(reloadUri, url).href;
  23819. } catch (error) {
  23820. this.enabled = false;
  23821. this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);
  23822. return;
  23823. }
  23824. }
  23825. this.scheduleRefresh(this.uri || context.url);
  23826. if (pathwayClones) {
  23827. this.clonePathways(pathwayClones);
  23828. }
  23829. const loadedSteeringData = {
  23830. steeringManifest: steeringData,
  23831. url: url.toString()
  23832. };
  23833. this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  23834. if (pathwayPriority) {
  23835. this.updatePathwayPriority(pathwayPriority);
  23836. }
  23837. },
  23838. onError: (error, context, networkDetails, stats) => {
  23839. this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);
  23840. this.stopLoad();
  23841. if (error.code === 410) {
  23842. this.enabled = false;
  23843. this.log(`Steering manifest ${context.url} no longer available`);
  23844. return;
  23845. }
  23846. let ttl = this.timeToLoad * 1000;
  23847. if (error.code === 429) {
  23848. const loader = this.loader;
  23849. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  23850. const retryAfter = loader.getResponseHeader('Retry-After');
  23851. if (retryAfter) {
  23852. ttl = parseFloat(retryAfter) * 1000;
  23853. }
  23854. }
  23855. this.log(`Steering manifest ${context.url} rate limited`);
  23856. return;
  23857. }
  23858. this.scheduleRefresh(this.uri || context.url, ttl);
  23859. },
  23860. onTimeout: (stats, context, networkDetails) => {
  23861. this.log(`Timeout loading steering manifest (${context.url})`);
  23862. this.scheduleRefresh(this.uri || context.url);
  23863. }
  23864. };
  23865. this.log(`Requesting steering manifest: ${url}`);
  23866. this.loader.load(context, loaderConfig, callbacks);
  23867. }
  23868. scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {
  23869. this.clearTimeout();
  23870. this.reloadTimer = self.setTimeout(() => {
  23871. var _this$hls;
  23872. const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;
  23873. if (media && !media.ended) {
  23874. this.loadSteeringManifest(uri);
  23875. return;
  23876. }
  23877. this.scheduleRefresh(uri, this.timeToLoad * 1000);
  23878. }, ttlMs);
  23879. }
  23880. }
  23881. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  23882. if (!tracks) {
  23883. return;
  23884. }
  23885. Object.keys(groupCloneMap).forEach(audioGroupId => {
  23886. const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {
  23887. const clonedTrack = _extends({}, track);
  23888. clonedTrack.details = undefined;
  23889. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  23890. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  23891. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  23892. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  23893. return clonedTrack;
  23894. });
  23895. tracks.push(...clonedTracks);
  23896. });
  23897. }
  23898. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  23899. const {
  23900. HOST: host,
  23901. PARAMS: params,
  23902. [perOptionKey]: perOptionUris
  23903. } = uriReplacement;
  23904. let perVariantUri;
  23905. if (stableId) {
  23906. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  23907. if (perVariantUri) {
  23908. uri = perVariantUri;
  23909. }
  23910. }
  23911. const url = new self.URL(uri);
  23912. if (host && !perVariantUri) {
  23913. url.host = host;
  23914. }
  23915. if (params) {
  23916. Object.keys(params).sort().forEach(key => {
  23917. if (key) {
  23918. url.searchParams.set(key, params[key]);
  23919. }
  23920. });
  23921. }
  23922. return url.href;
  23923. }
  23924. const AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  23925. class XhrLoader {
  23926. constructor(config) {
  23927. this.xhrSetup = void 0;
  23928. this.requestTimeout = void 0;
  23929. this.retryTimeout = void 0;
  23930. this.retryDelay = void 0;
  23931. this.config = null;
  23932. this.callbacks = null;
  23933. this.context = null;
  23934. this.loader = null;
  23935. this.stats = void 0;
  23936. this.xhrSetup = config ? config.xhrSetup || null : null;
  23937. this.stats = new LoadStats();
  23938. this.retryDelay = 0;
  23939. }
  23940. destroy() {
  23941. this.callbacks = null;
  23942. this.abortInternal();
  23943. this.loader = null;
  23944. this.config = null;
  23945. this.context = null;
  23946. this.xhrSetup = null;
  23947. }
  23948. abortInternal() {
  23949. const loader = this.loader;
  23950. self.clearTimeout(this.requestTimeout);
  23951. self.clearTimeout(this.retryTimeout);
  23952. if (loader) {
  23953. loader.onreadystatechange = null;
  23954. loader.onprogress = null;
  23955. if (loader.readyState !== 4) {
  23956. this.stats.aborted = true;
  23957. loader.abort();
  23958. }
  23959. }
  23960. }
  23961. abort() {
  23962. var _this$callbacks;
  23963. this.abortInternal();
  23964. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  23965. this.callbacks.onAbort(this.stats, this.context, this.loader);
  23966. }
  23967. }
  23968. load(context, config, callbacks) {
  23969. if (this.stats.loading.start) {
  23970. throw new Error('Loader can only be used once.');
  23971. }
  23972. this.stats.loading.start = self.performance.now();
  23973. this.context = context;
  23974. this.config = config;
  23975. this.callbacks = callbacks;
  23976. this.loadInternal();
  23977. }
  23978. loadInternal() {
  23979. const {
  23980. config,
  23981. context
  23982. } = this;
  23983. if (!config || !context) {
  23984. return;
  23985. }
  23986. const xhr = this.loader = new self.XMLHttpRequest();
  23987. const stats = this.stats;
  23988. stats.loading.first = 0;
  23989. stats.loaded = 0;
  23990. stats.aborted = false;
  23991. const xhrSetup = this.xhrSetup;
  23992. if (xhrSetup) {
  23993. Promise.resolve().then(() => {
  23994. if (this.loader !== xhr || this.stats.aborted) return;
  23995. return xhrSetup(xhr, context.url);
  23996. }).catch(error => {
  23997. if (this.loader !== xhr || this.stats.aborted) return;
  23998. xhr.open('GET', context.url, true);
  23999. return xhrSetup(xhr, context.url);
  24000. }).then(() => {
  24001. if (this.loader !== xhr || this.stats.aborted) return;
  24002. this.openAndSendXhr(xhr, context, config);
  24003. }).catch(error => {
  24004. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  24005. this.callbacks.onError({
  24006. code: xhr.status,
  24007. text: error.message
  24008. }, context, xhr, stats);
  24009. return;
  24010. });
  24011. } else {
  24012. this.openAndSendXhr(xhr, context, config);
  24013. }
  24014. }
  24015. openAndSendXhr(xhr, context, config) {
  24016. if (!xhr.readyState) {
  24017. xhr.open('GET', context.url, true);
  24018. }
  24019. const headers = context.headers;
  24020. const {
  24021. maxTimeToFirstByteMs,
  24022. maxLoadTimeMs
  24023. } = config.loadPolicy;
  24024. if (headers) {
  24025. for (const header in headers) {
  24026. xhr.setRequestHeader(header, headers[header]);
  24027. }
  24028. }
  24029. if (context.rangeEnd) {
  24030. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  24031. }
  24032. xhr.onreadystatechange = this.readystatechange.bind(this);
  24033. xhr.onprogress = this.loadprogress.bind(this);
  24034. xhr.responseType = context.responseType;
  24035. // setup timeout before we perform request
  24036. self.clearTimeout(this.requestTimeout);
  24037. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  24038. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  24039. xhr.send();
  24040. }
  24041. readystatechange() {
  24042. const {
  24043. context,
  24044. loader: xhr,
  24045. stats
  24046. } = this;
  24047. if (!context || !xhr) {
  24048. return;
  24049. }
  24050. const readyState = xhr.readyState;
  24051. const config = this.config;
  24052. // don't proceed if xhr has been aborted
  24053. if (stats.aborted) {
  24054. return;
  24055. }
  24056. // >= HEADERS_RECEIVED
  24057. if (readyState >= 2) {
  24058. if (stats.loading.first === 0) {
  24059. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  24060. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  24061. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  24062. self.clearTimeout(this.requestTimeout);
  24063. config.timeout = config.loadPolicy.maxLoadTimeMs;
  24064. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  24065. }
  24066. }
  24067. if (readyState === 4) {
  24068. self.clearTimeout(this.requestTimeout);
  24069. xhr.onreadystatechange = null;
  24070. xhr.onprogress = null;
  24071. const status = xhr.status;
  24072. // http status between 200 to 299 are all successful
  24073. const useResponse = xhr.responseType !== 'text';
  24074. if (status >= 200 && status < 300 && (useResponse && xhr.response || xhr.responseText !== null)) {
  24075. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  24076. const data = useResponse ? xhr.response : xhr.responseText;
  24077. const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  24078. stats.loaded = stats.total = len;
  24079. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  24080. if (!this.callbacks) {
  24081. return;
  24082. }
  24083. const onProgress = this.callbacks.onProgress;
  24084. if (onProgress) {
  24085. onProgress(stats, context, data, xhr);
  24086. }
  24087. if (!this.callbacks) {
  24088. return;
  24089. }
  24090. const response = {
  24091. url: xhr.responseURL,
  24092. data: data,
  24093. code: status
  24094. };
  24095. this.callbacks.onSuccess(response, stats, context, xhr);
  24096. } else {
  24097. const retryConfig = config.loadPolicy.errorRetry;
  24098. const retryCount = stats.retry;
  24099. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  24100. const response = {
  24101. url: context.url,
  24102. data: undefined,
  24103. code: status
  24104. };
  24105. if (shouldRetry(retryConfig, retryCount, false, response)) {
  24106. this.retry(retryConfig);
  24107. } else {
  24108. logger.error(`${status} while loading ${context.url}`);
  24109. this.callbacks.onError({
  24110. code: status,
  24111. text: xhr.statusText
  24112. }, context, xhr, stats);
  24113. }
  24114. }
  24115. }
  24116. }
  24117. }
  24118. loadtimeout() {
  24119. if (!this.config) return;
  24120. const retryConfig = this.config.loadPolicy.timeoutRetry;
  24121. const retryCount = this.stats.retry;
  24122. if (shouldRetry(retryConfig, retryCount, true)) {
  24123. this.retry(retryConfig);
  24124. } else {
  24125. var _this$context;
  24126. logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);
  24127. const callbacks = this.callbacks;
  24128. if (callbacks) {
  24129. this.abortInternal();
  24130. callbacks.onTimeout(this.stats, this.context, this.loader);
  24131. }
  24132. }
  24133. }
  24134. retry(retryConfig) {
  24135. const {
  24136. context,
  24137. stats
  24138. } = this;
  24139. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  24140. stats.retry++;
  24141. logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);
  24142. // abort and reset internal state
  24143. this.abortInternal();
  24144. this.loader = null;
  24145. // schedule retry
  24146. self.clearTimeout(this.retryTimeout);
  24147. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  24148. }
  24149. loadprogress(event) {
  24150. const stats = this.stats;
  24151. stats.loaded = event.loaded;
  24152. if (event.lengthComputable) {
  24153. stats.total = event.total;
  24154. }
  24155. }
  24156. getCacheAge() {
  24157. let result = null;
  24158. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  24159. const ageHeader = this.loader.getResponseHeader('age');
  24160. result = ageHeader ? parseFloat(ageHeader) : null;
  24161. }
  24162. return result;
  24163. }
  24164. getResponseHeader(name) {
  24165. if (this.loader && new RegExp(`^${name}:\\s*[\\d.]+\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {
  24166. return this.loader.getResponseHeader(name);
  24167. }
  24168. return null;
  24169. }
  24170. }
  24171. function fetchSupported() {
  24172. if (
  24173. // @ts-ignore
  24174. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  24175. try {
  24176. new self.ReadableStream({}); // eslint-disable-line no-new
  24177. return true;
  24178. } catch (e) {
  24179. /* noop */
  24180. }
  24181. }
  24182. return false;
  24183. }
  24184. const BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  24185. class FetchLoader {
  24186. constructor(config /* HlsConfig */) {
  24187. this.fetchSetup = void 0;
  24188. this.requestTimeout = void 0;
  24189. this.request = null;
  24190. this.response = null;
  24191. this.controller = void 0;
  24192. this.context = null;
  24193. this.config = null;
  24194. this.callbacks = null;
  24195. this.stats = void 0;
  24196. this.loader = null;
  24197. this.fetchSetup = config.fetchSetup || getRequest;
  24198. this.controller = new self.AbortController();
  24199. this.stats = new LoadStats();
  24200. }
  24201. destroy() {
  24202. this.loader = this.callbacks = this.context = this.config = this.request = null;
  24203. this.abortInternal();
  24204. this.response = null;
  24205. // @ts-ignore
  24206. this.fetchSetup = this.controller = this.stats = null;
  24207. }
  24208. abortInternal() {
  24209. if (this.controller && !this.stats.loading.end) {
  24210. this.stats.aborted = true;
  24211. this.controller.abort();
  24212. }
  24213. }
  24214. abort() {
  24215. var _this$callbacks;
  24216. this.abortInternal();
  24217. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  24218. this.callbacks.onAbort(this.stats, this.context, this.response);
  24219. }
  24220. }
  24221. load(context, config, callbacks) {
  24222. const stats = this.stats;
  24223. if (stats.loading.start) {
  24224. throw new Error('Loader can only be used once.');
  24225. }
  24226. stats.loading.start = self.performance.now();
  24227. const initParams = getRequestParameters(context, this.controller.signal);
  24228. const onProgress = callbacks.onProgress;
  24229. const isArrayBuffer = context.responseType === 'arraybuffer';
  24230. const LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  24231. const {
  24232. maxTimeToFirstByteMs,
  24233. maxLoadTimeMs
  24234. } = config.loadPolicy;
  24235. this.context = context;
  24236. this.config = config;
  24237. this.callbacks = callbacks;
  24238. this.request = this.fetchSetup(context, initParams);
  24239. self.clearTimeout(this.requestTimeout);
  24240. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  24241. this.requestTimeout = self.setTimeout(() => {
  24242. this.abortInternal();
  24243. callbacks.onTimeout(stats, context, this.response);
  24244. }, config.timeout);
  24245. self.fetch(this.request).then(response => {
  24246. this.response = this.loader = response;
  24247. const first = Math.max(self.performance.now(), stats.loading.start);
  24248. self.clearTimeout(this.requestTimeout);
  24249. config.timeout = maxLoadTimeMs;
  24250. this.requestTimeout = self.setTimeout(() => {
  24251. this.abortInternal();
  24252. callbacks.onTimeout(stats, context, this.response);
  24253. }, maxLoadTimeMs - (first - stats.loading.start));
  24254. if (!response.ok) {
  24255. const {
  24256. status,
  24257. statusText
  24258. } = response;
  24259. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  24260. }
  24261. stats.loading.first = first;
  24262. stats.total = getContentLength(response.headers) || stats.total;
  24263. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  24264. return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  24265. }
  24266. if (isArrayBuffer) {
  24267. return response.arrayBuffer();
  24268. }
  24269. if (context.responseType === 'json') {
  24270. return response.json();
  24271. }
  24272. return response.text();
  24273. }).then(responseData => {
  24274. const response = this.response;
  24275. if (!response) {
  24276. throw new Error('loader destroyed');
  24277. }
  24278. self.clearTimeout(this.requestTimeout);
  24279. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  24280. const total = responseData[LENGTH];
  24281. if (total) {
  24282. stats.loaded = stats.total = total;
  24283. }
  24284. const loaderResponse = {
  24285. url: response.url,
  24286. data: responseData,
  24287. code: response.status
  24288. };
  24289. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  24290. onProgress(stats, context, responseData, response);
  24291. }
  24292. callbacks.onSuccess(loaderResponse, stats, context, response);
  24293. }).catch(error => {
  24294. self.clearTimeout(this.requestTimeout);
  24295. if (stats.aborted) {
  24296. return;
  24297. }
  24298. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  24299. // when destroying, 'error' itself can be undefined
  24300. const code = !error ? 0 : error.code || 0;
  24301. const text = !error ? null : error.message;
  24302. callbacks.onError({
  24303. code,
  24304. text
  24305. }, context, error ? error.details : null, stats);
  24306. });
  24307. }
  24308. getCacheAge() {
  24309. let result = null;
  24310. if (this.response) {
  24311. const ageHeader = this.response.headers.get('age');
  24312. result = ageHeader ? parseFloat(ageHeader) : null;
  24313. }
  24314. return result;
  24315. }
  24316. getResponseHeader(name) {
  24317. return this.response ? this.response.headers.get(name) : null;
  24318. }
  24319. loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {
  24320. const chunkCache = new ChunkCache();
  24321. const reader = response.body.getReader();
  24322. const pump = () => {
  24323. return reader.read().then(data => {
  24324. if (data.done) {
  24325. if (chunkCache.dataLength) {
  24326. onProgress(stats, context, chunkCache.flush(), response);
  24327. }
  24328. return Promise.resolve(new ArrayBuffer(0));
  24329. }
  24330. const chunk = data.value;
  24331. const len = chunk.length;
  24332. stats.loaded += len;
  24333. if (len < highWaterMark || chunkCache.dataLength) {
  24334. // The current chunk is too small to to be emitted or the cache already has data
  24335. // Push it to the cache
  24336. chunkCache.push(chunk);
  24337. if (chunkCache.dataLength >= highWaterMark) {
  24338. // flush in order to join the typed arrays
  24339. onProgress(stats, context, chunkCache.flush(), response);
  24340. }
  24341. } else {
  24342. // If there's nothing cached already, and the chache is large enough
  24343. // just emit the progress event
  24344. onProgress(stats, context, chunk, response);
  24345. }
  24346. return pump();
  24347. }).catch(() => {
  24348. /* aborted */
  24349. return Promise.reject();
  24350. });
  24351. };
  24352. return pump();
  24353. }
  24354. }
  24355. function getRequestParameters(context, signal) {
  24356. const initParams = {
  24357. method: 'GET',
  24358. mode: 'cors',
  24359. credentials: 'same-origin',
  24360. signal,
  24361. headers: new self.Headers(_extends({}, context.headers))
  24362. };
  24363. if (context.rangeEnd) {
  24364. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  24365. }
  24366. return initParams;
  24367. }
  24368. function getByteRangeLength(byteRangeHeader) {
  24369. const result = BYTERANGE.exec(byteRangeHeader);
  24370. if (result) {
  24371. return parseInt(result[2]) - parseInt(result[1]) + 1;
  24372. }
  24373. }
  24374. function getContentLength(headers) {
  24375. const contentRange = headers.get('Content-Range');
  24376. if (contentRange) {
  24377. const byteRangeLength = getByteRangeLength(contentRange);
  24378. if (isFiniteNumber(byteRangeLength)) {
  24379. return byteRangeLength;
  24380. }
  24381. }
  24382. const contentLength = headers.get('Content-Length');
  24383. if (contentLength) {
  24384. return parseInt(contentLength);
  24385. }
  24386. }
  24387. function getRequest(context, initParams) {
  24388. return new self.Request(context.url, initParams);
  24389. }
  24390. class FetchError extends Error {
  24391. constructor(message, code, details) {
  24392. super(message);
  24393. this.code = void 0;
  24394. this.details = void 0;
  24395. this.code = code;
  24396. this.details = details;
  24397. }
  24398. }
  24399. const WHITESPACE_CHAR = /\s/;
  24400. const Cues = {
  24401. newCue(track, startTime, endTime, captionScreen) {
  24402. const result = [];
  24403. let row;
  24404. // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
  24405. let cue;
  24406. let indenting;
  24407. let indent;
  24408. let text;
  24409. const Cue = self.VTTCue || self.TextTrackCue;
  24410. for (let r = 0; r < captionScreen.rows.length; r++) {
  24411. row = captionScreen.rows[r];
  24412. indenting = true;
  24413. indent = 0;
  24414. text = '';
  24415. if (!row.isEmpty()) {
  24416. var _track$cues;
  24417. for (let c = 0; c < row.chars.length; c++) {
  24418. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  24419. indent++;
  24420. } else {
  24421. text += row.chars[c].uchar;
  24422. indenting = false;
  24423. }
  24424. }
  24425. // To be used for cleaning-up orphaned roll-up captions
  24426. row.cueStartTime = startTime;
  24427. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  24428. if (startTime === endTime) {
  24429. endTime += 0.0001;
  24430. }
  24431. if (indent >= 16) {
  24432. indent--;
  24433. } else {
  24434. indent++;
  24435. }
  24436. const cueText = fixLineBreaks(text.trim());
  24437. const id = generateCueId(startTime, endTime, cueText);
  24438. // If this cue already exists in the track do not push it
  24439. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  24440. cue = new Cue(startTime, endTime, cueText);
  24441. cue.id = id;
  24442. cue.line = r + 1;
  24443. cue.align = 'left';
  24444. // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
  24445. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  24446. // Firefox throws an exception and captions break with out of bounds 0-100 values
  24447. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  24448. result.push(cue);
  24449. }
  24450. }
  24451. }
  24452. if (track && result.length) {
  24453. // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
  24454. result.sort((cueA, cueB) => {
  24455. if (cueA.line === 'auto' || cueB.line === 'auto') {
  24456. return 0;
  24457. }
  24458. if (cueA.line > 8 && cueB.line > 8) {
  24459. return cueB.line - cueA.line;
  24460. }
  24461. return cueA.line - cueB.line;
  24462. });
  24463. result.forEach(cue => addCueToTrack(track, cue));
  24464. }
  24465. return result;
  24466. }
  24467. };
  24468. /**
  24469. * @deprecated use fragLoadPolicy.default
  24470. */
  24471. /**
  24472. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  24473. */
  24474. const defaultLoadPolicy = {
  24475. maxTimeToFirstByteMs: 8000,
  24476. maxLoadTimeMs: 20000,
  24477. timeoutRetry: null,
  24478. errorRetry: null
  24479. };
  24480. /**
  24481. * @ignore
  24482. * If possible, keep hlsDefaultConfig shallow
  24483. * It is cloned whenever a new Hls instance is created, by keeping the config
  24484. * shallow the properties are cloned, and we don't end up manipulating the default
  24485. */
  24486. const hlsDefaultConfig = _objectSpread2(_objectSpread2({
  24487. autoStartLoad: true,
  24488. // used by stream-controller
  24489. startPosition: -1,
  24490. // used by stream-controller
  24491. defaultAudioCodec: undefined,
  24492. // used by stream-controller
  24493. debug: false,
  24494. // used by logger
  24495. capLevelOnFPSDrop: false,
  24496. // used by fps-controller
  24497. capLevelToPlayerSize: false,
  24498. // used by cap-level-controller
  24499. ignoreDevicePixelRatio: false,
  24500. // used by cap-level-controller
  24501. preferManagedMediaSource: true,
  24502. initialLiveManifestSize: 1,
  24503. // used by stream-controller
  24504. maxBufferLength: 30,
  24505. // used by stream-controller
  24506. backBufferLength: Infinity,
  24507. // used by buffer-controller
  24508. frontBufferFlushThreshold: Infinity,
  24509. maxBufferSize: 60 * 1000 * 1000,
  24510. // used by stream-controller
  24511. maxBufferHole: 0.1,
  24512. // used by stream-controller
  24513. highBufferWatchdogPeriod: 2,
  24514. // used by stream-controller
  24515. nudgeOffset: 0.1,
  24516. // used by stream-controller
  24517. nudgeMaxRetry: 3,
  24518. // used by stream-controller
  24519. maxFragLookUpTolerance: 0.25,
  24520. // used by stream-controller
  24521. liveSyncDurationCount: 3,
  24522. // used by latency-controller
  24523. liveMaxLatencyDurationCount: Infinity,
  24524. // used by latency-controller
  24525. liveSyncDuration: undefined,
  24526. // used by latency-controller
  24527. liveMaxLatencyDuration: undefined,
  24528. // used by latency-controller
  24529. maxLiveSyncPlaybackRate: 1,
  24530. // used by latency-controller
  24531. liveDurationInfinity: false,
  24532. // used by buffer-controller
  24533. /**
  24534. * @deprecated use backBufferLength
  24535. */
  24536. liveBackBufferLength: null,
  24537. // used by buffer-controller
  24538. maxMaxBufferLength: 600,
  24539. // used by stream-controller
  24540. enableWorker: true,
  24541. // used by transmuxer
  24542. workerPath: null,
  24543. // used by transmuxer
  24544. enableSoftwareAES: true,
  24545. // used by decrypter
  24546. startLevel: undefined,
  24547. // used by level-controller
  24548. startFragPrefetch: false,
  24549. // used by stream-controller
  24550. fpsDroppedMonitoringPeriod: 5000,
  24551. // used by fps-controller
  24552. fpsDroppedMonitoringThreshold: 0.2,
  24553. // used by fps-controller
  24554. appendErrorMaxRetry: 3,
  24555. // used by buffer-controller
  24556. loader: XhrLoader,
  24557. // loader: FetchLoader,
  24558. fLoader: undefined,
  24559. // used by fragment-loader
  24560. pLoader: undefined,
  24561. // used by playlist-loader
  24562. xhrSetup: undefined,
  24563. // used by xhr-loader
  24564. licenseXhrSetup: undefined,
  24565. // used by eme-controller
  24566. licenseResponseCallback: undefined,
  24567. // used by eme-controller
  24568. abrController: AbrController,
  24569. bufferController: BufferController,
  24570. capLevelController: CapLevelController,
  24571. errorController: ErrorController,
  24572. fpsController: FPSController,
  24573. stretchShortVideoTrack: false,
  24574. // used by mp4-remuxer
  24575. maxAudioFramesDrift: 1,
  24576. // used by mp4-remuxer
  24577. forceKeyFrameOnDiscontinuity: true,
  24578. // used by ts-demuxer
  24579. abrEwmaFastLive: 3,
  24580. // used by abr-controller
  24581. abrEwmaSlowLive: 9,
  24582. // used by abr-controller
  24583. abrEwmaFastVoD: 3,
  24584. // used by abr-controller
  24585. abrEwmaSlowVoD: 9,
  24586. // used by abr-controller
  24587. abrEwmaDefaultEstimate: 5e5,
  24588. // 500 kbps // used by abr-controller
  24589. abrEwmaDefaultEstimateMax: 5e6,
  24590. // 5 mbps
  24591. abrBandWidthFactor: 0.95,
  24592. // used by abr-controller
  24593. abrBandWidthUpFactor: 0.7,
  24594. // used by abr-controller
  24595. abrMaxWithRealBitrate: false,
  24596. // used by abr-controller
  24597. maxStarvationDelay: 4,
  24598. // used by abr-controller
  24599. maxLoadingDelay: 4,
  24600. // used by abr-controller
  24601. minAutoBitrate: 0,
  24602. // used by hls
  24603. emeEnabled: false,
  24604. // used by eme-controller
  24605. widevineLicenseUrl: undefined,
  24606. // used by eme-controller
  24607. drmSystems: {},
  24608. // used by eme-controller
  24609. drmSystemOptions: {},
  24610. // used by eme-controller
  24611. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess ,
  24612. // used by eme-controller
  24613. testBandwidth: true,
  24614. progressive: false,
  24615. lowLatencyMode: true,
  24616. cmcd: undefined,
  24617. enableDateRangeMetadataCues: true,
  24618. enableEmsgMetadataCues: true,
  24619. enableID3MetadataCues: true,
  24620. useMediaCapabilities: true,
  24621. certLoadPolicy: {
  24622. default: defaultLoadPolicy
  24623. },
  24624. keyLoadPolicy: {
  24625. default: {
  24626. maxTimeToFirstByteMs: 8000,
  24627. maxLoadTimeMs: 20000,
  24628. timeoutRetry: {
  24629. maxNumRetry: 1,
  24630. retryDelayMs: 1000,
  24631. maxRetryDelayMs: 20000,
  24632. backoff: 'linear'
  24633. },
  24634. errorRetry: {
  24635. maxNumRetry: 8,
  24636. retryDelayMs: 1000,
  24637. maxRetryDelayMs: 20000,
  24638. backoff: 'linear'
  24639. }
  24640. }
  24641. },
  24642. manifestLoadPolicy: {
  24643. default: {
  24644. maxTimeToFirstByteMs: Infinity,
  24645. maxLoadTimeMs: 20000,
  24646. timeoutRetry: {
  24647. maxNumRetry: 2,
  24648. retryDelayMs: 0,
  24649. maxRetryDelayMs: 0
  24650. },
  24651. errorRetry: {
  24652. maxNumRetry: 1,
  24653. retryDelayMs: 1000,
  24654. maxRetryDelayMs: 8000
  24655. }
  24656. }
  24657. },
  24658. playlistLoadPolicy: {
  24659. default: {
  24660. maxTimeToFirstByteMs: 10000,
  24661. maxLoadTimeMs: 20000,
  24662. timeoutRetry: {
  24663. maxNumRetry: 2,
  24664. retryDelayMs: 0,
  24665. maxRetryDelayMs: 0
  24666. },
  24667. errorRetry: {
  24668. maxNumRetry: 2,
  24669. retryDelayMs: 1000,
  24670. maxRetryDelayMs: 8000
  24671. }
  24672. }
  24673. },
  24674. fragLoadPolicy: {
  24675. default: {
  24676. maxTimeToFirstByteMs: 10000,
  24677. maxLoadTimeMs: 120000,
  24678. timeoutRetry: {
  24679. maxNumRetry: 4,
  24680. retryDelayMs: 0,
  24681. maxRetryDelayMs: 0
  24682. },
  24683. errorRetry: {
  24684. maxNumRetry: 6,
  24685. retryDelayMs: 1000,
  24686. maxRetryDelayMs: 8000
  24687. }
  24688. }
  24689. },
  24690. steeringManifestLoadPolicy: {
  24691. default: {
  24692. maxTimeToFirstByteMs: 10000,
  24693. maxLoadTimeMs: 20000,
  24694. timeoutRetry: {
  24695. maxNumRetry: 2,
  24696. retryDelayMs: 0,
  24697. maxRetryDelayMs: 0
  24698. },
  24699. errorRetry: {
  24700. maxNumRetry: 1,
  24701. retryDelayMs: 1000,
  24702. maxRetryDelayMs: 8000
  24703. }
  24704. }
  24705. },
  24706. // These default settings are deprecated in favor of the above policies
  24707. // and are maintained for backwards compatibility
  24708. manifestLoadingTimeOut: 10000,
  24709. manifestLoadingMaxRetry: 1,
  24710. manifestLoadingRetryDelay: 1000,
  24711. manifestLoadingMaxRetryTimeout: 64000,
  24712. levelLoadingTimeOut: 10000,
  24713. levelLoadingMaxRetry: 4,
  24714. levelLoadingRetryDelay: 1000,
  24715. levelLoadingMaxRetryTimeout: 64000,
  24716. fragLoadingTimeOut: 20000,
  24717. fragLoadingMaxRetry: 6,
  24718. fragLoadingRetryDelay: 1000,
  24719. fragLoadingMaxRetryTimeout: 64000
  24720. }, timelineConfig()), {}, {
  24721. subtitleStreamController: SubtitleStreamController ,
  24722. subtitleTrackController: SubtitleTrackController ,
  24723. timelineController: TimelineController ,
  24724. audioStreamController: AudioStreamController ,
  24725. audioTrackController: AudioTrackController ,
  24726. emeController: EMEController ,
  24727. cmcdController: CMCDController ,
  24728. contentSteeringController: ContentSteeringController
  24729. });
  24730. function timelineConfig() {
  24731. return {
  24732. cueHandler: Cues,
  24733. // used by timeline-controller
  24734. enableWebVTT: true,
  24735. // used by timeline-controller
  24736. enableIMSC1: true,
  24737. // used by timeline-controller
  24738. enableCEA708Captions: true,
  24739. // used by timeline-controller
  24740. captionsTextTrack1Label: 'English',
  24741. // used by timeline-controller
  24742. captionsTextTrack1LanguageCode: 'en',
  24743. // used by timeline-controller
  24744. captionsTextTrack2Label: 'Spanish',
  24745. // used by timeline-controller
  24746. captionsTextTrack2LanguageCode: 'es',
  24747. // used by timeline-controller
  24748. captionsTextTrack3Label: 'Unknown CC',
  24749. // used by timeline-controller
  24750. captionsTextTrack3LanguageCode: '',
  24751. // used by timeline-controller
  24752. captionsTextTrack4Label: 'Unknown CC',
  24753. // used by timeline-controller
  24754. captionsTextTrack4LanguageCode: '',
  24755. // used by timeline-controller
  24756. renderTextTracksNatively: true
  24757. };
  24758. }
  24759. /**
  24760. * @ignore
  24761. */
  24762. function mergeConfig(defaultConfig, userConfig) {
  24763. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  24764. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  24765. }
  24766. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  24767. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  24768. }
  24769. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  24770. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  24771. }
  24772. const defaultsCopy = deepCpy(defaultConfig);
  24773. // Backwards compatibility with deprecated config values
  24774. const deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  24775. const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  24776. deprecatedSettingTypes.forEach(type => {
  24777. const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;
  24778. const policyNotSet = userConfig[policyName] === undefined;
  24779. const report = [];
  24780. deprecatedSettings.forEach(setting => {
  24781. const deprecatedSetting = `${type}Loading${setting}`;
  24782. const value = userConfig[deprecatedSetting];
  24783. if (value !== undefined && policyNotSet) {
  24784. report.push(deprecatedSetting);
  24785. const settings = defaultsCopy[policyName].default;
  24786. userConfig[policyName] = {
  24787. default: settings
  24788. };
  24789. switch (setting) {
  24790. case 'TimeOut':
  24791. settings.maxLoadTimeMs = value;
  24792. settings.maxTimeToFirstByteMs = value;
  24793. break;
  24794. case 'MaxRetry':
  24795. settings.errorRetry.maxNumRetry = value;
  24796. settings.timeoutRetry.maxNumRetry = value;
  24797. break;
  24798. case 'RetryDelay':
  24799. settings.errorRetry.retryDelayMs = value;
  24800. settings.timeoutRetry.retryDelayMs = value;
  24801. break;
  24802. case 'MaxRetryTimeout':
  24803. settings.errorRetry.maxRetryDelayMs = value;
  24804. settings.timeoutRetry.maxRetryDelayMs = value;
  24805. break;
  24806. }
  24807. }
  24808. });
  24809. if (report.length) {
  24810. logger.warn(`hls.js config: "${report.join('", "')}" setting(s) are deprecated, use "${policyName}": ${JSON.stringify(userConfig[policyName])}`);
  24811. }
  24812. });
  24813. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  24814. }
  24815. function deepCpy(obj) {
  24816. if (obj && typeof obj === 'object') {
  24817. if (Array.isArray(obj)) {
  24818. return obj.map(deepCpy);
  24819. }
  24820. return Object.keys(obj).reduce((result, key) => {
  24821. result[key] = deepCpy(obj[key]);
  24822. return result;
  24823. }, {});
  24824. }
  24825. return obj;
  24826. }
  24827. /**
  24828. * @ignore
  24829. */
  24830. function enableStreamingMode(config) {
  24831. const currentLoader = config.loader;
  24832. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  24833. // If a developer has configured their own loader, respect that choice
  24834. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  24835. config.progressive = false;
  24836. } else {
  24837. const canStreamProgressively = fetchSupported();
  24838. if (canStreamProgressively) {
  24839. config.loader = FetchLoader;
  24840. config.progressive = true;
  24841. config.enableSoftwareAES = true;
  24842. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  24843. }
  24844. }
  24845. }
  24846. let chromeOrFirefox;
  24847. class LevelController extends BasePlaylistController {
  24848. constructor(hls, contentSteeringController) {
  24849. super(hls, '[level-controller]');
  24850. this._levels = [];
  24851. this._firstLevel = -1;
  24852. this._maxAutoLevel = -1;
  24853. this._startLevel = void 0;
  24854. this.currentLevel = null;
  24855. this.currentLevelIndex = -1;
  24856. this.manualLevelIndex = -1;
  24857. this.steering = void 0;
  24858. this.onParsedComplete = void 0;
  24859. this.steering = contentSteeringController;
  24860. this._registerListeners();
  24861. }
  24862. _registerListeners() {
  24863. const {
  24864. hls
  24865. } = this;
  24866. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24867. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24868. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24869. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  24870. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  24871. hls.on(Events.ERROR, this.onError, this);
  24872. }
  24873. _unregisterListeners() {
  24874. const {
  24875. hls
  24876. } = this;
  24877. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24878. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  24879. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  24880. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  24881. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  24882. hls.off(Events.ERROR, this.onError, this);
  24883. }
  24884. destroy() {
  24885. this._unregisterListeners();
  24886. this.steering = null;
  24887. this.resetLevels();
  24888. super.destroy();
  24889. }
  24890. stopLoad() {
  24891. const levels = this._levels;
  24892. // clean up live level details to force reload them, and reset load errors
  24893. levels.forEach(level => {
  24894. level.loadError = 0;
  24895. level.fragmentError = 0;
  24896. });
  24897. super.stopLoad();
  24898. }
  24899. resetLevels() {
  24900. this._startLevel = undefined;
  24901. this.manualLevelIndex = -1;
  24902. this.currentLevelIndex = -1;
  24903. this.currentLevel = null;
  24904. this._levels = [];
  24905. this._maxAutoLevel = -1;
  24906. }
  24907. onManifestLoading(event, data) {
  24908. this.resetLevels();
  24909. }
  24910. onManifestLoaded(event, data) {
  24911. const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  24912. const levels = [];
  24913. const redundantSet = {};
  24914. const generatePathwaySet = {};
  24915. let resolutionFound = false;
  24916. let videoCodecFound = false;
  24917. let audioCodecFound = false;
  24918. data.levels.forEach(levelParsed => {
  24919. var _audioCodec, _videoCodec;
  24920. const attributes = levelParsed.attrs;
  24921. // erase audio codec info if browser does not support mp4a.40.34.
  24922. // demuxer will autodetect codec and fallback to mpeg/audio
  24923. let {
  24924. audioCodec,
  24925. videoCodec
  24926. } = levelParsed;
  24927. if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf('mp4a.40.34')) !== -1) {
  24928. chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent));
  24929. if (chromeOrFirefox) {
  24930. levelParsed.audioCodec = audioCodec = undefined;
  24931. }
  24932. }
  24933. if (audioCodec) {
  24934. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource);
  24935. }
  24936. if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {
  24937. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  24938. }
  24939. // only keep levels with supported audio/video codecs
  24940. const {
  24941. width,
  24942. height,
  24943. unknownCodecs
  24944. } = levelParsed;
  24945. resolutionFound || (resolutionFound = !!(width && height));
  24946. videoCodecFound || (videoCodecFound = !!videoCodec);
  24947. audioCodecFound || (audioCodecFound = !!audioCodec);
  24948. if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, 'audio', preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, 'video', preferManagedMediaSource)) {
  24949. return;
  24950. }
  24951. const {
  24952. CODECS,
  24953. 'FRAME-RATE': FRAMERATE,
  24954. 'HDCP-LEVEL': HDCP,
  24955. 'PATHWAY-ID': PATHWAY,
  24956. RESOLUTION,
  24957. 'VIDEO-RANGE': VIDEO_RANGE
  24958. } = attributes;
  24959. const contentSteeringPrefix = `${PATHWAY || '.'}-`;
  24960. const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;
  24961. if (!redundantSet[levelKey]) {
  24962. const level = new Level(levelParsed);
  24963. redundantSet[levelKey] = level;
  24964. generatePathwaySet[levelKey] = 1;
  24965. levels.push(level);
  24966. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  24967. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  24968. // Content Steering controller to handles Pathway fallback on error
  24969. const pathwayCount = generatePathwaySet[levelKey] += 1;
  24970. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  24971. const level = new Level(levelParsed);
  24972. redundantSet[levelKey] = level;
  24973. levels.push(level);
  24974. } else {
  24975. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  24976. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  24977. }
  24978. });
  24979. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  24980. }
  24981. filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  24982. let audioTracks = [];
  24983. let subtitleTracks = [];
  24984. let levels = filteredLevels;
  24985. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  24986. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  24987. levels = levels.filter(({
  24988. videoCodec,
  24989. videoRange,
  24990. width,
  24991. height
  24992. }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));
  24993. }
  24994. if (levels.length === 0) {
  24995. // Dispatch error after MANIFEST_LOADED is done propagating
  24996. Promise.resolve().then(() => {
  24997. if (this.hls) {
  24998. if (data.levels.length) {
  24999. this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(data.levels[0].attrs)}`);
  25000. }
  25001. const error = new Error('no level with compatible codecs found in manifest');
  25002. this.hls.trigger(Events.ERROR, {
  25003. type: ErrorTypes.MEDIA_ERROR,
  25004. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  25005. fatal: true,
  25006. url: data.url,
  25007. error,
  25008. reason: error.message
  25009. });
  25010. }
  25011. });
  25012. return;
  25013. }
  25014. if (data.audioTracks) {
  25015. const {
  25016. preferManagedMediaSource
  25017. } = this.hls.config;
  25018. audioTracks = data.audioTracks.filter(track => !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, 'audio', preferManagedMediaSource));
  25019. // Assign ids after filtering as array indices by group-id
  25020. assignTrackIdsByGroup(audioTracks);
  25021. }
  25022. if (data.subtitles) {
  25023. subtitleTracks = data.subtitles;
  25024. assignTrackIdsByGroup(subtitleTracks);
  25025. }
  25026. // start bitrate is the first bitrate of the manifest
  25027. const unsortedLevels = levels.slice(0);
  25028. // sort levels from lowest to highest
  25029. levels.sort((a, b) => {
  25030. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  25031. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  25032. }
  25033. // sort on height before bitrate for cap-level-controller
  25034. if (resolutionFound && a.height !== b.height) {
  25035. return a.height - b.height;
  25036. }
  25037. if (a.frameRate !== b.frameRate) {
  25038. return a.frameRate - b.frameRate;
  25039. }
  25040. if (a.videoRange !== b.videoRange) {
  25041. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  25042. }
  25043. if (a.videoCodec !== b.videoCodec) {
  25044. const valueA = videoCodecPreferenceValue(a.videoCodec);
  25045. const valueB = videoCodecPreferenceValue(b.videoCodec);
  25046. if (valueA !== valueB) {
  25047. return valueB - valueA;
  25048. }
  25049. }
  25050. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  25051. const valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  25052. const valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  25053. if (valueA !== valueB) {
  25054. return valueB - valueA;
  25055. }
  25056. }
  25057. if (a.averageBitrate !== b.averageBitrate) {
  25058. return a.averageBitrate - b.averageBitrate;
  25059. }
  25060. return 0;
  25061. });
  25062. let firstLevelInPlaylist = unsortedLevels[0];
  25063. if (this.steering) {
  25064. levels = this.steering.filterParsedLevels(levels);
  25065. if (levels.length !== unsortedLevels.length) {
  25066. for (let i = 0; i < unsortedLevels.length; i++) {
  25067. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  25068. firstLevelInPlaylist = unsortedLevels[i];
  25069. break;
  25070. }
  25071. }
  25072. }
  25073. }
  25074. this._levels = levels;
  25075. // find index of first level in sorted levels
  25076. for (let i = 0; i < levels.length; i++) {
  25077. if (levels[i] === firstLevelInPlaylist) {
  25078. var _this$hls$userConfig;
  25079. this._firstLevel = i;
  25080. const firstLevelBitrate = firstLevelInPlaylist.bitrate;
  25081. const bandwidthEstimate = this.hls.bandwidthEstimate;
  25082. this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);
  25083. // Update default bwe to first variant bitrate as long it has not been configured or set
  25084. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  25085. const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  25086. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) {
  25087. this.hls.bandwidthEstimate = startingBwEstimate;
  25088. }
  25089. }
  25090. break;
  25091. }
  25092. }
  25093. // Audio is only alternate if manifest include a URI along with the audio group tag,
  25094. // and this is not an audio-only stream where levels contain audio-only
  25095. const audioOnly = audioCodecFound && !videoCodecFound;
  25096. const edata = {
  25097. levels,
  25098. audioTracks,
  25099. subtitleTracks,
  25100. sessionData: data.sessionData,
  25101. sessionKeys: data.sessionKeys,
  25102. firstLevel: this._firstLevel,
  25103. stats: data.stats,
  25104. audio: audioCodecFound,
  25105. video: videoCodecFound,
  25106. altAudio: !audioOnly && audioTracks.some(t => !!t.url)
  25107. };
  25108. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  25109. // Initiate loading after all controllers have received MANIFEST_PARSED
  25110. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  25111. this.hls.startLoad(this.hls.config.startPosition);
  25112. }
  25113. }
  25114. get levels() {
  25115. if (this._levels.length === 0) {
  25116. return null;
  25117. }
  25118. return this._levels;
  25119. }
  25120. get level() {
  25121. return this.currentLevelIndex;
  25122. }
  25123. set level(newLevel) {
  25124. const levels = this._levels;
  25125. if (levels.length === 0) {
  25126. return;
  25127. }
  25128. // check if level idx is valid
  25129. if (newLevel < 0 || newLevel >= levels.length) {
  25130. // invalid level id given, trigger error
  25131. const error = new Error('invalid level idx');
  25132. const fatal = newLevel < 0;
  25133. this.hls.trigger(Events.ERROR, {
  25134. type: ErrorTypes.OTHER_ERROR,
  25135. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  25136. level: newLevel,
  25137. fatal,
  25138. error,
  25139. reason: error.message
  25140. });
  25141. if (fatal) {
  25142. return;
  25143. }
  25144. newLevel = Math.min(newLevel, levels.length - 1);
  25145. }
  25146. const lastLevelIndex = this.currentLevelIndex;
  25147. const lastLevel = this.currentLevel;
  25148. const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  25149. const level = levels[newLevel];
  25150. const pathwayId = level.attrs['PATHWAY-ID'];
  25151. this.currentLevelIndex = newLevel;
  25152. this.currentLevel = level;
  25153. if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) {
  25154. return;
  25155. }
  25156. 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 : ''}`);
  25157. const levelSwitchingData = {
  25158. level: newLevel,
  25159. attrs: level.attrs,
  25160. details: level.details,
  25161. bitrate: level.bitrate,
  25162. averageBitrate: level.averageBitrate,
  25163. maxBitrate: level.maxBitrate,
  25164. realBitrate: level.realBitrate,
  25165. width: level.width,
  25166. height: level.height,
  25167. codecSet: level.codecSet,
  25168. audioCodec: level.audioCodec,
  25169. videoCodec: level.videoCodec,
  25170. audioGroups: level.audioGroups,
  25171. subtitleGroups: level.subtitleGroups,
  25172. loaded: level.loaded,
  25173. loadError: level.loadError,
  25174. fragmentError: level.fragmentError,
  25175. name: level.name,
  25176. id: level.id,
  25177. uri: level.uri,
  25178. url: level.url,
  25179. urlId: 0,
  25180. audioGroupIds: level.audioGroupIds,
  25181. textGroupIds: level.textGroupIds
  25182. };
  25183. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  25184. // check if we need to load playlist for this level
  25185. const levelDetails = level.details;
  25186. if (!levelDetails || levelDetails.live) {
  25187. // level not retrieved yet, or live playlist we need to (re)load it
  25188. const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  25189. this.loadPlaylist(hlsUrlParameters);
  25190. }
  25191. }
  25192. get manualLevel() {
  25193. return this.manualLevelIndex;
  25194. }
  25195. set manualLevel(newLevel) {
  25196. this.manualLevelIndex = newLevel;
  25197. if (this._startLevel === undefined) {
  25198. this._startLevel = newLevel;
  25199. }
  25200. if (newLevel !== -1) {
  25201. this.level = newLevel;
  25202. }
  25203. }
  25204. get firstLevel() {
  25205. return this._firstLevel;
  25206. }
  25207. set firstLevel(newLevel) {
  25208. this._firstLevel = newLevel;
  25209. }
  25210. get startLevel() {
  25211. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  25212. if (this._startLevel === undefined) {
  25213. const configStartLevel = this.hls.config.startLevel;
  25214. if (configStartLevel !== undefined) {
  25215. return configStartLevel;
  25216. }
  25217. return this.hls.firstAutoLevel;
  25218. }
  25219. return this._startLevel;
  25220. }
  25221. set startLevel(newLevel) {
  25222. this._startLevel = newLevel;
  25223. }
  25224. onError(event, data) {
  25225. if (data.fatal || !data.context) {
  25226. return;
  25227. }
  25228. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  25229. this.checkRetry(data);
  25230. }
  25231. }
  25232. // reset errors on the successful load of a fragment
  25233. onFragBuffered(event, {
  25234. frag
  25235. }) {
  25236. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  25237. const el = frag.elementaryStreams;
  25238. if (!Object.keys(el).some(type => !!el[type])) {
  25239. return;
  25240. }
  25241. const level = this._levels[frag.level];
  25242. if (level != null && level.loadError) {
  25243. this.log(`Resetting level error count of ${level.loadError} on frag buffered`);
  25244. level.loadError = 0;
  25245. }
  25246. }
  25247. }
  25248. onLevelLoaded(event, data) {
  25249. var _data$deliveryDirecti2;
  25250. const {
  25251. level,
  25252. details
  25253. } = data;
  25254. const curLevel = this._levels[level];
  25255. if (!curLevel) {
  25256. var _data$deliveryDirecti;
  25257. this.warn(`Invalid level index ${level}`);
  25258. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  25259. details.deltaUpdateFailed = true;
  25260. }
  25261. return;
  25262. }
  25263. // only process level loaded events matching with expected level
  25264. if (level === this.currentLevelIndex) {
  25265. // reset level load error counter on successful level loaded only if there is no issues with fragments
  25266. if (curLevel.fragmentError === 0) {
  25267. curLevel.loadError = 0;
  25268. }
  25269. this.playlistLoaded(level, data, curLevel.details);
  25270. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  25271. // received a delta playlist update that cannot be merged
  25272. details.deltaUpdateFailed = true;
  25273. }
  25274. }
  25275. loadPlaylist(hlsUrlParameters) {
  25276. super.loadPlaylist();
  25277. const currentLevelIndex = this.currentLevelIndex;
  25278. const currentLevel = this.currentLevel;
  25279. if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {
  25280. let url = currentLevel.uri;
  25281. if (hlsUrlParameters) {
  25282. try {
  25283. url = hlsUrlParameters.addDirectives(url);
  25284. } catch (error) {
  25285. this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);
  25286. }
  25287. }
  25288. const pathwayId = currentLevel.attrs['PATHWAY-ID'];
  25289. 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}`);
  25290. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  25291. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  25292. this.clearTimer();
  25293. this.hls.trigger(Events.LEVEL_LOADING, {
  25294. url,
  25295. level: currentLevelIndex,
  25296. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  25297. id: 0,
  25298. // Deprecated Level urlId
  25299. deliveryDirectives: hlsUrlParameters || null
  25300. });
  25301. }
  25302. }
  25303. get nextLoadLevel() {
  25304. if (this.manualLevelIndex !== -1) {
  25305. return this.manualLevelIndex;
  25306. } else {
  25307. return this.hls.nextAutoLevel;
  25308. }
  25309. }
  25310. set nextLoadLevel(nextLevel) {
  25311. this.level = nextLevel;
  25312. if (this.manualLevelIndex === -1) {
  25313. this.hls.nextAutoLevel = nextLevel;
  25314. }
  25315. }
  25316. removeLevel(levelIndex) {
  25317. var _this$currentLevel;
  25318. const levels = this._levels.filter((level, index) => {
  25319. if (index !== levelIndex) {
  25320. return true;
  25321. }
  25322. if (this.steering) {
  25323. this.steering.removeLevel(level);
  25324. }
  25325. if (level === this.currentLevel) {
  25326. this.currentLevel = null;
  25327. this.currentLevelIndex = -1;
  25328. if (level.details) {
  25329. level.details.fragments.forEach(f => f.level = -1);
  25330. }
  25331. }
  25332. return false;
  25333. });
  25334. reassignFragmentLevelIndexes(levels);
  25335. this._levels = levels;
  25336. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  25337. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  25338. }
  25339. this.hls.trigger(Events.LEVELS_UPDATED, {
  25340. levels
  25341. });
  25342. }
  25343. onLevelsUpdated(event, {
  25344. levels
  25345. }) {
  25346. this._levels = levels;
  25347. }
  25348. checkMaxAutoUpdated() {
  25349. const {
  25350. autoLevelCapping,
  25351. maxAutoLevel,
  25352. maxHdcpLevel
  25353. } = this.hls;
  25354. if (this._maxAutoLevel !== maxAutoLevel) {
  25355. this._maxAutoLevel = maxAutoLevel;
  25356. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  25357. autoLevelCapping,
  25358. levels: this.levels,
  25359. maxAutoLevel,
  25360. minAutoLevel: this.hls.minAutoLevel,
  25361. maxHdcpLevel
  25362. });
  25363. }
  25364. }
  25365. }
  25366. function assignTrackIdsByGroup(tracks) {
  25367. const groups = {};
  25368. tracks.forEach(track => {
  25369. const groupId = track.groupId || '';
  25370. track.id = groups[groupId] = groups[groupId] || 0;
  25371. groups[groupId]++;
  25372. });
  25373. }
  25374. class KeyLoader {
  25375. constructor(config) {
  25376. this.config = void 0;
  25377. this.keyUriToKeyInfo = {};
  25378. this.emeController = null;
  25379. this.config = config;
  25380. }
  25381. abort(type) {
  25382. for (const uri in this.keyUriToKeyInfo) {
  25383. const loader = this.keyUriToKeyInfo[uri].loader;
  25384. if (loader) {
  25385. var _loader$context;
  25386. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  25387. return;
  25388. }
  25389. loader.abort();
  25390. }
  25391. }
  25392. }
  25393. detach() {
  25394. for (const uri in this.keyUriToKeyInfo) {
  25395. const keyInfo = this.keyUriToKeyInfo[uri];
  25396. // Remove cached EME keys on detach
  25397. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  25398. delete this.keyUriToKeyInfo[uri];
  25399. }
  25400. }
  25401. }
  25402. destroy() {
  25403. this.detach();
  25404. for (const uri in this.keyUriToKeyInfo) {
  25405. const loader = this.keyUriToKeyInfo[uri].loader;
  25406. if (loader) {
  25407. loader.destroy();
  25408. }
  25409. }
  25410. this.keyUriToKeyInfo = {};
  25411. }
  25412. createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {
  25413. return new LoadError({
  25414. type: ErrorTypes.NETWORK_ERROR,
  25415. details,
  25416. fatal: false,
  25417. frag,
  25418. response,
  25419. error,
  25420. networkDetails
  25421. });
  25422. }
  25423. loadClear(loadingFrag, encryptedFragments) {
  25424. if (this.emeController && this.config.emeEnabled) {
  25425. // access key-system with nearest key on start (loaidng frag is unencrypted)
  25426. const {
  25427. sn,
  25428. cc
  25429. } = loadingFrag;
  25430. for (let i = 0; i < encryptedFragments.length; i++) {
  25431. const frag = encryptedFragments[i];
  25432. if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {
  25433. this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  25434. frag.setKeyFormat(keySystemFormat);
  25435. });
  25436. break;
  25437. }
  25438. }
  25439. }
  25440. }
  25441. load(frag) {
  25442. if (!frag.decryptdata && frag.encrypted && this.emeController) {
  25443. // Multiple keys, but none selected, resolve in eme-controller
  25444. return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {
  25445. return this.loadInternal(frag, keySystemFormat);
  25446. });
  25447. }
  25448. return this.loadInternal(frag);
  25449. }
  25450. loadInternal(frag, keySystemFormat) {
  25451. var _keyInfo, _keyInfo2;
  25452. if (keySystemFormat) {
  25453. frag.setKeyFormat(keySystemFormat);
  25454. }
  25455. const decryptdata = frag.decryptdata;
  25456. if (!decryptdata) {
  25457. const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');
  25458. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  25459. }
  25460. const uri = decryptdata.uri;
  25461. if (!uri) {
  25462. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: "${uri}"`)));
  25463. }
  25464. let keyInfo = this.keyUriToKeyInfo[uri];
  25465. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  25466. decryptdata.key = keyInfo.decryptdata.key;
  25467. return Promise.resolve({
  25468. frag,
  25469. keyInfo
  25470. });
  25471. }
  25472. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  25473. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  25474. var _keyInfo$mediaKeySess;
  25475. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  25476. case undefined:
  25477. case 'status-pending':
  25478. case 'usable':
  25479. case 'usable-in-future':
  25480. return keyInfo.keyLoadPromise.then(keyLoadedData => {
  25481. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  25482. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  25483. return {
  25484. frag,
  25485. keyInfo
  25486. };
  25487. });
  25488. }
  25489. // If we have a key session and status and it is not pending or usable, continue
  25490. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  25491. }
  25492. // Load the key or return the loading promise
  25493. keyInfo = this.keyUriToKeyInfo[uri] = {
  25494. decryptdata,
  25495. keyLoadPromise: null,
  25496. loader: null,
  25497. mediaKeySessionContext: null
  25498. };
  25499. switch (decryptdata.method) {
  25500. case 'ISO-23001-7':
  25501. case 'SAMPLE-AES':
  25502. case 'SAMPLE-AES-CENC':
  25503. case 'SAMPLE-AES-CTR':
  25504. if (decryptdata.keyFormat === 'identity') {
  25505. // loadKeyHTTP handles http(s) and data URLs
  25506. return this.loadKeyHTTP(keyInfo, frag);
  25507. }
  25508. return this.loadKeyEME(keyInfo, frag);
  25509. case 'AES-128':
  25510. return this.loadKeyHTTP(keyInfo, frag);
  25511. default:
  25512. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: "${decryptdata.method}"`)));
  25513. }
  25514. }
  25515. loadKeyEME(keyInfo, frag) {
  25516. const keyLoadedData = {
  25517. frag,
  25518. keyInfo
  25519. };
  25520. if (this.emeController && this.config.emeEnabled) {
  25521. const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  25522. if (keySessionContextPromise) {
  25523. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {
  25524. keyInfo.mediaKeySessionContext = keySessionContext;
  25525. return keyLoadedData;
  25526. })).catch(error => {
  25527. // Remove promise for license renewal or retry
  25528. keyInfo.keyLoadPromise = null;
  25529. throw error;
  25530. });
  25531. }
  25532. }
  25533. return Promise.resolve(keyLoadedData);
  25534. }
  25535. loadKeyHTTP(keyInfo, frag) {
  25536. const config = this.config;
  25537. const Loader = config.loader;
  25538. const keyLoader = new Loader(config);
  25539. frag.keyLoader = keyInfo.loader = keyLoader;
  25540. return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {
  25541. const loaderContext = {
  25542. keyInfo,
  25543. frag,
  25544. responseType: 'arraybuffer',
  25545. url: keyInfo.decryptdata.uri
  25546. };
  25547. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  25548. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  25549. // this will also align retry logic with fragment-loader
  25550. const loadPolicy = config.keyLoadPolicy.default;
  25551. const loaderConfig = {
  25552. loadPolicy,
  25553. timeout: loadPolicy.maxLoadTimeMs,
  25554. maxRetry: 0,
  25555. retryDelay: 0,
  25556. maxRetryDelay: 0
  25557. };
  25558. const loaderCallbacks = {
  25559. onSuccess: (response, stats, context, networkDetails) => {
  25560. const {
  25561. frag,
  25562. keyInfo,
  25563. url: uri
  25564. } = context;
  25565. if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {
  25566. return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  25567. }
  25568. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  25569. // detach fragment key loader on load success
  25570. frag.keyLoader = null;
  25571. keyInfo.loader = null;
  25572. resolve({
  25573. frag,
  25574. keyInfo
  25575. });
  25576. },
  25577. onError: (response, context, networkDetails, stats) => {
  25578. this.resetLoader(context);
  25579. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({
  25580. url: loaderContext.url,
  25581. data: undefined
  25582. }, response)));
  25583. },
  25584. onTimeout: (stats, context, networkDetails) => {
  25585. this.resetLoader(context);
  25586. reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  25587. },
  25588. onAbort: (stats, context, networkDetails) => {
  25589. this.resetLoader(context);
  25590. reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  25591. }
  25592. };
  25593. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  25594. });
  25595. }
  25596. resetLoader(context) {
  25597. const {
  25598. frag,
  25599. keyInfo,
  25600. url: uri
  25601. } = context;
  25602. const loader = keyInfo.loader;
  25603. if (frag.keyLoader === loader) {
  25604. frag.keyLoader = null;
  25605. keyInfo.loader = null;
  25606. }
  25607. delete this.keyUriToKeyInfo[uri];
  25608. if (loader) {
  25609. loader.destroy();
  25610. }
  25611. }
  25612. }
  25613. function getSourceBuffer() {
  25614. return self.SourceBuffer || self.WebKitSourceBuffer;
  25615. }
  25616. function isMSESupported() {
  25617. const mediaSource = getMediaSource();
  25618. if (!mediaSource) {
  25619. return false;
  25620. }
  25621. // if SourceBuffer is exposed ensure its API is valid
  25622. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  25623. const sourceBuffer = getSourceBuffer();
  25624. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  25625. }
  25626. function isSupported() {
  25627. if (!isMSESupported()) {
  25628. return false;
  25629. }
  25630. const mediaSource = getMediaSource();
  25631. 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'))));
  25632. }
  25633. function changeTypeSupported() {
  25634. var _sourceBuffer$prototy;
  25635. const sourceBuffer = getSourceBuffer();
  25636. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  25637. }
  25638. const STALL_MINIMUM_DURATION_MS = 250;
  25639. const MAX_START_GAP_JUMP = 2.0;
  25640. const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  25641. const SKIP_BUFFER_RANGE_START = 0.05;
  25642. class GapController {
  25643. constructor(config, media, fragmentTracker, hls) {
  25644. this.config = void 0;
  25645. this.media = null;
  25646. this.fragmentTracker = void 0;
  25647. this.hls = void 0;
  25648. this.nudgeRetry = 0;
  25649. this.stallReported = false;
  25650. this.stalled = null;
  25651. this.moved = false;
  25652. this.seeking = false;
  25653. this.config = config;
  25654. this.media = media;
  25655. this.fragmentTracker = fragmentTracker;
  25656. this.hls = hls;
  25657. }
  25658. destroy() {
  25659. this.media = null;
  25660. // @ts-ignore
  25661. this.hls = this.fragmentTracker = null;
  25662. }
  25663. /**
  25664. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  25665. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  25666. *
  25667. * @param lastCurrentTime - Previously read playhead position
  25668. */
  25669. poll(lastCurrentTime, activeFrag) {
  25670. const {
  25671. config,
  25672. media,
  25673. stalled
  25674. } = this;
  25675. if (media === null) {
  25676. return;
  25677. }
  25678. const {
  25679. currentTime,
  25680. seeking
  25681. } = media;
  25682. const seeked = this.seeking && !seeking;
  25683. const beginSeek = !this.seeking && seeking;
  25684. this.seeking = seeking;
  25685. // The playhead is moving, no-op
  25686. if (currentTime !== lastCurrentTime) {
  25687. this.moved = true;
  25688. if (!seeking) {
  25689. this.nudgeRetry = 0;
  25690. }
  25691. if (stalled !== null) {
  25692. // The playhead is now moving, but was previously stalled
  25693. if (this.stallReported) {
  25694. const _stalledDuration = self.performance.now() - stalled;
  25695. logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(_stalledDuration)}ms`);
  25696. this.stallReported = false;
  25697. }
  25698. this.stalled = null;
  25699. }
  25700. return;
  25701. }
  25702. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  25703. if (beginSeek || seeked) {
  25704. this.stalled = null;
  25705. return;
  25706. }
  25707. // The playhead should not be moving
  25708. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) {
  25709. this.nudgeRetry = 0;
  25710. return;
  25711. }
  25712. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  25713. const nextStart = bufferInfo.nextStart || 0;
  25714. if (seeking) {
  25715. // Waiting for seeking in a buffered range to complete
  25716. const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  25717. // Next buffered range is too far ahead to jump to while still seeking
  25718. const noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  25719. if (hasEnoughBuffer || noBufferGap) {
  25720. return;
  25721. }
  25722. // Reset moved state when seeking to a point in or before a gap
  25723. this.moved = false;
  25724. }
  25725. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  25726. // The addition poll gives the browser a chance to jump the gap for us
  25727. if (!this.moved && this.stalled !== null) {
  25728. var _level$details;
  25729. // There is no playable buffer (seeked, waiting for buffer)
  25730. const isBuffered = bufferInfo.len > 0;
  25731. if (!isBuffered && !nextStart) {
  25732. return;
  25733. }
  25734. // Jump start gaps within jump threshold
  25735. const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  25736. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  25737. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  25738. // that begins over 1 target duration after the video start position.
  25739. const level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  25740. const isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live;
  25741. const maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  25742. const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);
  25743. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  25744. if (!media.paused) {
  25745. this._trySkipBufferHole(partialOrGap);
  25746. }
  25747. return;
  25748. }
  25749. }
  25750. // Start tracking stall time
  25751. const tnow = self.performance.now();
  25752. if (stalled === null) {
  25753. this.stalled = tnow;
  25754. return;
  25755. }
  25756. const stalledDuration = tnow - stalled;
  25757. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  25758. // Report stalling after trying to fix
  25759. this._reportStall(bufferInfo);
  25760. if (!this.media) {
  25761. return;
  25762. }
  25763. }
  25764. const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  25765. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  25766. }
  25767. /**
  25768. * Detects and attempts to fix known buffer stalling issues.
  25769. * @param bufferInfo - The properties of the current buffer.
  25770. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  25771. * @private
  25772. */
  25773. _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  25774. const {
  25775. config,
  25776. fragmentTracker,
  25777. media
  25778. } = this;
  25779. if (media === null) {
  25780. return;
  25781. }
  25782. const currentTime = media.currentTime;
  25783. const partial = fragmentTracker.getPartialFragment(currentTime);
  25784. if (partial) {
  25785. // Try to skip over the buffer hole caused by a partial fragment
  25786. // This method isn't limited by the size of the gap between buffered ranges
  25787. const targetTime = this._trySkipBufferHole(partial);
  25788. // we return here in this case, meaning
  25789. // the branch below only executes when we haven't seeked to a new position
  25790. if (targetTime || !this.media) {
  25791. return;
  25792. }
  25793. }
  25794. // if we haven't had to skip over a buffer hole of a partial fragment
  25795. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  25796. // needs to cross some sort of threshold covering all source-buffers content
  25797. // to start playing properly.
  25798. if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  25799. logger.warn('Trying to nudge playhead over buffer-hole');
  25800. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  25801. // We only try to jump the hole if it's under the configured size
  25802. // Reset stalled so to rearm watchdog timer
  25803. this.stalled = null;
  25804. this._tryNudgeBuffer();
  25805. }
  25806. }
  25807. /**
  25808. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  25809. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  25810. * @private
  25811. */
  25812. _reportStall(bufferInfo) {
  25813. const {
  25814. hls,
  25815. media,
  25816. stallReported
  25817. } = this;
  25818. if (!stallReported && media) {
  25819. // Report stalled error once
  25820. this.stallReported = true;
  25821. const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${JSON.stringify(bufferInfo)})`);
  25822. logger.warn(error.message);
  25823. hls.trigger(Events.ERROR, {
  25824. type: ErrorTypes.MEDIA_ERROR,
  25825. details: ErrorDetails.BUFFER_STALLED_ERROR,
  25826. fatal: false,
  25827. error,
  25828. buffer: bufferInfo.len
  25829. });
  25830. }
  25831. }
  25832. /**
  25833. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  25834. * @param partial - The partial fragment found at the current time (where playback is stalling).
  25835. * @private
  25836. */
  25837. _trySkipBufferHole(partial) {
  25838. const {
  25839. config,
  25840. hls,
  25841. media
  25842. } = this;
  25843. if (media === null) {
  25844. return 0;
  25845. }
  25846. // Check if currentTime is between unbuffered regions of partial fragments
  25847. const currentTime = media.currentTime;
  25848. const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  25849. const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  25850. if (startTime) {
  25851. const bufferStarved = bufferInfo.len <= config.maxBufferHole;
  25852. const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  25853. const gapLength = startTime - currentTime;
  25854. if (gapLength > 0 && (bufferStarved || waiting)) {
  25855. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  25856. if (gapLength > config.maxBufferHole) {
  25857. const {
  25858. fragmentTracker
  25859. } = this;
  25860. let startGap = false;
  25861. if (currentTime === 0) {
  25862. const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  25863. if (startFrag && startTime < startFrag.end) {
  25864. startGap = true;
  25865. }
  25866. }
  25867. if (!startGap) {
  25868. const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  25869. if (startProvisioned) {
  25870. let moreToLoad = false;
  25871. let pos = startProvisioned.end;
  25872. while (pos < startTime) {
  25873. const provisioned = fragmentTracker.getPartialFragment(pos);
  25874. if (provisioned) {
  25875. pos += provisioned.duration;
  25876. } else {
  25877. moreToLoad = true;
  25878. break;
  25879. }
  25880. }
  25881. if (moreToLoad) {
  25882. return 0;
  25883. }
  25884. }
  25885. }
  25886. }
  25887. const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  25888. logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);
  25889. this.moved = true;
  25890. this.stalled = null;
  25891. media.currentTime = targetTime;
  25892. if (partial && !partial.gap) {
  25893. const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);
  25894. hls.trigger(Events.ERROR, {
  25895. type: ErrorTypes.MEDIA_ERROR,
  25896. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  25897. fatal: false,
  25898. error,
  25899. reason: error.message,
  25900. frag: partial
  25901. });
  25902. }
  25903. return targetTime;
  25904. }
  25905. }
  25906. return 0;
  25907. }
  25908. /**
  25909. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  25910. * @private
  25911. */
  25912. _tryNudgeBuffer() {
  25913. const {
  25914. config,
  25915. hls,
  25916. media,
  25917. nudgeRetry
  25918. } = this;
  25919. if (media === null) {
  25920. return;
  25921. }
  25922. const currentTime = media.currentTime;
  25923. this.nudgeRetry++;
  25924. if (nudgeRetry < config.nudgeMaxRetry) {
  25925. const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  25926. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  25927. const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);
  25928. logger.warn(error.message);
  25929. media.currentTime = targetTime;
  25930. hls.trigger(Events.ERROR, {
  25931. type: ErrorTypes.MEDIA_ERROR,
  25932. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  25933. error,
  25934. fatal: false
  25935. });
  25936. } else {
  25937. const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);
  25938. logger.error(error.message);
  25939. hls.trigger(Events.ERROR, {
  25940. type: ErrorTypes.MEDIA_ERROR,
  25941. details: ErrorDetails.BUFFER_STALLED_ERROR,
  25942. error,
  25943. fatal: true
  25944. });
  25945. }
  25946. }
  25947. }
  25948. const TICK_INTERVAL = 100; // how often to tick in ms
  25949. class StreamController extends BaseStreamController {
  25950. constructor(hls, fragmentTracker, keyLoader) {
  25951. super(hls, fragmentTracker, keyLoader, '[stream-controller]', PlaylistLevelType.MAIN);
  25952. this.audioCodecSwap = false;
  25953. this.gapController = null;
  25954. this.level = -1;
  25955. this._forceStartLoad = false;
  25956. this.altAudio = false;
  25957. this.audioOnly = false;
  25958. this.fragPlaying = null;
  25959. this.onvplaying = null;
  25960. this.onvseeked = null;
  25961. this.fragLastKbps = 0;
  25962. this.couldBacktrack = false;
  25963. this.backtrackFragment = null;
  25964. this.audioCodecSwitch = false;
  25965. this.videoBuffer = null;
  25966. this._registerListeners();
  25967. }
  25968. _registerListeners() {
  25969. const {
  25970. hls
  25971. } = this;
  25972. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  25973. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25974. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25975. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25976. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  25977. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25978. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  25979. hls.on(Events.ERROR, this.onError, this);
  25980. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  25981. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  25982. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  25983. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  25984. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  25985. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  25986. }
  25987. _unregisterListeners() {
  25988. const {
  25989. hls
  25990. } = this;
  25991. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  25992. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  25993. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  25994. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  25995. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25996. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  25997. hls.off(Events.ERROR, this.onError, this);
  25998. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  25999. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  26000. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  26001. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  26002. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  26003. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  26004. }
  26005. onHandlerDestroying() {
  26006. this._unregisterListeners();
  26007. super.onHandlerDestroying();
  26008. }
  26009. startLoad(startPosition) {
  26010. if (this.levels) {
  26011. const {
  26012. lastCurrentTime,
  26013. hls
  26014. } = this;
  26015. this.stopLoad();
  26016. this.setInterval(TICK_INTERVAL);
  26017. this.level = -1;
  26018. if (!this.startFragRequested) {
  26019. // determine load level
  26020. let startLevel = hls.startLevel;
  26021. if (startLevel === -1) {
  26022. if (hls.config.testBandwidth && this.levels.length > 1) {
  26023. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  26024. startLevel = 0;
  26025. this.bitrateTest = true;
  26026. } else {
  26027. startLevel = hls.firstAutoLevel;
  26028. }
  26029. }
  26030. // set new level to playlist loader : this will trigger start level load
  26031. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  26032. hls.nextLoadLevel = startLevel;
  26033. this.level = hls.loadLevel;
  26034. this.loadedmetadata = false;
  26035. }
  26036. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  26037. if (lastCurrentTime > 0 && startPosition === -1) {
  26038. this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);
  26039. startPosition = lastCurrentTime;
  26040. }
  26041. this.state = State.IDLE;
  26042. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  26043. this.tick();
  26044. } else {
  26045. this._forceStartLoad = true;
  26046. this.state = State.STOPPED;
  26047. }
  26048. }
  26049. stopLoad() {
  26050. this._forceStartLoad = false;
  26051. super.stopLoad();
  26052. }
  26053. doTick() {
  26054. switch (this.state) {
  26055. case State.WAITING_LEVEL:
  26056. {
  26057. const {
  26058. levels,
  26059. level
  26060. } = this;
  26061. const currentLevel = levels == null ? void 0 : levels[level];
  26062. const details = currentLevel == null ? void 0 : currentLevel.details;
  26063. if (details && (!details.live || this.levelLastLoaded === currentLevel)) {
  26064. if (this.waitForCdnTuneIn(details)) {
  26065. break;
  26066. }
  26067. this.state = State.IDLE;
  26068. break;
  26069. } else if (this.hls.nextLoadLevel !== this.level) {
  26070. this.state = State.IDLE;
  26071. break;
  26072. }
  26073. break;
  26074. }
  26075. case State.FRAG_LOADING_WAITING_RETRY:
  26076. {
  26077. var _this$media;
  26078. const now = self.performance.now();
  26079. const retryDate = this.retryDate;
  26080. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  26081. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  26082. const {
  26083. levels,
  26084. level
  26085. } = this;
  26086. const currentLevel = levels == null ? void 0 : levels[level];
  26087. this.resetStartWhenNotLoaded(currentLevel || null);
  26088. this.state = State.IDLE;
  26089. }
  26090. }
  26091. break;
  26092. }
  26093. if (this.state === State.IDLE) {
  26094. this.doTickIdle();
  26095. }
  26096. this.onTickEnd();
  26097. }
  26098. onTickEnd() {
  26099. super.onTickEnd();
  26100. this.checkBuffer();
  26101. this.checkFragmentChanged();
  26102. }
  26103. doTickIdle() {
  26104. const {
  26105. hls,
  26106. levelLastLoaded,
  26107. levels,
  26108. media
  26109. } = this;
  26110. // if start level not parsed yet OR
  26111. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  26112. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  26113. if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  26114. return;
  26115. }
  26116. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  26117. if (this.altAudio && this.audioOnly) {
  26118. return;
  26119. }
  26120. const level = hls.nextLoadLevel;
  26121. if (!(levels != null && levels[level])) {
  26122. return;
  26123. }
  26124. const levelInfo = levels[level];
  26125. // if buffer length is less than maxBufLen try to load a new fragment
  26126. const bufferInfo = this.getMainFwdBufferInfo();
  26127. if (bufferInfo === null) {
  26128. return;
  26129. }
  26130. const lastDetails = this.getLevelDetails();
  26131. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  26132. const data = {};
  26133. if (this.altAudio) {
  26134. data.type = 'video';
  26135. }
  26136. this.hls.trigger(Events.BUFFER_EOS, data);
  26137. this.state = State.ENDED;
  26138. return;
  26139. }
  26140. // set next load level : this will trigger a playlist load if needed
  26141. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  26142. this.log(`Adapting to level ${level} from level ${this.level}`);
  26143. }
  26144. this.level = hls.nextLoadLevel = level;
  26145. const levelDetails = levelInfo.details;
  26146. // if level info not retrieved yet, switch state and wait for level retrieval
  26147. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  26148. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  26149. if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) {
  26150. this.level = level;
  26151. this.state = State.WAITING_LEVEL;
  26152. return;
  26153. }
  26154. const bufferLen = bufferInfo.len;
  26155. // 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
  26156. const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  26157. // Stay idle if we are still with buffer margins
  26158. if (bufferLen >= maxBufLen) {
  26159. return;
  26160. }
  26161. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  26162. this.backtrackFragment = null;
  26163. }
  26164. const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  26165. let frag = this.getNextFragment(targetBufferTime, levelDetails);
  26166. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  26167. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  26168. var _this$backtrackFragme;
  26169. const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  26170. const fragIdx = backtrackSn - levelDetails.startSN;
  26171. const backtrackFrag = levelDetails.fragments[fragIdx - 1];
  26172. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  26173. frag = backtrackFrag;
  26174. this.fragmentTracker.removeFragment(backtrackFrag);
  26175. }
  26176. } else if (this.backtrackFragment && bufferInfo.len) {
  26177. this.backtrackFragment = null;
  26178. }
  26179. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  26180. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  26181. const gapStart = frag.gap;
  26182. if (!gapStart) {
  26183. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  26184. const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  26185. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  26186. if (mediaBuffer) {
  26187. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  26188. }
  26189. }
  26190. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  26191. }
  26192. if (!frag) {
  26193. return;
  26194. }
  26195. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  26196. frag = frag.initSegment;
  26197. }
  26198. this.loadFragment(frag, levelInfo, targetBufferTime);
  26199. }
  26200. loadFragment(frag, level, targetBufferTime) {
  26201. // Check if fragment is not loaded
  26202. const fragState = this.fragmentTracker.getState(frag);
  26203. this.fragCurrent = frag;
  26204. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  26205. if (frag.sn === 'initSegment') {
  26206. this._loadInitSegment(frag, level);
  26207. } else if (this.bitrateTest) {
  26208. this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);
  26209. this._loadBitrateTestFrag(frag, level);
  26210. } else {
  26211. this.startFragRequested = true;
  26212. super.loadFragment(frag, level, targetBufferTime);
  26213. }
  26214. } else {
  26215. this.clearTrackerIfNeeded(frag);
  26216. }
  26217. }
  26218. getBufferedFrag(position) {
  26219. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  26220. }
  26221. followingBufferedFrag(frag) {
  26222. if (frag) {
  26223. // try to get range of next fragment (500ms after this range)
  26224. return this.getBufferedFrag(frag.end + 0.5);
  26225. }
  26226. return null;
  26227. }
  26228. /*
  26229. on immediate level switch :
  26230. - pause playback if playing
  26231. - cancel any pending load request
  26232. - and trigger a buffer flush
  26233. */
  26234. immediateLevelSwitch() {
  26235. this.abortCurrentFrag();
  26236. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  26237. }
  26238. /**
  26239. * try to switch ASAP without breaking video playback:
  26240. * in order to ensure smooth but quick level switching,
  26241. * we need to find the next flushable buffer range
  26242. * we should take into account new segment fetch time
  26243. */
  26244. nextLevelSwitch() {
  26245. const {
  26246. levels,
  26247. media
  26248. } = this;
  26249. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  26250. if (media != null && media.readyState) {
  26251. let fetchdelay;
  26252. const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  26253. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  26254. // flush buffer preceding current fragment (flush until current fragment start offset)
  26255. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  26256. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  26257. }
  26258. const levelDetails = this.getLevelDetails();
  26259. if (levelDetails != null && levelDetails.live) {
  26260. const bufferInfo = this.getMainFwdBufferInfo();
  26261. // Do not flush in live stream with low buffer
  26262. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  26263. return;
  26264. }
  26265. }
  26266. if (!media.paused && levels) {
  26267. // add a safety delay of 1s
  26268. const nextLevelId = this.hls.nextLoadLevel;
  26269. const nextLevel = levels[nextLevelId];
  26270. const fragLastKbps = this.fragLastKbps;
  26271. if (fragLastKbps && this.fragCurrent) {
  26272. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  26273. } else {
  26274. fetchdelay = 0;
  26275. }
  26276. } else {
  26277. fetchdelay = 0;
  26278. }
  26279. // this.log('fetchdelay:'+fetchdelay);
  26280. // find buffer range that will be reached once new fragment will be fetched
  26281. const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  26282. if (bufferedFrag) {
  26283. // we can flush buffer range following this one without stalling playback
  26284. const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  26285. if (nextBufferedFrag) {
  26286. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  26287. this.abortCurrentFrag();
  26288. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  26289. const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  26290. const fragDuration = nextBufferedFrag.duration;
  26291. 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)));
  26292. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  26293. }
  26294. }
  26295. }
  26296. }
  26297. abortCurrentFrag() {
  26298. const fragCurrent = this.fragCurrent;
  26299. this.fragCurrent = null;
  26300. this.backtrackFragment = null;
  26301. if (fragCurrent) {
  26302. fragCurrent.abortRequests();
  26303. this.fragmentTracker.removeFragment(fragCurrent);
  26304. }
  26305. switch (this.state) {
  26306. case State.KEY_LOADING:
  26307. case State.FRAG_LOADING:
  26308. case State.FRAG_LOADING_WAITING_RETRY:
  26309. case State.PARSING:
  26310. case State.PARSED:
  26311. this.state = State.IDLE;
  26312. break;
  26313. }
  26314. this.nextLoadPosition = this.getLoadPosition();
  26315. }
  26316. flushMainBuffer(startOffset, endOffset) {
  26317. super.flushMainBuffer(startOffset, endOffset, this.altAudio ? 'video' : null);
  26318. }
  26319. onMediaAttached(event, data) {
  26320. super.onMediaAttached(event, data);
  26321. const media = data.media;
  26322. this.onvplaying = this.onMediaPlaying.bind(this);
  26323. this.onvseeked = this.onMediaSeeked.bind(this);
  26324. media.addEventListener('playing', this.onvplaying);
  26325. media.addEventListener('seeked', this.onvseeked);
  26326. this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls);
  26327. }
  26328. onMediaDetaching() {
  26329. const {
  26330. media
  26331. } = this;
  26332. if (media && this.onvplaying && this.onvseeked) {
  26333. media.removeEventListener('playing', this.onvplaying);
  26334. media.removeEventListener('seeked', this.onvseeked);
  26335. this.onvplaying = this.onvseeked = null;
  26336. this.videoBuffer = null;
  26337. }
  26338. this.fragPlaying = null;
  26339. if (this.gapController) {
  26340. this.gapController.destroy();
  26341. this.gapController = null;
  26342. }
  26343. super.onMediaDetaching();
  26344. }
  26345. onMediaPlaying() {
  26346. // tick to speed up FRAG_CHANGED triggering
  26347. this.tick();
  26348. }
  26349. onMediaSeeked() {
  26350. const media = this.media;
  26351. const currentTime = media ? media.currentTime : null;
  26352. if (isFiniteNumber(currentTime)) {
  26353. this.log(`Media seeked to ${currentTime.toFixed(3)}`);
  26354. }
  26355. // If seeked was issued before buffer was appended do not tick immediately
  26356. const bufferInfo = this.getMainFwdBufferInfo();
  26357. if (bufferInfo === null || bufferInfo.len === 0) {
  26358. this.warn(`Main forward buffer length on "seeked" event ${bufferInfo ? bufferInfo.len : 'empty'})`);
  26359. return;
  26360. }
  26361. // tick to speed up FRAG_CHANGED triggering
  26362. this.tick();
  26363. }
  26364. onManifestLoading() {
  26365. // reset buffer on manifest loading
  26366. this.log('Trigger BUFFER_RESET');
  26367. this.hls.trigger(Events.BUFFER_RESET, undefined);
  26368. this.fragmentTracker.removeAllFragments();
  26369. this.couldBacktrack = false;
  26370. this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
  26371. this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null;
  26372. this.altAudio = this.audioOnly = this.startFragRequested = false;
  26373. }
  26374. onManifestParsed(event, data) {
  26375. // detect if we have different kind of audio codecs used amongst playlists
  26376. let aac = false;
  26377. let heaac = false;
  26378. data.levels.forEach(level => {
  26379. const codec = level.audioCodec;
  26380. if (codec) {
  26381. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  26382. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  26383. }
  26384. });
  26385. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  26386. if (this.audioCodecSwitch) {
  26387. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  26388. }
  26389. this.levels = data.levels;
  26390. this.startFragRequested = false;
  26391. }
  26392. onLevelLoading(event, data) {
  26393. const {
  26394. levels
  26395. } = this;
  26396. if (!levels || this.state !== State.IDLE) {
  26397. return;
  26398. }
  26399. const level = levels[data.level];
  26400. if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) {
  26401. this.state = State.WAITING_LEVEL;
  26402. }
  26403. }
  26404. onLevelLoaded(event, data) {
  26405. var _curLevel$details;
  26406. const {
  26407. levels
  26408. } = this;
  26409. const newLevelId = data.level;
  26410. const newDetails = data.details;
  26411. const duration = newDetails.totalduration;
  26412. if (!levels) {
  26413. this.warn(`Levels were reset while loading level ${newLevelId}`);
  26414. return;
  26415. }
  26416. this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);
  26417. const curLevel = levels[newLevelId];
  26418. const fragCurrent = this.fragCurrent;
  26419. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  26420. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  26421. this.abortCurrentFrag();
  26422. }
  26423. }
  26424. let sliding = 0;
  26425. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  26426. var _this$levelLastLoaded;
  26427. this.checkLiveUpdate(newDetails);
  26428. if (newDetails.deltaUpdateFailed) {
  26429. return;
  26430. }
  26431. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  26432. }
  26433. // override level info
  26434. curLevel.details = newDetails;
  26435. this.levelLastLoaded = curLevel;
  26436. this.hls.trigger(Events.LEVEL_UPDATED, {
  26437. details: newDetails,
  26438. level: newLevelId
  26439. });
  26440. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  26441. if (this.state === State.WAITING_LEVEL) {
  26442. if (this.waitForCdnTuneIn(newDetails)) {
  26443. // Wait for Low-Latency CDN Tune-in
  26444. return;
  26445. }
  26446. this.state = State.IDLE;
  26447. }
  26448. if (!this.startFragRequested) {
  26449. this.setStartPosition(newDetails, sliding);
  26450. } else if (newDetails.live) {
  26451. this.synchronizeToLiveEdge(newDetails);
  26452. }
  26453. // trigger handler right now
  26454. this.tick();
  26455. }
  26456. _handleFragmentLoadProgress(data) {
  26457. var _frag$initSegment;
  26458. const {
  26459. frag,
  26460. part,
  26461. payload
  26462. } = data;
  26463. const {
  26464. levels
  26465. } = this;
  26466. if (!levels) {
  26467. this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);
  26468. return;
  26469. }
  26470. const currentLevel = levels[frag.level];
  26471. const details = currentLevel.details;
  26472. if (!details) {
  26473. this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);
  26474. this.fragmentTracker.removeFragment(frag);
  26475. return;
  26476. }
  26477. const videoCodec = currentLevel.videoCodec;
  26478. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  26479. const accurateTimeOffset = details.PTSKnown || !details.live;
  26480. const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  26481. const audioCodec = this._getAudioCodec(currentLevel);
  26482. // transmux the MPEG-TS data to ISO-BMFF segments
  26483. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  26484. const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  26485. const partIndex = part ? part.index : -1;
  26486. const partial = partIndex !== -1;
  26487. const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  26488. const initPTS = this.initPTS[frag.cc];
  26489. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  26490. }
  26491. onAudioTrackSwitching(event, data) {
  26492. // if any URL found on new audio track, it is an alternate audio track
  26493. const fromAltAudio = this.altAudio;
  26494. const altAudio = !!data.url;
  26495. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  26496. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  26497. // we will just have to change buffer scheduling on audioTrackSwitched
  26498. if (!altAudio) {
  26499. if (this.mediaBuffer !== this.media) {
  26500. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  26501. this.mediaBuffer = this.media;
  26502. const fragCurrent = this.fragCurrent;
  26503. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  26504. if (fragCurrent) {
  26505. this.log('Switching to main audio track, cancel main fragment load');
  26506. fragCurrent.abortRequests();
  26507. this.fragmentTracker.removeFragment(fragCurrent);
  26508. }
  26509. // destroy transmuxer to force init segment generation (following audio switch)
  26510. this.resetTransmuxer();
  26511. // switch to IDLE state to load new fragment
  26512. this.resetLoadingState();
  26513. } else if (this.audioOnly) {
  26514. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  26515. this.resetTransmuxer();
  26516. }
  26517. const hls = this.hls;
  26518. // If switching from alt to main audio, flush all audio and trigger track switched
  26519. if (fromAltAudio) {
  26520. hls.trigger(Events.BUFFER_FLUSHING, {
  26521. startOffset: 0,
  26522. endOffset: Number.POSITIVE_INFINITY,
  26523. type: null
  26524. });
  26525. this.fragmentTracker.removeAllFragments();
  26526. }
  26527. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  26528. }
  26529. }
  26530. onAudioTrackSwitched(event, data) {
  26531. const trackId = data.id;
  26532. const altAudio = !!this.hls.audioTracks[trackId].url;
  26533. if (altAudio) {
  26534. const videoBuffer = this.videoBuffer;
  26535. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  26536. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  26537. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  26538. this.mediaBuffer = videoBuffer;
  26539. }
  26540. }
  26541. this.altAudio = altAudio;
  26542. this.tick();
  26543. }
  26544. onBufferCreated(event, data) {
  26545. const tracks = data.tracks;
  26546. let mediaTrack;
  26547. let name;
  26548. let alternate = false;
  26549. for (const type in tracks) {
  26550. const track = tracks[type];
  26551. if (track.id === 'main') {
  26552. name = type;
  26553. mediaTrack = track;
  26554. // keep video source buffer reference
  26555. if (type === 'video') {
  26556. const videoTrack = tracks[type];
  26557. if (videoTrack) {
  26558. this.videoBuffer = videoTrack.buffer;
  26559. }
  26560. }
  26561. } else {
  26562. alternate = true;
  26563. }
  26564. }
  26565. if (alternate && mediaTrack) {
  26566. this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);
  26567. this.mediaBuffer = mediaTrack.buffer;
  26568. } else {
  26569. this.mediaBuffer = this.media;
  26570. }
  26571. }
  26572. onFragBuffered(event, data) {
  26573. const {
  26574. frag,
  26575. part
  26576. } = data;
  26577. if (frag && frag.type !== PlaylistLevelType.MAIN) {
  26578. return;
  26579. }
  26580. if (this.fragContextChanged(frag)) {
  26581. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  26582. // Avoid setting state back to IDLE, since that will interfere with a level switch
  26583. this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);
  26584. if (this.state === State.PARSED) {
  26585. this.state = State.IDLE;
  26586. }
  26587. return;
  26588. }
  26589. const stats = part ? part.stats : frag.stats;
  26590. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  26591. if (frag.sn !== 'initSegment') {
  26592. this.fragPrevious = frag;
  26593. }
  26594. this.fragBufferedComplete(frag, part);
  26595. }
  26596. onError(event, data) {
  26597. var _data$context;
  26598. if (data.fatal) {
  26599. this.state = State.ERROR;
  26600. return;
  26601. }
  26602. switch (data.details) {
  26603. case ErrorDetails.FRAG_GAP:
  26604. case ErrorDetails.FRAG_PARSING_ERROR:
  26605. case ErrorDetails.FRAG_DECRYPT_ERROR:
  26606. case ErrorDetails.FRAG_LOAD_ERROR:
  26607. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  26608. case ErrorDetails.KEY_LOAD_ERROR:
  26609. case ErrorDetails.KEY_LOAD_TIMEOUT:
  26610. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  26611. break;
  26612. case ErrorDetails.LEVEL_LOAD_ERROR:
  26613. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  26614. case ErrorDetails.LEVEL_PARSING_ERROR:
  26615. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  26616. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  26617. this.state = State.IDLE;
  26618. }
  26619. break;
  26620. case ErrorDetails.BUFFER_APPEND_ERROR:
  26621. case ErrorDetails.BUFFER_FULL_ERROR:
  26622. if (!data.parent || data.parent !== 'main') {
  26623. return;
  26624. }
  26625. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  26626. this.resetLoadingState();
  26627. return;
  26628. }
  26629. if (this.reduceLengthAndFlushBuffer(data)) {
  26630. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  26631. }
  26632. break;
  26633. case ErrorDetails.INTERNAL_EXCEPTION:
  26634. this.recoverWorkerError(data);
  26635. break;
  26636. }
  26637. }
  26638. // Checks the health of the buffer and attempts to resolve playback stalls.
  26639. checkBuffer() {
  26640. const {
  26641. media,
  26642. gapController
  26643. } = this;
  26644. if (!media || !gapController || !media.readyState) {
  26645. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  26646. return;
  26647. }
  26648. if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
  26649. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  26650. const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;
  26651. gapController.poll(this.lastCurrentTime, activeFrag);
  26652. }
  26653. this.lastCurrentTime = media.currentTime;
  26654. }
  26655. onFragLoadEmergencyAborted() {
  26656. this.state = State.IDLE;
  26657. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  26658. // in that case, reset startFragRequested flag
  26659. if (!this.loadedmetadata) {
  26660. this.startFragRequested = false;
  26661. this.nextLoadPosition = this.startPosition;
  26662. }
  26663. this.tickImmediate();
  26664. }
  26665. onBufferFlushed(event, {
  26666. type
  26667. }) {
  26668. if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  26669. const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  26670. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  26671. this.tick();
  26672. }
  26673. }
  26674. onLevelsUpdated(event, data) {
  26675. if (this.level > -1 && this.fragCurrent) {
  26676. this.level = this.fragCurrent.level;
  26677. }
  26678. this.levels = data.levels;
  26679. }
  26680. swapAudioCodec() {
  26681. this.audioCodecSwap = !this.audioCodecSwap;
  26682. }
  26683. /**
  26684. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  26685. */
  26686. seekToStartPos() {
  26687. const {
  26688. media
  26689. } = this;
  26690. if (!media) {
  26691. return;
  26692. }
  26693. const currentTime = media.currentTime;
  26694. let startPosition = this.startPosition;
  26695. // only adjust currentTime if different from startPosition or if startPosition not buffered
  26696. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  26697. if (startPosition >= 0 && currentTime < startPosition) {
  26698. if (media.seeking) {
  26699. this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);
  26700. return;
  26701. }
  26702. const buffered = BufferHelper.getBuffered(media);
  26703. const bufferStart = buffered.length ? buffered.start(0) : 0;
  26704. const delta = bufferStart - startPosition;
  26705. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  26706. this.log(`adjusting start position by ${delta} to match buffer start`);
  26707. startPosition += delta;
  26708. this.startPosition = startPosition;
  26709. }
  26710. this.log(`seek to target start position ${startPosition} from current time ${currentTime}`);
  26711. media.currentTime = startPosition;
  26712. }
  26713. }
  26714. _getAudioCodec(currentLevel) {
  26715. let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  26716. if (this.audioCodecSwap && audioCodec) {
  26717. this.log('Swapping audio codec');
  26718. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  26719. audioCodec = 'mp4a.40.2';
  26720. } else {
  26721. audioCodec = 'mp4a.40.5';
  26722. }
  26723. }
  26724. return audioCodec;
  26725. }
  26726. _loadBitrateTestFrag(frag, level) {
  26727. frag.bitrateTest = true;
  26728. this._doFragLoad(frag, level).then(data => {
  26729. const {
  26730. hls
  26731. } = this;
  26732. if (!data || this.fragContextChanged(frag)) {
  26733. return;
  26734. }
  26735. level.fragmentError = 0;
  26736. this.state = State.IDLE;
  26737. this.startFragRequested = false;
  26738. this.bitrateTest = false;
  26739. const stats = frag.stats;
  26740. // Bitrate tests fragments are neither parsed nor buffered
  26741. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  26742. hls.trigger(Events.FRAG_LOADED, data);
  26743. frag.bitrateTest = false;
  26744. });
  26745. }
  26746. _handleTransmuxComplete(transmuxResult) {
  26747. var _id3$samples;
  26748. const id = 'main';
  26749. const {
  26750. hls
  26751. } = this;
  26752. const {
  26753. remuxResult,
  26754. chunkMeta
  26755. } = transmuxResult;
  26756. const context = this.getCurrentContext(chunkMeta);
  26757. if (!context) {
  26758. this.resetWhenMissingContext(chunkMeta);
  26759. return;
  26760. }
  26761. const {
  26762. frag,
  26763. part,
  26764. level
  26765. } = context;
  26766. const {
  26767. video,
  26768. text,
  26769. id3,
  26770. initSegment
  26771. } = remuxResult;
  26772. const {
  26773. details
  26774. } = level;
  26775. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  26776. const audio = this.altAudio ? undefined : remuxResult.audio;
  26777. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  26778. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  26779. if (this.fragContextChanged(frag)) {
  26780. this.fragmentTracker.removeFragment(frag);
  26781. return;
  26782. }
  26783. this.state = State.PARSING;
  26784. if (initSegment) {
  26785. if (initSegment != null && initSegment.tracks) {
  26786. const mapFragment = frag.initSegment || frag;
  26787. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  26788. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  26789. frag: mapFragment,
  26790. id,
  26791. tracks: initSegment.tracks
  26792. });
  26793. }
  26794. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  26795. const initPTS = initSegment.initPTS;
  26796. const timescale = initSegment.timescale;
  26797. if (isFiniteNumber(initPTS)) {
  26798. this.initPTS[frag.cc] = {
  26799. baseTime: initPTS,
  26800. timescale
  26801. };
  26802. hls.trigger(Events.INIT_PTS_FOUND, {
  26803. frag,
  26804. id,
  26805. initPTS,
  26806. timescale
  26807. });
  26808. }
  26809. }
  26810. // Avoid buffering if backtracking this fragment
  26811. if (video && details && frag.sn !== 'initSegment') {
  26812. const prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  26813. const isFirstFragment = frag.sn === details.startSN;
  26814. const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  26815. if (remuxResult.independent !== false) {
  26816. const {
  26817. startPTS,
  26818. endPTS,
  26819. startDTS,
  26820. endDTS
  26821. } = video;
  26822. if (part) {
  26823. part.elementaryStreams[video.type] = {
  26824. startPTS,
  26825. endPTS,
  26826. startDTS,
  26827. endDTS
  26828. };
  26829. } else {
  26830. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  26831. this.couldBacktrack = true;
  26832. }
  26833. if (video.dropped && video.independent) {
  26834. // Backtrack if dropped frames create a gap after currentTime
  26835. const bufferInfo = this.getMainFwdBufferInfo();
  26836. const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  26837. const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  26838. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  26839. this.backtrack(frag);
  26840. return;
  26841. } else if (isFirstInDiscontinuity) {
  26842. // Mark segment with a gap to avoid loop loading
  26843. frag.gap = true;
  26844. }
  26845. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  26846. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  26847. } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {
  26848. // Mark segment with a gap to skip large start gap
  26849. frag.gap = true;
  26850. }
  26851. }
  26852. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  26853. if (this.backtrackFragment) {
  26854. this.backtrackFragment = frag;
  26855. }
  26856. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  26857. } else if (isFirstFragment || isFirstInDiscontinuity) {
  26858. // Mark segment with a gap to avoid loop loading
  26859. frag.gap = true;
  26860. } else {
  26861. this.backtrack(frag);
  26862. return;
  26863. }
  26864. }
  26865. if (audio) {
  26866. const {
  26867. startPTS,
  26868. endPTS,
  26869. startDTS,
  26870. endDTS
  26871. } = audio;
  26872. if (part) {
  26873. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  26874. startPTS,
  26875. endPTS,
  26876. startDTS,
  26877. endDTS
  26878. };
  26879. }
  26880. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  26881. this.bufferFragmentData(audio, frag, part, chunkMeta);
  26882. }
  26883. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  26884. const emittedID3 = {
  26885. id,
  26886. frag,
  26887. details,
  26888. samples: id3.samples
  26889. };
  26890. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  26891. }
  26892. if (details && text) {
  26893. const emittedText = {
  26894. id,
  26895. frag,
  26896. details,
  26897. samples: text.samples
  26898. };
  26899. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  26900. }
  26901. }
  26902. _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  26903. if (this.state !== State.PARSING) {
  26904. return;
  26905. }
  26906. this.audioOnly = !!tracks.audio && !tracks.video;
  26907. // if audio track is expected to come from audio stream controller, discard any coming from main
  26908. if (this.altAudio && !this.audioOnly) {
  26909. delete tracks.audio;
  26910. }
  26911. // include levelCodec in audio and video tracks
  26912. const {
  26913. audio,
  26914. video,
  26915. audiovideo
  26916. } = tracks;
  26917. if (audio) {
  26918. let audioCodec = currentLevel.audioCodec;
  26919. const ua = navigator.userAgent.toLowerCase();
  26920. if (this.audioCodecSwitch) {
  26921. if (audioCodec) {
  26922. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  26923. audioCodec = 'mp4a.40.2';
  26924. } else {
  26925. audioCodec = 'mp4a.40.5';
  26926. }
  26927. }
  26928. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  26929. // force HE-AAC, as it seems that most browsers prefers it.
  26930. // don't force HE-AAC if mono stream, or in Firefox
  26931. const audioMetadata = audio.metadata;
  26932. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  26933. audioCodec = 'mp4a.40.5';
  26934. }
  26935. }
  26936. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  26937. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  26938. // Exclude mpeg audio
  26939. audioCodec = 'mp4a.40.2';
  26940. this.log(`Android: force audio codec to ${audioCodec}`);
  26941. }
  26942. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  26943. this.log(`Swapping manifest audio codec "${currentLevel.audioCodec}" for "${audioCodec}"`);
  26944. }
  26945. audio.levelCodec = audioCodec;
  26946. audio.id = 'main';
  26947. this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${currentLevel.audioCodec || ''}/${audio.codec}]`);
  26948. }
  26949. if (video) {
  26950. video.levelCodec = currentLevel.videoCodec;
  26951. video.id = 'main';
  26952. this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${video.codec}]`);
  26953. }
  26954. if (audiovideo) {
  26955. this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);
  26956. }
  26957. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  26958. // loop through tracks that are going to be provided to bufferController
  26959. Object.keys(tracks).forEach(trackName => {
  26960. const track = tracks[trackName];
  26961. const initSegment = track.initSegment;
  26962. if (initSegment != null && initSegment.byteLength) {
  26963. this.hls.trigger(Events.BUFFER_APPENDING, {
  26964. type: trackName,
  26965. data: initSegment,
  26966. frag,
  26967. part: null,
  26968. chunkMeta,
  26969. parent: frag.type
  26970. });
  26971. }
  26972. });
  26973. // trigger handler right now
  26974. this.tickImmediate();
  26975. }
  26976. getMainFwdBufferInfo() {
  26977. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN);
  26978. }
  26979. backtrack(frag) {
  26980. this.couldBacktrack = true;
  26981. // Causes findFragments to backtrack through fragments to find the keyframe
  26982. this.backtrackFragment = frag;
  26983. this.resetTransmuxer();
  26984. this.flushBufferGap(frag);
  26985. this.fragmentTracker.removeFragment(frag);
  26986. this.fragPrevious = null;
  26987. this.nextLoadPosition = frag.start;
  26988. this.state = State.IDLE;
  26989. }
  26990. checkFragmentChanged() {
  26991. const video = this.media;
  26992. let fragPlayingCurrent = null;
  26993. if (video && video.readyState > 1 && video.seeking === false) {
  26994. const currentTime = video.currentTime;
  26995. /* if video element is in seeked state, currentTime can only increase.
  26996. (assuming that playback rate is positive ...)
  26997. As sometimes currentTime jumps back to zero after a
  26998. media decode error, check this, to avoid seeking back to
  26999. wrong position after a media decode error
  27000. */
  27001. if (BufferHelper.isBuffered(video, currentTime)) {
  27002. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  27003. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  27004. /* ensure that FRAG_CHANGED event is triggered at startup,
  27005. when first video frame is displayed and playback is paused.
  27006. add a tolerance of 100ms, in case current position is not buffered,
  27007. check if current pos+100ms is buffered and use that buffer range
  27008. for FRAG_CHANGED event reporting */
  27009. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  27010. }
  27011. if (fragPlayingCurrent) {
  27012. this.backtrackFragment = null;
  27013. const fragPlaying = this.fragPlaying;
  27014. const fragCurrentLevel = fragPlayingCurrent.level;
  27015. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  27016. this.fragPlaying = fragPlayingCurrent;
  27017. this.hls.trigger(Events.FRAG_CHANGED, {
  27018. frag: fragPlayingCurrent
  27019. });
  27020. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  27021. this.hls.trigger(Events.LEVEL_SWITCHED, {
  27022. level: fragCurrentLevel
  27023. });
  27024. }
  27025. }
  27026. }
  27027. }
  27028. }
  27029. get nextLevel() {
  27030. const frag = this.nextBufferedFrag;
  27031. if (frag) {
  27032. return frag.level;
  27033. }
  27034. return -1;
  27035. }
  27036. get currentFrag() {
  27037. const media = this.media;
  27038. if (media) {
  27039. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  27040. }
  27041. return null;
  27042. }
  27043. get currentProgramDateTime() {
  27044. const media = this.media;
  27045. if (media) {
  27046. const currentTime = media.currentTime;
  27047. const frag = this.currentFrag;
  27048. if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) {
  27049. const epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  27050. return new Date(epocMs);
  27051. }
  27052. }
  27053. return null;
  27054. }
  27055. get currentLevel() {
  27056. const frag = this.currentFrag;
  27057. if (frag) {
  27058. return frag.level;
  27059. }
  27060. return -1;
  27061. }
  27062. get nextBufferedFrag() {
  27063. const frag = this.currentFrag;
  27064. if (frag) {
  27065. return this.followingBufferedFrag(frag);
  27066. }
  27067. return null;
  27068. }
  27069. get forceStartLoad() {
  27070. return this._forceStartLoad;
  27071. }
  27072. }
  27073. /**
  27074. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  27075. * @public
  27076. */
  27077. class Hls {
  27078. /**
  27079. * Get the video-dev/hls.js package version.
  27080. */
  27081. static get version() {
  27082. return "1.5.11";
  27083. }
  27084. /**
  27085. * Check if the required MediaSource Extensions are available.
  27086. */
  27087. static isMSESupported() {
  27088. return isMSESupported();
  27089. }
  27090. /**
  27091. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  27092. */
  27093. static isSupported() {
  27094. return isSupported();
  27095. }
  27096. /**
  27097. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  27098. */
  27099. static getMediaSource() {
  27100. return getMediaSource();
  27101. }
  27102. static get Events() {
  27103. return Events;
  27104. }
  27105. static get ErrorTypes() {
  27106. return ErrorTypes;
  27107. }
  27108. static get ErrorDetails() {
  27109. return ErrorDetails;
  27110. }
  27111. /**
  27112. * Get the default configuration applied to new instances.
  27113. */
  27114. static get DefaultConfig() {
  27115. if (!Hls.defaultConfig) {
  27116. return hlsDefaultConfig;
  27117. }
  27118. return Hls.defaultConfig;
  27119. }
  27120. /**
  27121. * Replace the default configuration applied to new instances.
  27122. */
  27123. static set DefaultConfig(defaultConfig) {
  27124. Hls.defaultConfig = defaultConfig;
  27125. }
  27126. /**
  27127. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  27128. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  27129. */
  27130. constructor(userConfig = {}) {
  27131. /**
  27132. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  27133. */
  27134. this.config = void 0;
  27135. /**
  27136. * The configuration object provided on player instantiation.
  27137. */
  27138. this.userConfig = void 0;
  27139. this.coreComponents = void 0;
  27140. this.networkControllers = void 0;
  27141. this.started = false;
  27142. this._emitter = new EventEmitter();
  27143. this._autoLevelCapping = -1;
  27144. this._maxHdcpLevel = null;
  27145. this.abrController = void 0;
  27146. this.bufferController = void 0;
  27147. this.capLevelController = void 0;
  27148. this.latencyController = void 0;
  27149. this.levelController = void 0;
  27150. this.streamController = void 0;
  27151. this.audioTrackController = void 0;
  27152. this.subtitleTrackController = void 0;
  27153. this.emeController = void 0;
  27154. this.cmcdController = void 0;
  27155. this._media = null;
  27156. this.url = null;
  27157. this.triggeringException = void 0;
  27158. enableLogs(userConfig.debug || false, 'Hls instance');
  27159. const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig);
  27160. this.userConfig = userConfig;
  27161. if (config.progressive) {
  27162. enableStreamingMode(config);
  27163. }
  27164. // core controllers and network loaders
  27165. const {
  27166. abrController: ConfigAbrController,
  27167. bufferController: ConfigBufferController,
  27168. capLevelController: ConfigCapLevelController,
  27169. errorController: ConfigErrorController,
  27170. fpsController: ConfigFpsController
  27171. } = config;
  27172. const errorController = new ConfigErrorController(this);
  27173. const abrController = this.abrController = new ConfigAbrController(this);
  27174. const bufferController = this.bufferController = new ConfigBufferController(this);
  27175. const capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  27176. const fpsController = new ConfigFpsController(this);
  27177. const playListLoader = new PlaylistLoader(this);
  27178. const id3TrackController = new ID3TrackController(this);
  27179. const ConfigContentSteeringController = config.contentSteeringController;
  27180. // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first
  27181. const contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null;
  27182. const levelController = this.levelController = new LevelController(this, contentSteering);
  27183. // FragmentTracker must be defined before StreamController because the order of event handling is important
  27184. const fragmentTracker = new FragmentTracker(this);
  27185. const keyLoader = new KeyLoader(this.config);
  27186. const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  27187. // Cap level controller uses streamController to flush the buffer
  27188. capLevelController.setStreamController(streamController);
  27189. // fpsController uses streamController to switch when frames are being dropped
  27190. fpsController.setStreamController(streamController);
  27191. const networkControllers = [playListLoader, levelController, streamController];
  27192. if (contentSteering) {
  27193. networkControllers.splice(1, 0, contentSteering);
  27194. }
  27195. this.networkControllers = networkControllers;
  27196. const coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  27197. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  27198. const AudioStreamControllerClass = config.audioStreamController;
  27199. if (AudioStreamControllerClass) {
  27200. networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  27201. }
  27202. // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important
  27203. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  27204. const SubtitleStreamControllerClass = config.subtitleStreamController;
  27205. if (SubtitleStreamControllerClass) {
  27206. networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  27207. }
  27208. this.createController(config.timelineController, coreComponents);
  27209. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  27210. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  27211. this.latencyController = this.createController(LatencyController, coreComponents);
  27212. this.coreComponents = coreComponents;
  27213. // Error controller handles errors before and after all other controllers
  27214. // This listener will be invoked after all other controllers error listeners
  27215. networkControllers.push(errorController);
  27216. const onErrorOut = errorController.onErrorOut;
  27217. if (typeof onErrorOut === 'function') {
  27218. this.on(Events.ERROR, onErrorOut, errorController);
  27219. }
  27220. }
  27221. createController(ControllerClass, components) {
  27222. if (ControllerClass) {
  27223. const controllerInstance = new ControllerClass(this);
  27224. if (components) {
  27225. components.push(controllerInstance);
  27226. }
  27227. return controllerInstance;
  27228. }
  27229. return null;
  27230. }
  27231. // Delegate the EventEmitter through the public API of Hls.js
  27232. on(event, listener, context = this) {
  27233. this._emitter.on(event, listener, context);
  27234. }
  27235. once(event, listener, context = this) {
  27236. this._emitter.once(event, listener, context);
  27237. }
  27238. removeAllListeners(event) {
  27239. this._emitter.removeAllListeners(event);
  27240. }
  27241. off(event, listener, context = this, once) {
  27242. this._emitter.off(event, listener, context, once);
  27243. }
  27244. listeners(event) {
  27245. return this._emitter.listeners(event);
  27246. }
  27247. emit(event, name, eventObject) {
  27248. return this._emitter.emit(event, name, eventObject);
  27249. }
  27250. trigger(event, eventObject) {
  27251. if (this.config.debug) {
  27252. return this.emit(event, event, eventObject);
  27253. } else {
  27254. try {
  27255. return this.emit(event, event, eventObject);
  27256. } catch (error) {
  27257. logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  27258. // Prevent recursion in error event handlers that throw #5497
  27259. if (!this.triggeringException) {
  27260. this.triggeringException = true;
  27261. const fatal = event === Events.ERROR;
  27262. this.trigger(Events.ERROR, {
  27263. type: ErrorTypes.OTHER_ERROR,
  27264. details: ErrorDetails.INTERNAL_EXCEPTION,
  27265. fatal,
  27266. event,
  27267. error
  27268. });
  27269. this.triggeringException = false;
  27270. }
  27271. }
  27272. }
  27273. return false;
  27274. }
  27275. listenerCount(event) {
  27276. return this._emitter.listenerCount(event);
  27277. }
  27278. /**
  27279. * Dispose of the instance
  27280. */
  27281. destroy() {
  27282. logger.log('destroy');
  27283. this.trigger(Events.DESTROYING, undefined);
  27284. this.detachMedia();
  27285. this.removeAllListeners();
  27286. this._autoLevelCapping = -1;
  27287. this.url = null;
  27288. this.networkControllers.forEach(component => component.destroy());
  27289. this.networkControllers.length = 0;
  27290. this.coreComponents.forEach(component => component.destroy());
  27291. this.coreComponents.length = 0;
  27292. // Remove any references that could be held in config options or callbacks
  27293. const config = this.config;
  27294. config.xhrSetup = config.fetchSetup = undefined;
  27295. // @ts-ignore
  27296. this.userConfig = null;
  27297. }
  27298. /**
  27299. * Attaches Hls.js to a media element
  27300. */
  27301. attachMedia(media) {
  27302. logger.log('attachMedia');
  27303. this._media = media;
  27304. this.trigger(Events.MEDIA_ATTACHING, {
  27305. media: media
  27306. });
  27307. }
  27308. /**
  27309. * Detach Hls.js from the media
  27310. */
  27311. detachMedia() {
  27312. logger.log('detachMedia');
  27313. this.trigger(Events.MEDIA_DETACHING, undefined);
  27314. this._media = null;
  27315. }
  27316. /**
  27317. * Set the source URL. Can be relative or absolute.
  27318. */
  27319. loadSource(url) {
  27320. this.stopLoad();
  27321. const media = this.media;
  27322. const loadedSource = this.url;
  27323. const loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  27324. alwaysNormalize: true
  27325. });
  27326. this._autoLevelCapping = -1;
  27327. this._maxHdcpLevel = null;
  27328. logger.log(`loadSource:${loadingSource}`);
  27329. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  27330. this.detachMedia();
  27331. this.attachMedia(media);
  27332. }
  27333. // when attaching to a source URL, trigger a playlist load
  27334. this.trigger(Events.MANIFEST_LOADING, {
  27335. url: url
  27336. });
  27337. }
  27338. /**
  27339. * Start loading data from the stream source.
  27340. * Depending on default config, client starts loading automatically when a source is set.
  27341. *
  27342. * @param startPosition - Set the start position to stream from.
  27343. * Defaults to -1 (None: starts from earliest point)
  27344. */
  27345. startLoad(startPosition = -1) {
  27346. logger.log(`startLoad(${startPosition})`);
  27347. this.started = true;
  27348. this.networkControllers.forEach(controller => {
  27349. controller.startLoad(startPosition);
  27350. });
  27351. }
  27352. /**
  27353. * Stop loading of any stream data.
  27354. */
  27355. stopLoad() {
  27356. logger.log('stopLoad');
  27357. this.started = false;
  27358. this.networkControllers.forEach(controller => {
  27359. controller.stopLoad();
  27360. });
  27361. }
  27362. /**
  27363. * Resumes stream controller segment loading if previously started.
  27364. */
  27365. resumeBuffering() {
  27366. if (this.started) {
  27367. this.networkControllers.forEach(controller => {
  27368. if ('fragmentLoader' in controller) {
  27369. controller.startLoad(-1);
  27370. }
  27371. });
  27372. }
  27373. }
  27374. /**
  27375. * Stops stream controller segment loading without changing 'started' state like stopLoad().
  27376. * This allows for media buffering to be paused without interupting playlist loading.
  27377. */
  27378. pauseBuffering() {
  27379. this.networkControllers.forEach(controller => {
  27380. if ('fragmentLoader' in controller) {
  27381. controller.stopLoad();
  27382. }
  27383. });
  27384. }
  27385. /**
  27386. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  27387. */
  27388. swapAudioCodec() {
  27389. logger.log('swapAudioCodec');
  27390. this.streamController.swapAudioCodec();
  27391. }
  27392. /**
  27393. * When the media-element fails, this allows to detach and then re-attach it
  27394. * as one call (convenience method).
  27395. *
  27396. * Automatic recovery of media-errors by this process is configurable.
  27397. */
  27398. recoverMediaError() {
  27399. logger.log('recoverMediaError');
  27400. const media = this._media;
  27401. this.detachMedia();
  27402. if (media) {
  27403. this.attachMedia(media);
  27404. }
  27405. }
  27406. removeLevel(levelIndex) {
  27407. this.levelController.removeLevel(levelIndex);
  27408. }
  27409. /**
  27410. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  27411. */
  27412. get levels() {
  27413. const levels = this.levelController.levels;
  27414. return levels ? levels : [];
  27415. }
  27416. /**
  27417. * Index of quality level (variant) currently played
  27418. */
  27419. get currentLevel() {
  27420. return this.streamController.currentLevel;
  27421. }
  27422. /**
  27423. * 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.
  27424. */
  27425. set currentLevel(newLevel) {
  27426. logger.log(`set currentLevel:${newLevel}`);
  27427. this.levelController.manualLevel = newLevel;
  27428. this.streamController.immediateLevelSwitch();
  27429. }
  27430. /**
  27431. * Index of next quality level loaded as scheduled by stream controller.
  27432. */
  27433. get nextLevel() {
  27434. return this.streamController.nextLevel;
  27435. }
  27436. /**
  27437. * Set quality level index for next loaded data.
  27438. * This will switch the video quality asap, without interrupting playback.
  27439. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  27440. * @param newLevel - Pass -1 for automatic level selection
  27441. */
  27442. set nextLevel(newLevel) {
  27443. logger.log(`set nextLevel:${newLevel}`);
  27444. this.levelController.manualLevel = newLevel;
  27445. this.streamController.nextLevelSwitch();
  27446. }
  27447. /**
  27448. * Return the quality level of the currently or last (of none is loaded currently) segment
  27449. */
  27450. get loadLevel() {
  27451. return this.levelController.level;
  27452. }
  27453. /**
  27454. * Set quality level index for next loaded data in a conservative way.
  27455. * This will switch the quality without flushing, but interrupt current loading.
  27456. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  27457. * @param newLevel - Pass -1 for automatic level selection
  27458. */
  27459. set loadLevel(newLevel) {
  27460. logger.log(`set loadLevel:${newLevel}`);
  27461. this.levelController.manualLevel = newLevel;
  27462. }
  27463. /**
  27464. * get next quality level loaded
  27465. */
  27466. get nextLoadLevel() {
  27467. return this.levelController.nextLoadLevel;
  27468. }
  27469. /**
  27470. * Set quality level of next loaded segment in a fully "non-destructive" way.
  27471. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  27472. */
  27473. set nextLoadLevel(level) {
  27474. this.levelController.nextLoadLevel = level;
  27475. }
  27476. /**
  27477. * Return "first level": like a default level, if not set,
  27478. * falls back to index of first level referenced in manifest
  27479. */
  27480. get firstLevel() {
  27481. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  27482. }
  27483. /**
  27484. * Sets "first-level", see getter.
  27485. */
  27486. set firstLevel(newLevel) {
  27487. logger.log(`set firstLevel:${newLevel}`);
  27488. this.levelController.firstLevel = newLevel;
  27489. }
  27490. /**
  27491. * Return the desired start level for the first fragment that will be loaded.
  27492. * The default value of -1 indicates automatic start level selection.
  27493. * Setting hls.nextAutoLevel without setting a startLevel will result in
  27494. * the nextAutoLevel value being used for one fragment load.
  27495. */
  27496. get startLevel() {
  27497. const startLevel = this.levelController.startLevel;
  27498. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  27499. return this.abrController.forcedAutoLevel;
  27500. }
  27501. return startLevel;
  27502. }
  27503. /**
  27504. * set start level (level of first fragment that will be played back)
  27505. * if not overrided by user, first level appearing in manifest will be used as start level
  27506. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  27507. * (determined from download of first segment)
  27508. */
  27509. set startLevel(newLevel) {
  27510. logger.log(`set startLevel:${newLevel}`);
  27511. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  27512. if (newLevel !== -1) {
  27513. newLevel = Math.max(newLevel, this.minAutoLevel);
  27514. }
  27515. this.levelController.startLevel = newLevel;
  27516. }
  27517. /**
  27518. * Whether level capping is enabled.
  27519. * Default value is set via `config.capLevelToPlayerSize`.
  27520. */
  27521. get capLevelToPlayerSize() {
  27522. return this.config.capLevelToPlayerSize;
  27523. }
  27524. /**
  27525. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  27526. */
  27527. set capLevelToPlayerSize(shouldStartCapping) {
  27528. const newCapLevelToPlayerSize = !!shouldStartCapping;
  27529. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  27530. if (newCapLevelToPlayerSize) {
  27531. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  27532. } else {
  27533. this.capLevelController.stopCapping();
  27534. this.autoLevelCapping = -1;
  27535. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  27536. }
  27537. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  27538. }
  27539. }
  27540. /**
  27541. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  27542. */
  27543. get autoLevelCapping() {
  27544. return this._autoLevelCapping;
  27545. }
  27546. /**
  27547. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  27548. */
  27549. get bandwidthEstimate() {
  27550. const {
  27551. bwEstimator
  27552. } = this.abrController;
  27553. if (!bwEstimator) {
  27554. return NaN;
  27555. }
  27556. return bwEstimator.getEstimate();
  27557. }
  27558. set bandwidthEstimate(abrEwmaDefaultEstimate) {
  27559. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  27560. }
  27561. /**
  27562. * get time to first byte estimate
  27563. * @type {number}
  27564. */
  27565. get ttfbEstimate() {
  27566. const {
  27567. bwEstimator
  27568. } = this.abrController;
  27569. if (!bwEstimator) {
  27570. return NaN;
  27571. }
  27572. return bwEstimator.getEstimateTTFB();
  27573. }
  27574. /**
  27575. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  27576. */
  27577. set autoLevelCapping(newLevel) {
  27578. if (this._autoLevelCapping !== newLevel) {
  27579. logger.log(`set autoLevelCapping:${newLevel}`);
  27580. this._autoLevelCapping = newLevel;
  27581. this.levelController.checkMaxAutoUpdated();
  27582. }
  27583. }
  27584. get maxHdcpLevel() {
  27585. return this._maxHdcpLevel;
  27586. }
  27587. set maxHdcpLevel(value) {
  27588. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  27589. this._maxHdcpLevel = value;
  27590. this.levelController.checkMaxAutoUpdated();
  27591. }
  27592. }
  27593. /**
  27594. * True when automatic level selection enabled
  27595. */
  27596. get autoLevelEnabled() {
  27597. return this.levelController.manualLevel === -1;
  27598. }
  27599. /**
  27600. * Level set manually (if any)
  27601. */
  27602. get manualLevel() {
  27603. return this.levelController.manualLevel;
  27604. }
  27605. /**
  27606. * min level selectable in auto mode according to config.minAutoBitrate
  27607. */
  27608. get minAutoLevel() {
  27609. const {
  27610. levels,
  27611. config: {
  27612. minAutoBitrate
  27613. }
  27614. } = this;
  27615. if (!levels) return 0;
  27616. const len = levels.length;
  27617. for (let i = 0; i < len; i++) {
  27618. if (levels[i].maxBitrate >= minAutoBitrate) {
  27619. return i;
  27620. }
  27621. }
  27622. return 0;
  27623. }
  27624. /**
  27625. * max level selectable in auto mode according to autoLevelCapping
  27626. */
  27627. get maxAutoLevel() {
  27628. const {
  27629. levels,
  27630. autoLevelCapping,
  27631. maxHdcpLevel
  27632. } = this;
  27633. let maxAutoLevel;
  27634. if (autoLevelCapping === -1 && levels != null && levels.length) {
  27635. maxAutoLevel = levels.length - 1;
  27636. } else {
  27637. maxAutoLevel = autoLevelCapping;
  27638. }
  27639. if (maxHdcpLevel) {
  27640. for (let i = maxAutoLevel; i--;) {
  27641. const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  27642. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  27643. return i;
  27644. }
  27645. }
  27646. }
  27647. return maxAutoLevel;
  27648. }
  27649. get firstAutoLevel() {
  27650. return this.abrController.firstAutoLevel;
  27651. }
  27652. /**
  27653. * next automatically selected quality level
  27654. */
  27655. get nextAutoLevel() {
  27656. return this.abrController.nextAutoLevel;
  27657. }
  27658. /**
  27659. * this setter is used to force next auto level.
  27660. * this is useful to force a switch down in auto mode:
  27661. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  27662. * forced value is valid for one fragment. upon successful frag loading at forced level,
  27663. * this value will be resetted to -1 by ABR controller.
  27664. */
  27665. set nextAutoLevel(nextLevel) {
  27666. this.abrController.nextAutoLevel = nextLevel;
  27667. }
  27668. /**
  27669. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  27670. */
  27671. get playingDate() {
  27672. return this.streamController.currentProgramDateTime;
  27673. }
  27674. get mainForwardBufferInfo() {
  27675. return this.streamController.getMainFwdBufferInfo();
  27676. }
  27677. /**
  27678. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  27679. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  27680. */
  27681. setAudioOption(audioOption) {
  27682. var _this$audioTrackContr;
  27683. return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption);
  27684. }
  27685. /**
  27686. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  27687. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  27688. */
  27689. setSubtitleOption(subtitleOption) {
  27690. var _this$subtitleTrackCo;
  27691. (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption);
  27692. return null;
  27693. }
  27694. /**
  27695. * Get the complete list of audio tracks across all media groups
  27696. */
  27697. get allAudioTracks() {
  27698. const audioTrackController = this.audioTrackController;
  27699. return audioTrackController ? audioTrackController.allAudioTracks : [];
  27700. }
  27701. /**
  27702. * Get the list of selectable audio tracks
  27703. */
  27704. get audioTracks() {
  27705. const audioTrackController = this.audioTrackController;
  27706. return audioTrackController ? audioTrackController.audioTracks : [];
  27707. }
  27708. /**
  27709. * index of the selected audio track (index in audio track lists)
  27710. */
  27711. get audioTrack() {
  27712. const audioTrackController = this.audioTrackController;
  27713. return audioTrackController ? audioTrackController.audioTrack : -1;
  27714. }
  27715. /**
  27716. * selects an audio track, based on its index in audio track lists
  27717. */
  27718. set audioTrack(audioTrackId) {
  27719. const audioTrackController = this.audioTrackController;
  27720. if (audioTrackController) {
  27721. audioTrackController.audioTrack = audioTrackId;
  27722. }
  27723. }
  27724. /**
  27725. * get the complete list of subtitle tracks across all media groups
  27726. */
  27727. get allSubtitleTracks() {
  27728. const subtitleTrackController = this.subtitleTrackController;
  27729. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  27730. }
  27731. /**
  27732. * get alternate subtitle tracks list from playlist
  27733. */
  27734. get subtitleTracks() {
  27735. const subtitleTrackController = this.subtitleTrackController;
  27736. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  27737. }
  27738. /**
  27739. * index of the selected subtitle track (index in subtitle track lists)
  27740. */
  27741. get subtitleTrack() {
  27742. const subtitleTrackController = this.subtitleTrackController;
  27743. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  27744. }
  27745. get media() {
  27746. return this._media;
  27747. }
  27748. /**
  27749. * select an subtitle track, based on its index in subtitle track lists
  27750. */
  27751. set subtitleTrack(subtitleTrackId) {
  27752. const subtitleTrackController = this.subtitleTrackController;
  27753. if (subtitleTrackController) {
  27754. subtitleTrackController.subtitleTrack = subtitleTrackId;
  27755. }
  27756. }
  27757. /**
  27758. * Whether subtitle display is enabled or not
  27759. */
  27760. get subtitleDisplay() {
  27761. const subtitleTrackController = this.subtitleTrackController;
  27762. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  27763. }
  27764. /**
  27765. * Enable/disable subtitle display rendering
  27766. */
  27767. set subtitleDisplay(value) {
  27768. const subtitleTrackController = this.subtitleTrackController;
  27769. if (subtitleTrackController) {
  27770. subtitleTrackController.subtitleDisplay = value;
  27771. }
  27772. }
  27773. /**
  27774. * get mode for Low-Latency HLS loading
  27775. */
  27776. get lowLatencyMode() {
  27777. return this.config.lowLatencyMode;
  27778. }
  27779. /**
  27780. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  27781. */
  27782. set lowLatencyMode(mode) {
  27783. this.config.lowLatencyMode = mode;
  27784. }
  27785. /**
  27786. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  27787. * @returns null prior to loading live Playlist
  27788. */
  27789. get liveSyncPosition() {
  27790. return this.latencyController.liveSyncPosition;
  27791. }
  27792. /**
  27793. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  27794. * @returns 0 before first playlist is loaded
  27795. */
  27796. get latency() {
  27797. return this.latencyController.latency;
  27798. }
  27799. /**
  27800. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  27801. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  27802. * @returns 0 before first playlist is loaded
  27803. */
  27804. get maxLatency() {
  27805. return this.latencyController.maxLatency;
  27806. }
  27807. /**
  27808. * target distance from the edge as calculated by the latency controller
  27809. */
  27810. get targetLatency() {
  27811. return this.latencyController.targetLatency;
  27812. }
  27813. /**
  27814. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  27815. */
  27816. get drift() {
  27817. return this.latencyController.drift;
  27818. }
  27819. /**
  27820. * set to true when startLoad is called before MANIFEST_PARSED event
  27821. */
  27822. get forceStartLoad() {
  27823. return this.streamController.forceStartLoad;
  27824. }
  27825. }
  27826. Hls.defaultConfig = void 0;
  27827. 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 };
  27828. //# sourceMappingURL=hls.mjs.map