videojs-http-streaming.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110
  1. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('video.js'), require('@xmldom/xmldom')) :
  4. typeof define === 'function' && define.amd ? define(['exports', 'video.js', '@xmldom/xmldom'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.httpStreaming = {}, global.videojs, global.window));
  6. })(this, (function (exports, videojs, xmldom) { 'use strict';
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
  9. var urlToolkit = {exports: {}};
  10. (function (module, exports) {
  11. // see https://tools.ietf.org/html/rfc1808
  12. (function (root) {
  13. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
  14. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
  15. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  16. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  17. var URLToolkit = {
  18. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  19. // E.g
  20. // With opts.alwaysNormalize = false (default, spec compliant)
  21. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  22. // With opts.alwaysNormalize = true (not spec compliant)
  23. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  24. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  25. opts = opts || {}; // remove any remaining space and CRLF
  26. baseURL = baseURL.trim();
  27. relativeURL = relativeURL.trim();
  28. if (!relativeURL) {
  29. // 2a) If the embedded URL is entirely empty, it inherits the
  30. // entire base URL (i.e., is set equal to the base URL)
  31. // and we are done.
  32. if (!opts.alwaysNormalize) {
  33. return baseURL;
  34. }
  35. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  36. if (!basePartsForNormalise) {
  37. throw new Error('Error trying to parse base URL.');
  38. }
  39. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  40. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  41. }
  42. var relativeParts = URLToolkit.parseURL(relativeURL);
  43. if (!relativeParts) {
  44. throw new Error('Error trying to parse relative URL.');
  45. }
  46. if (relativeParts.scheme) {
  47. // 2b) If the embedded URL starts with a scheme name, it is
  48. // interpreted as an absolute URL and we are done.
  49. if (!opts.alwaysNormalize) {
  50. return relativeURL;
  51. }
  52. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  53. return URLToolkit.buildURLFromParts(relativeParts);
  54. }
  55. var baseParts = URLToolkit.parseURL(baseURL);
  56. if (!baseParts) {
  57. throw new Error('Error trying to parse base URL.');
  58. }
  59. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  60. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  61. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  62. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  63. baseParts.netLoc = pathParts[1];
  64. baseParts.path = pathParts[2];
  65. }
  66. if (baseParts.netLoc && !baseParts.path) {
  67. baseParts.path = '/';
  68. }
  69. var builtParts = {
  70. // 2c) Otherwise, the embedded URL inherits the scheme of
  71. // the base URL.
  72. scheme: baseParts.scheme,
  73. netLoc: relativeParts.netLoc,
  74. path: null,
  75. params: relativeParts.params,
  76. query: relativeParts.query,
  77. fragment: relativeParts.fragment
  78. };
  79. if (!relativeParts.netLoc) {
  80. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  81. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  82. // (if any) of the base URL.
  83. builtParts.netLoc = baseParts.netLoc; // 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; // 5a) if the embedded URL's <params> is non-empty, we skip to
  90. // step 7; otherwise, it inherits the <params> of the base
  91. // URL (if any) and
  92. if (!relativeParts.params) {
  93. builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to
  94. // step 7; otherwise, it inherits the <query> of the base
  95. // URL (if any) and we skip to step 7.
  96. if (!relativeParts.query) {
  97. builtParts.query = baseParts.query;
  98. }
  99. }
  100. } else {
  101. // 6) The last segment of the base URL's path (anything
  102. // following the rightmost slash "/", or the entire path if no
  103. // slash is present) is removed and the embedded URL's path is
  104. // appended in its place.
  105. var baseURLPath = baseParts.path;
  106. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  107. builtParts.path = URLToolkit.normalizePath(newPath);
  108. }
  109. }
  110. }
  111. if (builtParts.path === null) {
  112. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  113. }
  114. return URLToolkit.buildURLFromParts(builtParts);
  115. },
  116. parseURL: function (url) {
  117. var parts = URL_REGEX.exec(url);
  118. if (!parts) {
  119. return null;
  120. }
  121. return {
  122. scheme: parts[1] || '',
  123. netLoc: parts[2] || '',
  124. path: parts[3] || '',
  125. params: parts[4] || '',
  126. query: parts[5] || '',
  127. fragment: parts[6] || ''
  128. };
  129. },
  130. normalizePath: function (path) {
  131. // The following operations are
  132. // then applied, in order, to the new path:
  133. // 6a) All occurrences of "./", where "." is a complete path
  134. // segment, are removed.
  135. // 6b) If the path ends with "." as a complete path segment,
  136. // that "." is removed.
  137. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a
  138. // complete path segment not equal to "..", are removed.
  139. // Removal of these path segments is performed iteratively,
  140. // removing the leftmost matching pattern on each iteration,
  141. // until no matching pattern remains.
  142. // 6d) If the path ends with "<segment>/..", where <segment> is a
  143. // complete path segment not equal to "..", that
  144. // "<segment>/.." is removed.
  145. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  146. return path.split('').reverse().join('');
  147. },
  148. buildURLFromParts: function (parts) {
  149. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  150. }
  151. };
  152. module.exports = URLToolkit;
  153. })();
  154. })(urlToolkit);
  155. var URLToolkit = urlToolkit.exports;
  156. var DEFAULT_LOCATION = 'http://example.com';
  157. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  158. // return early if we don't need to resolve
  159. if (/^[a-z]+:/i.test(relativeUrl)) {
  160. return relativeUrl;
  161. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  162. if (/^data:/.test(baseUrl)) {
  163. baseUrl = window.location && window.location.href || '';
  164. } // IE11 supports URL but not the URL constructor
  165. // feature detect the behavior we want
  166. var nativeURL = typeof window.URL === 'function';
  167. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  168. // and if baseUrl isn't an absolute url
  169. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  170. if (nativeURL) {
  171. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  172. } else if (!/\/\//i.test(baseUrl)) {
  173. baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  174. }
  175. if (nativeURL) {
  176. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  177. // and if we're location-less, remove the location
  178. // otherwise, return the url unmodified
  179. if (removeLocation) {
  180. return newUrl.href.slice(DEFAULT_LOCATION.length);
  181. } else if (protocolLess) {
  182. return newUrl.href.slice(newUrl.protocol.length);
  183. }
  184. return newUrl.href;
  185. }
  186. return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  187. };
  188. /**
  189. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  190. */
  191. const resolveUrl = resolveUrl$1;
  192. /**
  193. * If the xhr request was redirected, return the responseURL, otherwise,
  194. * return the original url.
  195. *
  196. * @api private
  197. *
  198. * @param {string} url - an url being requested
  199. * @param {XMLHttpRequest} req - xhr request result
  200. *
  201. * @return {string}
  202. */
  203. const resolveManifestRedirect = (url, req) => {
  204. // To understand how the responseURL below is set and generated:
  205. // - https://fetch.spec.whatwg.org/#concept-response-url
  206. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  207. if (req && req.responseURL && url !== req.responseURL) {
  208. return req.responseURL;
  209. }
  210. return url;
  211. };
  212. const logger = source => {
  213. if (videojs__default["default"].log.debug) {
  214. return videojs__default["default"].log.debug.bind(videojs__default["default"], 'VHS:', `${source} >`);
  215. }
  216. return function () {};
  217. };
  218. function _extends() {
  219. _extends = Object.assign || function (target) {
  220. for (var i = 1; i < arguments.length; i++) {
  221. var source = arguments[i];
  222. for (var key in source) {
  223. if (Object.prototype.hasOwnProperty.call(source, key)) {
  224. target[key] = source[key];
  225. }
  226. }
  227. }
  228. return target;
  229. };
  230. return _extends.apply(this, arguments);
  231. }
  232. /**
  233. * @file stream.js
  234. */
  235. /**
  236. * A lightweight readable stream implemention that handles event dispatching.
  237. *
  238. * @class Stream
  239. */
  240. var Stream = /*#__PURE__*/function () {
  241. function Stream() {
  242. this.listeners = {};
  243. }
  244. /**
  245. * Add a listener for a specified event type.
  246. *
  247. * @param {string} type the event name
  248. * @param {Function} listener the callback to be invoked when an event of
  249. * the specified type occurs
  250. */
  251. var _proto = Stream.prototype;
  252. _proto.on = function on(type, listener) {
  253. if (!this.listeners[type]) {
  254. this.listeners[type] = [];
  255. }
  256. this.listeners[type].push(listener);
  257. }
  258. /**
  259. * Remove a listener for a specified event type.
  260. *
  261. * @param {string} type the event name
  262. * @param {Function} listener a function previously registered for this
  263. * type of event through `on`
  264. * @return {boolean} if we could turn it off or not
  265. */
  266. ;
  267. _proto.off = function off(type, listener) {
  268. if (!this.listeners[type]) {
  269. return false;
  270. }
  271. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  272. // In Video.js we slice listener functions
  273. // on trigger so that it does not mess up the order
  274. // while we loop through.
  275. //
  276. // Here we slice on off so that the loop in trigger
  277. // can continue using it's old reference to loop without
  278. // messing up the order.
  279. this.listeners[type] = this.listeners[type].slice(0);
  280. this.listeners[type].splice(index, 1);
  281. return index > -1;
  282. }
  283. /**
  284. * Trigger an event of the specified type on this stream. Any additional
  285. * arguments to this function are passed as parameters to event listeners.
  286. *
  287. * @param {string} type the event name
  288. */
  289. ;
  290. _proto.trigger = function trigger(type) {
  291. var callbacks = this.listeners[type];
  292. if (!callbacks) {
  293. return;
  294. } // Slicing the arguments on every invocation of this method
  295. // can add a significant amount of overhead. Avoid the
  296. // intermediate object creation for the common case of a
  297. // single callback argument
  298. if (arguments.length === 2) {
  299. var length = callbacks.length;
  300. for (var i = 0; i < length; ++i) {
  301. callbacks[i].call(this, arguments[1]);
  302. }
  303. } else {
  304. var args = Array.prototype.slice.call(arguments, 1);
  305. var _length = callbacks.length;
  306. for (var _i = 0; _i < _length; ++_i) {
  307. callbacks[_i].apply(this, args);
  308. }
  309. }
  310. }
  311. /**
  312. * Destroys the stream and cleans up.
  313. */
  314. ;
  315. _proto.dispose = function dispose() {
  316. this.listeners = {};
  317. }
  318. /**
  319. * Forwards all `data` events on this stream to the destination stream. The
  320. * destination stream should provide a method `push` to receive the data
  321. * events as they arrive.
  322. *
  323. * @param {Stream} destination the stream that will receive all `data` events
  324. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  325. */
  326. ;
  327. _proto.pipe = function pipe(destination) {
  328. this.on('data', function (data) {
  329. destination.push(data);
  330. });
  331. };
  332. return Stream;
  333. }();
  334. var atob = function atob(s) {
  335. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  336. };
  337. function decodeB64ToUint8Array(b64Text) {
  338. var decodedString = atob(b64Text);
  339. var array = new Uint8Array(decodedString.length);
  340. for (var i = 0; i < decodedString.length; i++) {
  341. array[i] = decodedString.charCodeAt(i);
  342. }
  343. return array;
  344. }
  345. /*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */
  346. /**
  347. * @file m3u8/line-stream.js
  348. */
  349. /**
  350. * A stream that buffers string input and generates a `data` event for each
  351. * line.
  352. *
  353. * @class LineStream
  354. * @extends Stream
  355. */
  356. class LineStream extends Stream {
  357. constructor() {
  358. super();
  359. this.buffer = '';
  360. }
  361. /**
  362. * Add new data to be parsed.
  363. *
  364. * @param {string} data the text to process
  365. */
  366. push(data) {
  367. let nextNewline;
  368. this.buffer += data;
  369. nextNewline = this.buffer.indexOf('\n');
  370. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  371. this.trigger('data', this.buffer.substring(0, nextNewline));
  372. this.buffer = this.buffer.substring(nextNewline + 1);
  373. }
  374. }
  375. }
  376. const TAB = String.fromCharCode(0x09);
  377. const parseByterange = function (byterangeString) {
  378. // optionally match and capture 0+ digits before `@`
  379. // optionally match and capture 0+ digits after `@`
  380. const match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  381. const result = {};
  382. if (match[1]) {
  383. result.length = parseInt(match[1], 10);
  384. }
  385. if (match[2]) {
  386. result.offset = parseInt(match[2], 10);
  387. }
  388. return result;
  389. };
  390. /**
  391. * "forgiving" attribute list psuedo-grammar:
  392. * attributes -> keyvalue (',' keyvalue)*
  393. * keyvalue -> key '=' value
  394. * key -> [^=]*
  395. * value -> '"' [^"]* '"' | [^,]*
  396. */
  397. const attributeSeparator = function () {
  398. const key = '[^=]*';
  399. const value = '"[^"]*"|[^,]*';
  400. const keyvalue = '(?:' + key + ')=(?:' + value + ')';
  401. return new RegExp('(?:^|,)(' + keyvalue + ')');
  402. };
  403. /**
  404. * Parse attributes from a line given the separator
  405. *
  406. * @param {string} attributes the attribute line to parse
  407. */
  408. const parseAttributes$1 = function (attributes) {
  409. const result = {};
  410. if (!attributes) {
  411. return result;
  412. } // split the string using attributes as the separator
  413. const attrs = attributes.split(attributeSeparator());
  414. let i = attrs.length;
  415. let attr;
  416. while (i--) {
  417. // filter out unmatched portions of the string
  418. if (attrs[i] === '') {
  419. continue;
  420. } // split the key and value
  421. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  422. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  423. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  424. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  425. result[attr[0]] = attr[1];
  426. }
  427. return result;
  428. };
  429. /**
  430. * A line-level M3U8 parser event stream. It expects to receive input one
  431. * line at a time and performs a context-free parse of its contents. A stream
  432. * interpretation of a manifest can be useful if the manifest is expected to
  433. * be too large to fit comfortably into memory or the entirety of the input
  434. * is not immediately available. Otherwise, it's probably much easier to work
  435. * with a regular `Parser` object.
  436. *
  437. * Produces `data` events with an object that captures the parser's
  438. * interpretation of the input. That object has a property `tag` that is one
  439. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  440. * property, `line`, which captures the entirety of the input without
  441. * interpretation. Comments similarly have a single additional property
  442. * `text` which is the input without the leading `#`.
  443. *
  444. * Tags always have a property `tagType` which is the lower-cased version of
  445. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  446. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  447. * tags are given the tag type `unknown` and a single additional property
  448. * `data` with the remainder of the input.
  449. *
  450. * @class ParseStream
  451. * @extends Stream
  452. */
  453. class ParseStream extends Stream {
  454. constructor() {
  455. super();
  456. this.customParsers = [];
  457. this.tagMappers = [];
  458. }
  459. /**
  460. * Parses an additional line of input.
  461. *
  462. * @param {string} line a single line of an M3U8 file to parse
  463. */
  464. push(line) {
  465. let match;
  466. let event; // strip whitespace
  467. line = line.trim();
  468. if (line.length === 0) {
  469. // ignore empty lines
  470. return;
  471. } // URIs
  472. if (line[0] !== '#') {
  473. this.trigger('data', {
  474. type: 'uri',
  475. uri: line
  476. });
  477. return;
  478. } // map tags
  479. const newLines = this.tagMappers.reduce((acc, mapper) => {
  480. const mappedLine = mapper(line); // skip if unchanged
  481. if (mappedLine === line) {
  482. return acc;
  483. }
  484. return acc.concat([mappedLine]);
  485. }, [line]);
  486. newLines.forEach(newLine => {
  487. for (let i = 0; i < this.customParsers.length; i++) {
  488. if (this.customParsers[i].call(this, newLine)) {
  489. return;
  490. }
  491. } // Comments
  492. if (newLine.indexOf('#EXT') !== 0) {
  493. this.trigger('data', {
  494. type: 'comment',
  495. text: newLine.slice(1)
  496. });
  497. return;
  498. } // strip off any carriage returns here so the regex matching
  499. // doesn't have to account for them.
  500. newLine = newLine.replace('\r', ''); // Tags
  501. match = /^#EXTM3U/.exec(newLine);
  502. if (match) {
  503. this.trigger('data', {
  504. type: 'tag',
  505. tagType: 'm3u'
  506. });
  507. return;
  508. }
  509. match = /^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine);
  510. if (match) {
  511. event = {
  512. type: 'tag',
  513. tagType: 'inf'
  514. };
  515. if (match[1]) {
  516. event.duration = parseFloat(match[1]);
  517. }
  518. if (match[2]) {
  519. event.title = match[2];
  520. }
  521. this.trigger('data', event);
  522. return;
  523. }
  524. match = /^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine);
  525. if (match) {
  526. event = {
  527. type: 'tag',
  528. tagType: 'targetduration'
  529. };
  530. if (match[1]) {
  531. event.duration = parseInt(match[1], 10);
  532. }
  533. this.trigger('data', event);
  534. return;
  535. }
  536. match = /^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine);
  537. if (match) {
  538. event = {
  539. type: 'tag',
  540. tagType: 'version'
  541. };
  542. if (match[1]) {
  543. event.version = parseInt(match[1], 10);
  544. }
  545. this.trigger('data', event);
  546. return;
  547. }
  548. match = /^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  549. if (match) {
  550. event = {
  551. type: 'tag',
  552. tagType: 'media-sequence'
  553. };
  554. if (match[1]) {
  555. event.number = parseInt(match[1], 10);
  556. }
  557. this.trigger('data', event);
  558. return;
  559. }
  560. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  561. if (match) {
  562. event = {
  563. type: 'tag',
  564. tagType: 'discontinuity-sequence'
  565. };
  566. if (match[1]) {
  567. event.number = parseInt(match[1], 10);
  568. }
  569. this.trigger('data', event);
  570. return;
  571. }
  572. match = /^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine);
  573. if (match) {
  574. event = {
  575. type: 'tag',
  576. tagType: 'playlist-type'
  577. };
  578. if (match[1]) {
  579. event.playlistType = match[1];
  580. }
  581. this.trigger('data', event);
  582. return;
  583. }
  584. match = /^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine);
  585. if (match) {
  586. event = _extends(parseByterange(match[1]), {
  587. type: 'tag',
  588. tagType: 'byterange'
  589. });
  590. this.trigger('data', event);
  591. return;
  592. }
  593. match = /^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine);
  594. if (match) {
  595. event = {
  596. type: 'tag',
  597. tagType: 'allow-cache'
  598. };
  599. if (match[1]) {
  600. event.allowed = !/NO/.test(match[1]);
  601. }
  602. this.trigger('data', event);
  603. return;
  604. }
  605. match = /^#EXT-X-MAP:(.*)$/.exec(newLine);
  606. if (match) {
  607. event = {
  608. type: 'tag',
  609. tagType: 'map'
  610. };
  611. if (match[1]) {
  612. const attributes = parseAttributes$1(match[1]);
  613. if (attributes.URI) {
  614. event.uri = attributes.URI;
  615. }
  616. if (attributes.BYTERANGE) {
  617. event.byterange = parseByterange(attributes.BYTERANGE);
  618. }
  619. }
  620. this.trigger('data', event);
  621. return;
  622. }
  623. match = /^#EXT-X-STREAM-INF:(.*)$/.exec(newLine);
  624. if (match) {
  625. event = {
  626. type: 'tag',
  627. tagType: 'stream-inf'
  628. };
  629. if (match[1]) {
  630. event.attributes = parseAttributes$1(match[1]);
  631. if (event.attributes.RESOLUTION) {
  632. const split = event.attributes.RESOLUTION.split('x');
  633. const resolution = {};
  634. if (split[0]) {
  635. resolution.width = parseInt(split[0], 10);
  636. }
  637. if (split[1]) {
  638. resolution.height = parseInt(split[1], 10);
  639. }
  640. event.attributes.RESOLUTION = resolution;
  641. }
  642. if (event.attributes.BANDWIDTH) {
  643. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  644. }
  645. if (event.attributes['FRAME-RATE']) {
  646. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  647. }
  648. if (event.attributes['PROGRAM-ID']) {
  649. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  650. }
  651. }
  652. this.trigger('data', event);
  653. return;
  654. }
  655. match = /^#EXT-X-MEDIA:(.*)$/.exec(newLine);
  656. if (match) {
  657. event = {
  658. type: 'tag',
  659. tagType: 'media'
  660. };
  661. if (match[1]) {
  662. event.attributes = parseAttributes$1(match[1]);
  663. }
  664. this.trigger('data', event);
  665. return;
  666. }
  667. match = /^#EXT-X-ENDLIST/.exec(newLine);
  668. if (match) {
  669. this.trigger('data', {
  670. type: 'tag',
  671. tagType: 'endlist'
  672. });
  673. return;
  674. }
  675. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  676. if (match) {
  677. this.trigger('data', {
  678. type: 'tag',
  679. tagType: 'discontinuity'
  680. });
  681. return;
  682. }
  683. match = /^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine);
  684. if (match) {
  685. event = {
  686. type: 'tag',
  687. tagType: 'program-date-time'
  688. };
  689. if (match[1]) {
  690. event.dateTimeString = match[1];
  691. event.dateTimeObject = new Date(match[1]);
  692. }
  693. this.trigger('data', event);
  694. return;
  695. }
  696. match = /^#EXT-X-KEY:(.*)$/.exec(newLine);
  697. if (match) {
  698. event = {
  699. type: 'tag',
  700. tagType: 'key'
  701. };
  702. if (match[1]) {
  703. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  704. if (event.attributes.IV) {
  705. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  706. event.attributes.IV = event.attributes.IV.substring(2);
  707. }
  708. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  709. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  710. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  711. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  712. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  713. event.attributes.IV = new Uint32Array(event.attributes.IV);
  714. }
  715. }
  716. this.trigger('data', event);
  717. return;
  718. }
  719. match = /^#EXT-X-START:(.*)$/.exec(newLine);
  720. if (match) {
  721. event = {
  722. type: 'tag',
  723. tagType: 'start'
  724. };
  725. if (match[1]) {
  726. event.attributes = parseAttributes$1(match[1]);
  727. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  728. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  729. }
  730. this.trigger('data', event);
  731. return;
  732. }
  733. match = /^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine);
  734. if (match) {
  735. event = {
  736. type: 'tag',
  737. tagType: 'cue-out-cont'
  738. };
  739. if (match[1]) {
  740. event.data = match[1];
  741. } else {
  742. event.data = '';
  743. }
  744. this.trigger('data', event);
  745. return;
  746. }
  747. match = /^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine);
  748. if (match) {
  749. event = {
  750. type: 'tag',
  751. tagType: 'cue-out'
  752. };
  753. if (match[1]) {
  754. event.data = match[1];
  755. } else {
  756. event.data = '';
  757. }
  758. this.trigger('data', event);
  759. return;
  760. }
  761. match = /^#EXT-X-CUE-IN:(.*)?$/.exec(newLine);
  762. if (match) {
  763. event = {
  764. type: 'tag',
  765. tagType: 'cue-in'
  766. };
  767. if (match[1]) {
  768. event.data = match[1];
  769. } else {
  770. event.data = '';
  771. }
  772. this.trigger('data', event);
  773. return;
  774. }
  775. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  776. if (match && match[1]) {
  777. event = {
  778. type: 'tag',
  779. tagType: 'skip'
  780. };
  781. event.attributes = parseAttributes$1(match[1]);
  782. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  783. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  784. }
  785. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  786. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  787. }
  788. this.trigger('data', event);
  789. return;
  790. }
  791. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  792. if (match && match[1]) {
  793. event = {
  794. type: 'tag',
  795. tagType: 'part'
  796. };
  797. event.attributes = parseAttributes$1(match[1]);
  798. ['DURATION'].forEach(function (key) {
  799. if (event.attributes.hasOwnProperty(key)) {
  800. event.attributes[key] = parseFloat(event.attributes[key]);
  801. }
  802. });
  803. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  804. if (event.attributes.hasOwnProperty(key)) {
  805. event.attributes[key] = /YES/.test(event.attributes[key]);
  806. }
  807. });
  808. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  809. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  810. }
  811. this.trigger('data', event);
  812. return;
  813. }
  814. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  815. if (match && match[1]) {
  816. event = {
  817. type: 'tag',
  818. tagType: 'server-control'
  819. };
  820. event.attributes = parseAttributes$1(match[1]);
  821. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  822. if (event.attributes.hasOwnProperty(key)) {
  823. event.attributes[key] = parseFloat(event.attributes[key]);
  824. }
  825. });
  826. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  827. if (event.attributes.hasOwnProperty(key)) {
  828. event.attributes[key] = /YES/.test(event.attributes[key]);
  829. }
  830. });
  831. this.trigger('data', event);
  832. return;
  833. }
  834. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  835. if (match && match[1]) {
  836. event = {
  837. type: 'tag',
  838. tagType: 'part-inf'
  839. };
  840. event.attributes = parseAttributes$1(match[1]);
  841. ['PART-TARGET'].forEach(function (key) {
  842. if (event.attributes.hasOwnProperty(key)) {
  843. event.attributes[key] = parseFloat(event.attributes[key]);
  844. }
  845. });
  846. this.trigger('data', event);
  847. return;
  848. }
  849. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  850. if (match && match[1]) {
  851. event = {
  852. type: 'tag',
  853. tagType: 'preload-hint'
  854. };
  855. event.attributes = parseAttributes$1(match[1]);
  856. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  857. if (event.attributes.hasOwnProperty(key)) {
  858. event.attributes[key] = parseInt(event.attributes[key], 10);
  859. const subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  860. event.attributes.byterange = event.attributes.byterange || {};
  861. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  862. delete event.attributes[key];
  863. }
  864. });
  865. this.trigger('data', event);
  866. return;
  867. }
  868. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  869. if (match && match[1]) {
  870. event = {
  871. type: 'tag',
  872. tagType: 'rendition-report'
  873. };
  874. event.attributes = parseAttributes$1(match[1]);
  875. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  876. if (event.attributes.hasOwnProperty(key)) {
  877. event.attributes[key] = parseInt(event.attributes[key], 10);
  878. }
  879. });
  880. this.trigger('data', event);
  881. return;
  882. } // unknown tag type
  883. this.trigger('data', {
  884. type: 'tag',
  885. data: newLine.slice(4)
  886. });
  887. });
  888. }
  889. /**
  890. * Add a parser for custom headers
  891. *
  892. * @param {Object} options a map of options for the added parser
  893. * @param {RegExp} options.expression a regular expression to match the custom header
  894. * @param {string} options.customType the custom type to register to the output
  895. * @param {Function} [options.dataParser] function to parse the line into an object
  896. * @param {boolean} [options.segment] should tag data be attached to the segment object
  897. */
  898. addParser({
  899. expression,
  900. customType,
  901. dataParser,
  902. segment
  903. }) {
  904. if (typeof dataParser !== 'function') {
  905. dataParser = line => line;
  906. }
  907. this.customParsers.push(line => {
  908. const match = expression.exec(line);
  909. if (match) {
  910. this.trigger('data', {
  911. type: 'custom',
  912. data: dataParser(line),
  913. customType,
  914. segment
  915. });
  916. return true;
  917. }
  918. });
  919. }
  920. /**
  921. * Add a custom header mapper
  922. *
  923. * @param {Object} options
  924. * @param {RegExp} options.expression a regular expression to match the custom header
  925. * @param {Function} options.map function to translate tag into a different tag
  926. */
  927. addTagMapper({
  928. expression,
  929. map
  930. }) {
  931. const mapFn = line => {
  932. if (expression.test(line)) {
  933. return map(line);
  934. }
  935. return line;
  936. };
  937. this.tagMappers.push(mapFn);
  938. }
  939. }
  940. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  941. const camelCaseKeys = function (attributes) {
  942. const result = {};
  943. Object.keys(attributes).forEach(function (key) {
  944. result[camelCase(key)] = attributes[key];
  945. });
  946. return result;
  947. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  948. // we need this helper because defaults are based upon targetDuration and
  949. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  950. // target durations are set.
  951. const setHoldBack = function (manifest) {
  952. const {
  953. serverControl,
  954. targetDuration,
  955. partTargetDuration
  956. } = manifest;
  957. if (!serverControl) {
  958. return;
  959. }
  960. const tag = '#EXT-X-SERVER-CONTROL';
  961. const hb = 'holdBack';
  962. const phb = 'partHoldBack';
  963. const minTargetDuration = targetDuration && targetDuration * 3;
  964. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  965. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  966. serverControl[hb] = minTargetDuration;
  967. this.trigger('info', {
  968. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  969. });
  970. }
  971. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  972. this.trigger('warn', {
  973. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  974. });
  975. serverControl[hb] = minTargetDuration;
  976. } // default no part hold back to part target duration * 3
  977. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  978. serverControl[phb] = partTargetDuration * 3;
  979. this.trigger('info', {
  980. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  981. });
  982. } // if part hold back is too small default it to part target duration * 2
  983. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  984. this.trigger('warn', {
  985. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  986. });
  987. serverControl[phb] = minPartDuration;
  988. }
  989. };
  990. /**
  991. * A parser for M3U8 files. The current interpretation of the input is
  992. * exposed as a property `manifest` on parser objects. It's just two lines to
  993. * create and parse a manifest once you have the contents available as a string:
  994. *
  995. * ```js
  996. * var parser = new m3u8.Parser();
  997. * parser.push(xhr.responseText);
  998. * ```
  999. *
  1000. * New input can later be applied to update the manifest object by calling
  1001. * `push` again.
  1002. *
  1003. * The parser attempts to create a usable manifest object even if the
  1004. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  1005. * events during the parse if it encounters input that seems invalid or
  1006. * requires some property of the manifest object to be defaulted.
  1007. *
  1008. * @class Parser
  1009. * @extends Stream
  1010. */
  1011. class Parser extends Stream {
  1012. constructor() {
  1013. super();
  1014. this.lineStream = new LineStream();
  1015. this.parseStream = new ParseStream();
  1016. this.lineStream.pipe(this.parseStream);
  1017. /* eslint-disable consistent-this */
  1018. const self = this;
  1019. /* eslint-enable consistent-this */
  1020. const uris = [];
  1021. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  1022. let currentMap; // if specified, the active decryption key
  1023. let key;
  1024. let hasParts = false;
  1025. const noop = function () {};
  1026. const defaultMediaGroups = {
  1027. 'AUDIO': {},
  1028. 'VIDEO': {},
  1029. 'CLOSED-CAPTIONS': {},
  1030. 'SUBTITLES': {}
  1031. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  1032. // used in MPDs with Widevine encrypted streams.
  1033. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  1034. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  1035. this.manifest = {
  1036. allowCache: true,
  1037. discontinuityStarts: [],
  1038. segments: []
  1039. }; // keep track of the last seen segment's byte range end, as segments are not required
  1040. // to provide the offset, in which case it defaults to the next byte after the
  1041. // previous segment
  1042. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  1043. let lastPartByterangeEnd = 0;
  1044. this.on('end', () => {
  1045. // only add preloadSegment if we don't yet have a uri for it.
  1046. // and we actually have parts/preloadHints
  1047. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  1048. return;
  1049. }
  1050. if (!currentUri.map && currentMap) {
  1051. currentUri.map = currentMap;
  1052. }
  1053. if (!currentUri.key && key) {
  1054. currentUri.key = key;
  1055. }
  1056. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  1057. currentUri.timeline = currentTimeline;
  1058. }
  1059. this.manifest.preloadSegment = currentUri;
  1060. }); // update the manifest with the m3u8 entry from the parse stream
  1061. this.parseStream.on('data', function (entry) {
  1062. let mediaGroup;
  1063. let rendition;
  1064. ({
  1065. tag() {
  1066. // switch based on the tag type
  1067. (({
  1068. version() {
  1069. if (entry.version) {
  1070. this.manifest.version = entry.version;
  1071. }
  1072. },
  1073. 'allow-cache'() {
  1074. this.manifest.allowCache = entry.allowed;
  1075. if (!('allowed' in entry)) {
  1076. this.trigger('info', {
  1077. message: 'defaulting allowCache to YES'
  1078. });
  1079. this.manifest.allowCache = true;
  1080. }
  1081. },
  1082. byterange() {
  1083. const byterange = {};
  1084. if ('length' in entry) {
  1085. currentUri.byterange = byterange;
  1086. byterange.length = entry.length;
  1087. if (!('offset' in entry)) {
  1088. /*
  1089. * From the latest spec (as of this writing):
  1090. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  1091. *
  1092. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  1093. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  1094. *
  1095. * "If o [offset] is not present, the sub-range begins at the next byte
  1096. * following the sub-range of the previous media segment."
  1097. */
  1098. entry.offset = lastByterangeEnd;
  1099. }
  1100. }
  1101. if ('offset' in entry) {
  1102. currentUri.byterange = byterange;
  1103. byterange.offset = entry.offset;
  1104. }
  1105. lastByterangeEnd = byterange.offset + byterange.length;
  1106. },
  1107. endlist() {
  1108. this.manifest.endList = true;
  1109. },
  1110. inf() {
  1111. if (!('mediaSequence' in this.manifest)) {
  1112. this.manifest.mediaSequence = 0;
  1113. this.trigger('info', {
  1114. message: 'defaulting media sequence to zero'
  1115. });
  1116. }
  1117. if (!('discontinuitySequence' in this.manifest)) {
  1118. this.manifest.discontinuitySequence = 0;
  1119. this.trigger('info', {
  1120. message: 'defaulting discontinuity sequence to zero'
  1121. });
  1122. }
  1123. if (entry.duration > 0) {
  1124. currentUri.duration = entry.duration;
  1125. }
  1126. if (entry.duration === 0) {
  1127. currentUri.duration = 0.01;
  1128. this.trigger('info', {
  1129. message: 'updating zero segment duration to a small value'
  1130. });
  1131. }
  1132. this.manifest.segments = uris;
  1133. },
  1134. key() {
  1135. if (!entry.attributes) {
  1136. this.trigger('warn', {
  1137. message: 'ignoring key declaration without attribute list'
  1138. });
  1139. return;
  1140. } // clear the active encryption key
  1141. if (entry.attributes.METHOD === 'NONE') {
  1142. key = null;
  1143. return;
  1144. }
  1145. if (!entry.attributes.URI) {
  1146. this.trigger('warn', {
  1147. message: 'ignoring key declaration without URI'
  1148. });
  1149. return;
  1150. }
  1151. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  1152. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1153. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  1154. attributes: entry.attributes
  1155. };
  1156. return;
  1157. }
  1158. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  1159. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1160. this.manifest.contentProtection['com.microsoft.playready'] = {
  1161. uri: entry.attributes.URI
  1162. };
  1163. return;
  1164. } // check if the content is encrypted for Widevine
  1165. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  1166. if (entry.attributes.KEYFORMAT === widevineUuid) {
  1167. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  1168. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  1169. this.trigger('warn', {
  1170. message: 'invalid key method provided for Widevine'
  1171. });
  1172. return;
  1173. }
  1174. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  1175. this.trigger('warn', {
  1176. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  1177. });
  1178. }
  1179. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  1180. this.trigger('warn', {
  1181. message: 'invalid key URI provided for Widevine'
  1182. });
  1183. return;
  1184. }
  1185. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  1186. this.trigger('warn', {
  1187. message: 'invalid key ID provided for Widevine'
  1188. });
  1189. return;
  1190. } // if Widevine key attributes are valid, store them as `contentProtection`
  1191. // on the manifest to emulate Widevine tag structure in a DASH mpd
  1192. this.manifest.contentProtection = this.manifest.contentProtection || {};
  1193. this.manifest.contentProtection['com.widevine.alpha'] = {
  1194. attributes: {
  1195. schemeIdUri: entry.attributes.KEYFORMAT,
  1196. // remove '0x' from the key id string
  1197. keyId: entry.attributes.KEYID.substring(2)
  1198. },
  1199. // decode the base64-encoded PSSH box
  1200. pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
  1201. };
  1202. return;
  1203. }
  1204. if (!entry.attributes.METHOD) {
  1205. this.trigger('warn', {
  1206. message: 'defaulting key method to AES-128'
  1207. });
  1208. } // setup an encryption key for upcoming segments
  1209. key = {
  1210. method: entry.attributes.METHOD || 'AES-128',
  1211. uri: entry.attributes.URI
  1212. };
  1213. if (typeof entry.attributes.IV !== 'undefined') {
  1214. key.iv = entry.attributes.IV;
  1215. }
  1216. },
  1217. 'media-sequence'() {
  1218. if (!isFinite(entry.number)) {
  1219. this.trigger('warn', {
  1220. message: 'ignoring invalid media sequence: ' + entry.number
  1221. });
  1222. return;
  1223. }
  1224. this.manifest.mediaSequence = entry.number;
  1225. },
  1226. 'discontinuity-sequence'() {
  1227. if (!isFinite(entry.number)) {
  1228. this.trigger('warn', {
  1229. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  1230. });
  1231. return;
  1232. }
  1233. this.manifest.discontinuitySequence = entry.number;
  1234. currentTimeline = entry.number;
  1235. },
  1236. 'playlist-type'() {
  1237. if (!/VOD|EVENT/.test(entry.playlistType)) {
  1238. this.trigger('warn', {
  1239. message: 'ignoring unknown playlist type: ' + entry.playlist
  1240. });
  1241. return;
  1242. }
  1243. this.manifest.playlistType = entry.playlistType;
  1244. },
  1245. map() {
  1246. currentMap = {};
  1247. if (entry.uri) {
  1248. currentMap.uri = entry.uri;
  1249. }
  1250. if (entry.byterange) {
  1251. currentMap.byterange = entry.byterange;
  1252. }
  1253. if (key) {
  1254. currentMap.key = key;
  1255. }
  1256. },
  1257. 'stream-inf'() {
  1258. this.manifest.playlists = uris;
  1259. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1260. if (!entry.attributes) {
  1261. this.trigger('warn', {
  1262. message: 'ignoring empty stream-inf attributes'
  1263. });
  1264. return;
  1265. }
  1266. if (!currentUri.attributes) {
  1267. currentUri.attributes = {};
  1268. }
  1269. _extends(currentUri.attributes, entry.attributes);
  1270. },
  1271. media() {
  1272. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1273. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1274. this.trigger('warn', {
  1275. message: 'ignoring incomplete or missing media group'
  1276. });
  1277. return;
  1278. } // find the media group, creating defaults as necessary
  1279. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1280. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1281. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  1282. rendition = {
  1283. default: /yes/i.test(entry.attributes.DEFAULT)
  1284. };
  1285. if (rendition.default) {
  1286. rendition.autoselect = true;
  1287. } else {
  1288. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1289. }
  1290. if (entry.attributes.LANGUAGE) {
  1291. rendition.language = entry.attributes.LANGUAGE;
  1292. }
  1293. if (entry.attributes.URI) {
  1294. rendition.uri = entry.attributes.URI;
  1295. }
  1296. if (entry.attributes['INSTREAM-ID']) {
  1297. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  1298. }
  1299. if (entry.attributes.CHARACTERISTICS) {
  1300. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  1301. }
  1302. if (entry.attributes.FORCED) {
  1303. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  1304. } // insert the new rendition
  1305. mediaGroup[entry.attributes.NAME] = rendition;
  1306. },
  1307. discontinuity() {
  1308. currentTimeline += 1;
  1309. currentUri.discontinuity = true;
  1310. this.manifest.discontinuityStarts.push(uris.length);
  1311. },
  1312. 'program-date-time'() {
  1313. if (typeof this.manifest.dateTimeString === 'undefined') {
  1314. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  1315. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  1316. // to the manifest object
  1317. // TODO: Consider removing this in future major version
  1318. this.manifest.dateTimeString = entry.dateTimeString;
  1319. this.manifest.dateTimeObject = entry.dateTimeObject;
  1320. }
  1321. currentUri.dateTimeString = entry.dateTimeString;
  1322. currentUri.dateTimeObject = entry.dateTimeObject;
  1323. },
  1324. targetduration() {
  1325. if (!isFinite(entry.duration) || entry.duration < 0) {
  1326. this.trigger('warn', {
  1327. message: 'ignoring invalid target duration: ' + entry.duration
  1328. });
  1329. return;
  1330. }
  1331. this.manifest.targetDuration = entry.duration;
  1332. setHoldBack.call(this, this.manifest);
  1333. },
  1334. start() {
  1335. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  1336. this.trigger('warn', {
  1337. message: 'ignoring start declaration without appropriate attribute list'
  1338. });
  1339. return;
  1340. }
  1341. this.manifest.start = {
  1342. timeOffset: entry.attributes['TIME-OFFSET'],
  1343. precise: entry.attributes.PRECISE
  1344. };
  1345. },
  1346. 'cue-out'() {
  1347. currentUri.cueOut = entry.data;
  1348. },
  1349. 'cue-out-cont'() {
  1350. currentUri.cueOutCont = entry.data;
  1351. },
  1352. 'cue-in'() {
  1353. currentUri.cueIn = entry.data;
  1354. },
  1355. 'skip'() {
  1356. this.manifest.skip = camelCaseKeys(entry.attributes);
  1357. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  1358. },
  1359. 'part'() {
  1360. hasParts = true; // parts are always specifed before a segment
  1361. const segmentIndex = this.manifest.segments.length;
  1362. const part = camelCaseKeys(entry.attributes);
  1363. currentUri.parts = currentUri.parts || [];
  1364. currentUri.parts.push(part);
  1365. if (part.byterange) {
  1366. if (!part.byterange.hasOwnProperty('offset')) {
  1367. part.byterange.offset = lastPartByterangeEnd;
  1368. }
  1369. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  1370. }
  1371. const partIndex = currentUri.parts.length - 1;
  1372. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  1373. if (this.manifest.renditionReports) {
  1374. this.manifest.renditionReports.forEach((r, i) => {
  1375. if (!r.hasOwnProperty('lastPart')) {
  1376. this.trigger('warn', {
  1377. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  1378. });
  1379. }
  1380. });
  1381. }
  1382. },
  1383. 'server-control'() {
  1384. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  1385. if (!attrs.hasOwnProperty('canBlockReload')) {
  1386. attrs.canBlockReload = false;
  1387. this.trigger('info', {
  1388. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  1389. });
  1390. }
  1391. setHoldBack.call(this, this.manifest);
  1392. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  1393. this.trigger('warn', {
  1394. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  1395. });
  1396. }
  1397. },
  1398. 'preload-hint'() {
  1399. // parts are always specifed before a segment
  1400. const segmentIndex = this.manifest.segments.length;
  1401. const hint = camelCaseKeys(entry.attributes);
  1402. const isPart = hint.type && hint.type === 'PART';
  1403. currentUri.preloadHints = currentUri.preloadHints || [];
  1404. currentUri.preloadHints.push(hint);
  1405. if (hint.byterange) {
  1406. if (!hint.byterange.hasOwnProperty('offset')) {
  1407. // use last part byterange end or zero if not a part.
  1408. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  1409. if (isPart) {
  1410. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  1411. }
  1412. }
  1413. }
  1414. const index = currentUri.preloadHints.length - 1;
  1415. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  1416. if (!hint.type) {
  1417. return;
  1418. } // search through all preload hints except for the current one for
  1419. // a duplicate type.
  1420. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  1421. const otherHint = currentUri.preloadHints[i];
  1422. if (!otherHint.type) {
  1423. continue;
  1424. }
  1425. if (otherHint.type === hint.type) {
  1426. this.trigger('warn', {
  1427. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  1428. });
  1429. }
  1430. }
  1431. },
  1432. 'rendition-report'() {
  1433. const report = camelCaseKeys(entry.attributes);
  1434. this.manifest.renditionReports = this.manifest.renditionReports || [];
  1435. this.manifest.renditionReports.push(report);
  1436. const index = this.manifest.renditionReports.length - 1;
  1437. const required = ['LAST-MSN', 'URI'];
  1438. if (hasParts) {
  1439. required.push('LAST-PART');
  1440. }
  1441. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  1442. },
  1443. 'part-inf'() {
  1444. this.manifest.partInf = camelCaseKeys(entry.attributes);
  1445. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  1446. if (this.manifest.partInf.partTarget) {
  1447. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  1448. }
  1449. setHoldBack.call(this, this.manifest);
  1450. }
  1451. })[entry.tagType] || noop).call(self);
  1452. },
  1453. uri() {
  1454. currentUri.uri = entry.uri;
  1455. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  1456. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1457. this.trigger('warn', {
  1458. message: 'defaulting segment duration to the target duration'
  1459. });
  1460. currentUri.duration = this.manifest.targetDuration;
  1461. } // annotate with encryption information, if necessary
  1462. if (key) {
  1463. currentUri.key = key;
  1464. }
  1465. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  1466. if (currentMap) {
  1467. currentUri.map = currentMap;
  1468. } // reset the last byterange end as it needs to be 0 between parts
  1469. lastPartByterangeEnd = 0; // prepare for the next URI
  1470. currentUri = {};
  1471. },
  1472. comment() {// comments are not important for playback
  1473. },
  1474. custom() {
  1475. // if this is segment-level data attach the output to the segment
  1476. if (entry.segment) {
  1477. currentUri.custom = currentUri.custom || {};
  1478. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  1479. } else {
  1480. this.manifest.custom = this.manifest.custom || {};
  1481. this.manifest.custom[entry.customType] = entry.data;
  1482. }
  1483. }
  1484. })[entry.type].call(self);
  1485. });
  1486. }
  1487. warnOnMissingAttributes_(identifier, attributes, required) {
  1488. const missing = [];
  1489. required.forEach(function (key) {
  1490. if (!attributes.hasOwnProperty(key)) {
  1491. missing.push(key);
  1492. }
  1493. });
  1494. if (missing.length) {
  1495. this.trigger('warn', {
  1496. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  1497. });
  1498. }
  1499. }
  1500. /**
  1501. * Parse the input string and update the manifest object.
  1502. *
  1503. * @param {string} chunk a potentially incomplete portion of the manifest
  1504. */
  1505. push(chunk) {
  1506. this.lineStream.push(chunk);
  1507. }
  1508. /**
  1509. * Flush any remaining input. This can be handy if the last line of an M3U8
  1510. * manifest did not contain a trailing newline but the file has been
  1511. * completely received.
  1512. */
  1513. end() {
  1514. // flush any buffered input
  1515. this.lineStream.push('\n');
  1516. this.trigger('end');
  1517. }
  1518. /**
  1519. * Add an additional parser for non-standard tags
  1520. *
  1521. * @param {Object} options a map of options for the added parser
  1522. * @param {RegExp} options.expression a regular expression to match the custom header
  1523. * @param {string} options.type the type to register to the output
  1524. * @param {Function} [options.dataParser] function to parse the line into an object
  1525. * @param {boolean} [options.segment] should tag data be attached to the segment object
  1526. */
  1527. addParser(options) {
  1528. this.parseStream.addParser(options);
  1529. }
  1530. /**
  1531. * Add a custom header mapper
  1532. *
  1533. * @param {Object} options
  1534. * @param {RegExp} options.expression a regular expression to match the custom header
  1535. * @param {Function} options.map function to translate tag into a different tag
  1536. */
  1537. addTagMapper(options) {
  1538. this.parseStream.addTagMapper(options);
  1539. }
  1540. }
  1541. var regexs = {
  1542. // to determine mime types
  1543. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  1544. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  1545. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  1546. // to determine if a codec is audio or video
  1547. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  1548. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  1549. text: /^(stpp.ttml.im1t)/,
  1550. // mux.js support regex
  1551. muxerVideo: /^(avc0?1)/,
  1552. muxerAudio: /^(mp4a)/,
  1553. // match nothing as muxer does not support text right now.
  1554. // there cannot never be a character before the start of a string
  1555. // so this matches nothing.
  1556. muxerText: /a^/
  1557. };
  1558. var mediaTypes = ['video', 'audio', 'text'];
  1559. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  1560. /**
  1561. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  1562. * `avc1.<hhhhhh>`
  1563. *
  1564. * @param {string} codec
  1565. * Codec string to translate
  1566. * @return {string}
  1567. * The translated codec string
  1568. */
  1569. var translateLegacyCodec = function translateLegacyCodec(codec) {
  1570. if (!codec) {
  1571. return codec;
  1572. }
  1573. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  1574. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  1575. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  1576. return 'avc1.' + profileHex + '00' + avcLevelHex;
  1577. });
  1578. };
  1579. /**
  1580. * @typedef {Object} ParsedCodecInfo
  1581. * @property {number} codecCount
  1582. * Number of codecs parsed
  1583. * @property {string} [videoCodec]
  1584. * Parsed video codec (if found)
  1585. * @property {string} [videoObjectTypeIndicator]
  1586. * Video object type indicator (if found)
  1587. * @property {string|null} audioProfile
  1588. * Audio profile
  1589. */
  1590. /**
  1591. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  1592. * object type indicator, and the audio profile.
  1593. *
  1594. * @param {string} [codecString]
  1595. * The codec string to parse
  1596. * @return {ParsedCodecInfo}
  1597. * Parsed codec info
  1598. */
  1599. var parseCodecs = function parseCodecs(codecString) {
  1600. if (codecString === void 0) {
  1601. codecString = '';
  1602. }
  1603. var codecs = codecString.split(',');
  1604. var result = [];
  1605. codecs.forEach(function (codec) {
  1606. codec = codec.trim();
  1607. var codecType;
  1608. mediaTypes.forEach(function (name) {
  1609. var match = regexs[name].exec(codec.toLowerCase());
  1610. if (!match || match.length <= 1) {
  1611. return;
  1612. }
  1613. codecType = name; // maintain codec case
  1614. var type = codec.substring(0, match[1].length);
  1615. var details = codec.replace(type, '');
  1616. result.push({
  1617. type: type,
  1618. details: details,
  1619. mediaType: name
  1620. });
  1621. });
  1622. if (!codecType) {
  1623. result.push({
  1624. type: codec,
  1625. details: '',
  1626. mediaType: 'unknown'
  1627. });
  1628. }
  1629. });
  1630. return result;
  1631. };
  1632. /**
  1633. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  1634. * a default alternate audio playlist for the provided audio group.
  1635. *
  1636. * @param {Object} master
  1637. * The master playlist
  1638. * @param {string} audioGroupId
  1639. * ID of the audio group for which to find the default codec info
  1640. * @return {ParsedCodecInfo}
  1641. * Parsed codec info
  1642. */
  1643. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  1644. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  1645. return null;
  1646. }
  1647. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  1648. if (!audioGroup) {
  1649. return null;
  1650. }
  1651. for (var name in audioGroup) {
  1652. var audioType = audioGroup[name];
  1653. if (audioType.default && audioType.playlists) {
  1654. // codec should be the same for all playlists within the audio type
  1655. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  1656. }
  1657. }
  1658. return null;
  1659. };
  1660. var isAudioCodec = function isAudioCodec(codec) {
  1661. if (codec === void 0) {
  1662. codec = '';
  1663. }
  1664. return regexs.audio.test(codec.trim().toLowerCase());
  1665. };
  1666. var isTextCodec = function isTextCodec(codec) {
  1667. if (codec === void 0) {
  1668. codec = '';
  1669. }
  1670. return regexs.text.test(codec.trim().toLowerCase());
  1671. };
  1672. var getMimeForCodec = function getMimeForCodec(codecString) {
  1673. if (!codecString || typeof codecString !== 'string') {
  1674. return;
  1675. }
  1676. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  1677. return translateLegacyCodec(c.trim());
  1678. }); // default to video type
  1679. var type = 'video'; // only change to audio type if the only codec we have is
  1680. // audio
  1681. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  1682. type = 'audio';
  1683. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  1684. // text uses application/<container> for now
  1685. type = 'application';
  1686. } // default the container to mp4
  1687. var container = 'mp4'; // every codec must be able to go into the container
  1688. // for that container to be the correct one
  1689. if (codecs.every(function (c) {
  1690. return regexs.mp4.test(c);
  1691. })) {
  1692. container = 'mp4';
  1693. } else if (codecs.every(function (c) {
  1694. return regexs.webm.test(c);
  1695. })) {
  1696. container = 'webm';
  1697. } else if (codecs.every(function (c) {
  1698. return regexs.ogg.test(c);
  1699. })) {
  1700. container = 'ogg';
  1701. }
  1702. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  1703. };
  1704. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  1705. if (codecString === void 0) {
  1706. codecString = '';
  1707. }
  1708. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  1709. };
  1710. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  1711. if (codecString === void 0) {
  1712. codecString = '';
  1713. }
  1714. return codecString.toLowerCase().split(',').every(function (codec) {
  1715. codec = codec.trim(); // any match is supported.
  1716. for (var i = 0; i < upperMediaTypes.length; i++) {
  1717. var type = upperMediaTypes[i];
  1718. if (regexs["muxer" + type].test(codec)) {
  1719. return true;
  1720. }
  1721. }
  1722. return false;
  1723. });
  1724. };
  1725. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  1726. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  1727. /**
  1728. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  1729. */
  1730. /**
  1731. * Delegates to videojs.obj.merge (Video.js 8) or
  1732. * videojs.mergeOptions (Video.js 7).
  1733. */
  1734. function merge$1(...args) {
  1735. const context = videojs__default["default"].obj || videojs__default["default"];
  1736. const fn = context.merge || context.mergeOptions;
  1737. return fn.apply(context, args);
  1738. }
  1739. /**
  1740. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  1741. * videojs.createTimeRanges (Video.js 7).
  1742. */
  1743. function createTimeRanges(...args) {
  1744. const context = videojs__default["default"].time || videojs__default["default"];
  1745. const fn = context.createTimeRanges || context.createTimeRanges;
  1746. return fn.apply(context, args);
  1747. }
  1748. /**
  1749. * ranges
  1750. *
  1751. * Utilities for working with TimeRanges.
  1752. *
  1753. */
  1754. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  1755. // can be misleading because of precision differences or when the current media has poorly
  1756. // aligned audio and video, which can cause values to be slightly off from what you would
  1757. // expect. This value is what we consider to be safe to use in such comparisons to account
  1758. // for these scenarios.
  1759. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  1760. const filterRanges = function (timeRanges, predicate) {
  1761. const results = [];
  1762. let i;
  1763. if (timeRanges && timeRanges.length) {
  1764. // Search for ranges that match the predicate
  1765. for (i = 0; i < timeRanges.length; i++) {
  1766. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  1767. results.push([timeRanges.start(i), timeRanges.end(i)]);
  1768. }
  1769. }
  1770. }
  1771. return createTimeRanges(results);
  1772. };
  1773. /**
  1774. * Attempts to find the buffered TimeRange that contains the specified
  1775. * time.
  1776. *
  1777. * @param {TimeRanges} buffered - the TimeRanges object to query
  1778. * @param {number} time - the time to filter on.
  1779. * @return {TimeRanges} a new TimeRanges object
  1780. */
  1781. const findRange = function (buffered, time) {
  1782. return filterRanges(buffered, function (start, end) {
  1783. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  1784. });
  1785. };
  1786. /**
  1787. * Returns the TimeRanges that begin later than the specified time.
  1788. *
  1789. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  1790. * @param {number} time - the time to filter on.
  1791. * @return {TimeRanges} a new TimeRanges object.
  1792. */
  1793. const findNextRange = function (timeRanges, time) {
  1794. return filterRanges(timeRanges, function (start) {
  1795. return start - TIME_FUDGE_FACTOR >= time;
  1796. });
  1797. };
  1798. /**
  1799. * Returns gaps within a list of TimeRanges
  1800. *
  1801. * @param {TimeRanges} buffered - the TimeRanges object
  1802. * @return {TimeRanges} a TimeRanges object of gaps
  1803. */
  1804. const findGaps = function (buffered) {
  1805. if (buffered.length < 2) {
  1806. return createTimeRanges();
  1807. }
  1808. const ranges = [];
  1809. for (let i = 1; i < buffered.length; i++) {
  1810. const start = buffered.end(i - 1);
  1811. const end = buffered.start(i);
  1812. ranges.push([start, end]);
  1813. }
  1814. return createTimeRanges(ranges);
  1815. };
  1816. /**
  1817. * Calculate the intersection of two TimeRanges
  1818. *
  1819. * @param {TimeRanges} bufferA
  1820. * @param {TimeRanges} bufferB
  1821. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  1822. */
  1823. const bufferIntersection = function (bufferA, bufferB) {
  1824. let start = null;
  1825. let end = null;
  1826. let arity = 0;
  1827. const extents = [];
  1828. const ranges = [];
  1829. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  1830. return createTimeRanges();
  1831. } // Handle the case where we have both buffers and create an
  1832. // intersection of the two
  1833. let count = bufferA.length; // A) Gather up all start and end times
  1834. while (count--) {
  1835. extents.push({
  1836. time: bufferA.start(count),
  1837. type: 'start'
  1838. });
  1839. extents.push({
  1840. time: bufferA.end(count),
  1841. type: 'end'
  1842. });
  1843. }
  1844. count = bufferB.length;
  1845. while (count--) {
  1846. extents.push({
  1847. time: bufferB.start(count),
  1848. type: 'start'
  1849. });
  1850. extents.push({
  1851. time: bufferB.end(count),
  1852. type: 'end'
  1853. });
  1854. } // B) Sort them by time
  1855. extents.sort(function (a, b) {
  1856. return a.time - b.time;
  1857. }); // C) Go along one by one incrementing arity for start and decrementing
  1858. // arity for ends
  1859. for (count = 0; count < extents.length; count++) {
  1860. if (extents[count].type === 'start') {
  1861. arity++; // D) If arity is ever incremented to 2 we are entering an
  1862. // overlapping range
  1863. if (arity === 2) {
  1864. start = extents[count].time;
  1865. }
  1866. } else if (extents[count].type === 'end') {
  1867. arity--; // E) If arity is ever decremented to 1 we leaving an
  1868. // overlapping range
  1869. if (arity === 1) {
  1870. end = extents[count].time;
  1871. }
  1872. } // F) Record overlapping ranges
  1873. if (start !== null && end !== null) {
  1874. ranges.push([start, end]);
  1875. start = null;
  1876. end = null;
  1877. }
  1878. }
  1879. return createTimeRanges(ranges);
  1880. };
  1881. /**
  1882. * Gets a human readable string for a TimeRange
  1883. *
  1884. * @param {TimeRange} range
  1885. * @return {string} a human readable string
  1886. */
  1887. const printableRange = range => {
  1888. const strArr = [];
  1889. if (!range || !range.length) {
  1890. return '';
  1891. }
  1892. for (let i = 0; i < range.length; i++) {
  1893. strArr.push(range.start(i) + ' => ' + range.end(i));
  1894. }
  1895. return strArr.join(', ');
  1896. };
  1897. /**
  1898. * Calculates the amount of time left in seconds until the player hits the end of the
  1899. * buffer and causes a rebuffer
  1900. *
  1901. * @param {TimeRange} buffered
  1902. * The state of the buffer
  1903. * @param {Numnber} currentTime
  1904. * The current time of the player
  1905. * @param {number} playbackRate
  1906. * The current playback rate of the player. Defaults to 1.
  1907. * @return {number}
  1908. * Time until the player has to start rebuffering in seconds.
  1909. * @function timeUntilRebuffer
  1910. */
  1911. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  1912. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  1913. return (bufferedEnd - currentTime) / playbackRate;
  1914. };
  1915. /**
  1916. * Converts a TimeRanges object into an array representation
  1917. *
  1918. * @param {TimeRanges} timeRanges
  1919. * @return {Array}
  1920. */
  1921. const timeRangesToArray = timeRanges => {
  1922. const timeRangesList = [];
  1923. for (let i = 0; i < timeRanges.length; i++) {
  1924. timeRangesList.push({
  1925. start: timeRanges.start(i),
  1926. end: timeRanges.end(i)
  1927. });
  1928. }
  1929. return timeRangesList;
  1930. };
  1931. /**
  1932. * Determines if two time range objects are different.
  1933. *
  1934. * @param {TimeRange} a
  1935. * the first time range object to check
  1936. *
  1937. * @param {TimeRange} b
  1938. * the second time range object to check
  1939. *
  1940. * @return {Boolean}
  1941. * Whether the time range objects differ
  1942. */
  1943. const isRangeDifferent = function (a, b) {
  1944. // same object
  1945. if (a === b) {
  1946. return false;
  1947. } // one or the other is undefined
  1948. if (!a && b || !b && a) {
  1949. return true;
  1950. } // length is different
  1951. if (a.length !== b.length) {
  1952. return true;
  1953. } // see if any start/end pair is different
  1954. for (let i = 0; i < a.length; i++) {
  1955. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  1956. return true;
  1957. }
  1958. } // if the length and every pair is the same
  1959. // this is the same time range
  1960. return false;
  1961. };
  1962. const lastBufferedEnd = function (a) {
  1963. if (!a || !a.length || !a.end) {
  1964. return;
  1965. }
  1966. return a.end(a.length - 1);
  1967. };
  1968. /**
  1969. * A utility function to add up the amount of time in a timeRange
  1970. * after a specified startTime.
  1971. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  1972. * would return 40 as there are 40s seconds after 0 in the timeRange
  1973. *
  1974. * @param {TimeRange} range
  1975. * The range to check against
  1976. * @param {number} startTime
  1977. * The time in the time range that you should start counting from
  1978. *
  1979. * @return {number}
  1980. * The number of seconds in the buffer passed the specified time.
  1981. */
  1982. const timeAheadOf = function (range, startTime) {
  1983. let time = 0;
  1984. if (!range || !range.length) {
  1985. return time;
  1986. }
  1987. for (let i = 0; i < range.length; i++) {
  1988. const start = range.start(i);
  1989. const end = range.end(i); // startTime is after this range entirely
  1990. if (startTime > end) {
  1991. continue;
  1992. } // startTime is within this range
  1993. if (startTime > start && startTime <= end) {
  1994. time += end - startTime;
  1995. continue;
  1996. } // startTime is before this range.
  1997. time += end - start;
  1998. }
  1999. return time;
  2000. };
  2001. /**
  2002. * @file playlist.js
  2003. *
  2004. * Playlist related utilities.
  2005. */
  2006. /**
  2007. * Get the duration of a segment, with special cases for
  2008. * llhls segments that do not have a duration yet.
  2009. *
  2010. * @param {Object} playlist
  2011. * the playlist that the segment belongs to.
  2012. * @param {Object} segment
  2013. * the segment to get a duration for.
  2014. *
  2015. * @return {number}
  2016. * the segment duration
  2017. */
  2018. const segmentDurationWithParts = (playlist, segment) => {
  2019. // if this isn't a preload segment
  2020. // then we will have a segment duration that is accurate.
  2021. if (!segment.preload) {
  2022. return segment.duration;
  2023. } // otherwise we have to add up parts and preload hints
  2024. // to get an up to date duration.
  2025. let result = 0;
  2026. (segment.parts || []).forEach(function (p) {
  2027. result += p.duration;
  2028. }); // for preload hints we have to use partTargetDuration
  2029. // as they won't even have a duration yet.
  2030. (segment.preloadHints || []).forEach(function (p) {
  2031. if (p.type === 'PART') {
  2032. result += playlist.partTargetDuration;
  2033. }
  2034. });
  2035. return result;
  2036. };
  2037. /**
  2038. * A function to get a combined list of parts and segments with durations
  2039. * and indexes.
  2040. *
  2041. * @param {Playlist} playlist the playlist to get the list for.
  2042. *
  2043. * @return {Array} The part/segment list.
  2044. */
  2045. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  2046. if (segment.parts) {
  2047. segment.parts.forEach(function (part, pi) {
  2048. acc.push({
  2049. duration: part.duration,
  2050. segmentIndex: si,
  2051. partIndex: pi,
  2052. part,
  2053. segment
  2054. });
  2055. });
  2056. } else {
  2057. acc.push({
  2058. duration: segment.duration,
  2059. segmentIndex: si,
  2060. partIndex: null,
  2061. segment,
  2062. part: null
  2063. });
  2064. }
  2065. return acc;
  2066. }, []);
  2067. const getLastParts = media => {
  2068. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  2069. return lastSegment && lastSegment.parts || [];
  2070. };
  2071. const getKnownPartCount = ({
  2072. preloadSegment
  2073. }) => {
  2074. if (!preloadSegment) {
  2075. return;
  2076. }
  2077. const {
  2078. parts,
  2079. preloadHints
  2080. } = preloadSegment;
  2081. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  2082. partCount += parts && parts.length ? parts.length : 0;
  2083. return partCount;
  2084. };
  2085. /**
  2086. * Get the number of seconds to delay from the end of a
  2087. * live playlist.
  2088. *
  2089. * @param {Playlist} main the main playlist
  2090. * @param {Playlist} media the media playlist
  2091. * @return {number} the hold back in seconds.
  2092. */
  2093. const liveEdgeDelay = (main, media) => {
  2094. if (media.endList) {
  2095. return 0;
  2096. } // dash suggestedPresentationDelay trumps everything
  2097. if (main && main.suggestedPresentationDelay) {
  2098. return main.suggestedPresentationDelay;
  2099. }
  2100. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  2101. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  2102. return media.serverControl.partHoldBack;
  2103. } else if (hasParts && media.partTargetDuration) {
  2104. return media.partTargetDuration * 3; // finally look for full segment delays
  2105. } else if (media.serverControl && media.serverControl.holdBack) {
  2106. return media.serverControl.holdBack;
  2107. } else if (media.targetDuration) {
  2108. return media.targetDuration * 3;
  2109. }
  2110. return 0;
  2111. };
  2112. /**
  2113. * walk backward until we find a duration we can use
  2114. * or return a failure
  2115. *
  2116. * @param {Playlist} playlist the playlist to walk through
  2117. * @param {Number} endSequence the mediaSequence to stop walking on
  2118. */
  2119. const backwardDuration = function (playlist, endSequence) {
  2120. let result = 0;
  2121. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  2122. // the interval, use it
  2123. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  2124. // information that is earlier than endSequence
  2125. if (segment) {
  2126. if (typeof segment.start !== 'undefined') {
  2127. return {
  2128. result: segment.start,
  2129. precise: true
  2130. };
  2131. }
  2132. if (typeof segment.end !== 'undefined') {
  2133. return {
  2134. result: segment.end - segment.duration,
  2135. precise: true
  2136. };
  2137. }
  2138. }
  2139. while (i--) {
  2140. segment = playlist.segments[i];
  2141. if (typeof segment.end !== 'undefined') {
  2142. return {
  2143. result: result + segment.end,
  2144. precise: true
  2145. };
  2146. }
  2147. result += segmentDurationWithParts(playlist, segment);
  2148. if (typeof segment.start !== 'undefined') {
  2149. return {
  2150. result: result + segment.start,
  2151. precise: true
  2152. };
  2153. }
  2154. }
  2155. return {
  2156. result,
  2157. precise: false
  2158. };
  2159. };
  2160. /**
  2161. * walk forward until we find a duration we can use
  2162. * or return a failure
  2163. *
  2164. * @param {Playlist} playlist the playlist to walk through
  2165. * @param {number} endSequence the mediaSequence to stop walking on
  2166. */
  2167. const forwardDuration = function (playlist, endSequence) {
  2168. let result = 0;
  2169. let segment;
  2170. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  2171. // information
  2172. for (; i < playlist.segments.length; i++) {
  2173. segment = playlist.segments[i];
  2174. if (typeof segment.start !== 'undefined') {
  2175. return {
  2176. result: segment.start - result,
  2177. precise: true
  2178. };
  2179. }
  2180. result += segmentDurationWithParts(playlist, segment);
  2181. if (typeof segment.end !== 'undefined') {
  2182. return {
  2183. result: segment.end - result,
  2184. precise: true
  2185. };
  2186. }
  2187. } // indicate we didn't find a useful duration estimate
  2188. return {
  2189. result: -1,
  2190. precise: false
  2191. };
  2192. };
  2193. /**
  2194. * Calculate the media duration from the segments associated with a
  2195. * playlist. The duration of a subinterval of the available segments
  2196. * may be calculated by specifying an end index.
  2197. *
  2198. * @param {Object} playlist a media playlist object
  2199. * @param {number=} endSequence an exclusive upper boundary
  2200. * for the playlist. Defaults to playlist length.
  2201. * @param {number} expired the amount of time that has dropped
  2202. * off the front of the playlist in a live scenario
  2203. * @return {number} the duration between the first available segment
  2204. * and end index.
  2205. */
  2206. const intervalDuration = function (playlist, endSequence, expired) {
  2207. if (typeof endSequence === 'undefined') {
  2208. endSequence = playlist.mediaSequence + playlist.segments.length;
  2209. }
  2210. if (endSequence < playlist.mediaSequence) {
  2211. return 0;
  2212. } // do a backward walk to estimate the duration
  2213. const backward = backwardDuration(playlist, endSequence);
  2214. if (backward.precise) {
  2215. // if we were able to base our duration estimate on timing
  2216. // information provided directly from the Media Source, return
  2217. // it
  2218. return backward.result;
  2219. } // walk forward to see if a precise duration estimate can be made
  2220. // that way
  2221. const forward = forwardDuration(playlist, endSequence);
  2222. if (forward.precise) {
  2223. // we found a segment that has been buffered and so it's
  2224. // position is known precisely
  2225. return forward.result;
  2226. } // return the less-precise, playlist-based duration estimate
  2227. return backward.result + expired;
  2228. };
  2229. /**
  2230. * Calculates the duration of a playlist. If a start and end index
  2231. * are specified, the duration will be for the subset of the media
  2232. * timeline between those two indices. The total duration for live
  2233. * playlists is always Infinity.
  2234. *
  2235. * @param {Object} playlist a media playlist object
  2236. * @param {number=} endSequence an exclusive upper
  2237. * boundary for the playlist. Defaults to the playlist media
  2238. * sequence number plus its length.
  2239. * @param {number=} expired the amount of time that has
  2240. * dropped off the front of the playlist in a live scenario
  2241. * @return {number} the duration between the start index and end
  2242. * index.
  2243. */
  2244. const duration = function (playlist, endSequence, expired) {
  2245. if (!playlist) {
  2246. return 0;
  2247. }
  2248. if (typeof expired !== 'number') {
  2249. expired = 0;
  2250. } // if a slice of the total duration is not requested, use
  2251. // playlist-level duration indicators when they're present
  2252. if (typeof endSequence === 'undefined') {
  2253. // if present, use the duration specified in the playlist
  2254. if (playlist.totalDuration) {
  2255. return playlist.totalDuration;
  2256. } // duration should be Infinity for live playlists
  2257. if (!playlist.endList) {
  2258. return window.Infinity;
  2259. }
  2260. } // calculate the total duration based on the segment durations
  2261. return intervalDuration(playlist, endSequence, expired);
  2262. };
  2263. /**
  2264. * Calculate the time between two indexes in the current playlist
  2265. * neight the start- nor the end-index need to be within the current
  2266. * playlist in which case, the targetDuration of the playlist is used
  2267. * to approximate the durations of the segments
  2268. *
  2269. * @param {Array} options.durationList list to iterate over for durations.
  2270. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  2271. * @param {number} options.startIndex partsAndSegments index to start
  2272. * @param {number} options.endIndex partsAndSegments index to end.
  2273. * @return {number} the number of seconds between startIndex and endIndex
  2274. */
  2275. const sumDurations = function ({
  2276. defaultDuration,
  2277. durationList,
  2278. startIndex,
  2279. endIndex
  2280. }) {
  2281. let durations = 0;
  2282. if (startIndex > endIndex) {
  2283. [startIndex, endIndex] = [endIndex, startIndex];
  2284. }
  2285. if (startIndex < 0) {
  2286. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  2287. durations += defaultDuration;
  2288. }
  2289. startIndex = 0;
  2290. }
  2291. for (let i = startIndex; i < endIndex; i++) {
  2292. durations += durationList[i].duration;
  2293. }
  2294. return durations;
  2295. };
  2296. /**
  2297. * Calculates the playlist end time
  2298. *
  2299. * @param {Object} playlist a media playlist object
  2300. * @param {number=} expired the amount of time that has
  2301. * dropped off the front of the playlist in a live scenario
  2302. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  2303. * playlist end calculation should consider the safe live end
  2304. * (truncate the playlist end by three segments). This is normally
  2305. * used for calculating the end of the playlist's seekable range.
  2306. * This takes into account the value of liveEdgePadding.
  2307. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  2308. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  2309. * If this is provided, it is used in the safe live end calculation.
  2310. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  2311. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2312. * @return {number} the end time of playlist
  2313. * @function playlistEnd
  2314. */
  2315. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  2316. if (!playlist || !playlist.segments) {
  2317. return null;
  2318. }
  2319. if (playlist.endList) {
  2320. return duration(playlist);
  2321. }
  2322. if (expired === null) {
  2323. return null;
  2324. }
  2325. expired = expired || 0;
  2326. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  2327. if (useSafeLiveEnd) {
  2328. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  2329. lastSegmentEndTime -= liveEdgePadding;
  2330. } // don't return a time less than zero
  2331. return Math.max(0, lastSegmentEndTime);
  2332. };
  2333. /**
  2334. * Calculates the interval of time that is currently seekable in a
  2335. * playlist. The returned time ranges are relative to the earliest
  2336. * moment in the specified playlist that is still available. A full
  2337. * seekable implementation for live streams would need to offset
  2338. * these values by the duration of content that has expired from the
  2339. * stream.
  2340. *
  2341. * @param {Object} playlist a media playlist object
  2342. * dropped off the front of the playlist in a live scenario
  2343. * @param {number=} expired the amount of time that has
  2344. * dropped off the front of the playlist in a live scenario
  2345. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  2346. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2347. * @return {TimeRanges} the periods of time that are valid targets
  2348. * for seeking
  2349. */
  2350. const seekable = function (playlist, expired, liveEdgePadding) {
  2351. const useSafeLiveEnd = true;
  2352. const seekableStart = expired || 0;
  2353. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  2354. if (seekableEnd === null) {
  2355. return createTimeRanges();
  2356. }
  2357. return createTimeRanges(seekableStart, seekableEnd);
  2358. };
  2359. /**
  2360. * Determine the index and estimated starting time of the segment that
  2361. * contains a specified playback position in a media playlist.
  2362. *
  2363. * @param {Object} options.playlist the media playlist to query
  2364. * @param {number} options.currentTime The number of seconds since the earliest
  2365. * possible position to determine the containing segment for
  2366. * @param {number} options.startTime the time when the segment/part starts
  2367. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  2368. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  2369. *
  2370. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  2371. */
  2372. const getMediaInfoForTime = function ({
  2373. playlist,
  2374. currentTime,
  2375. startingSegmentIndex,
  2376. startingPartIndex,
  2377. startTime,
  2378. exactManifestTimings
  2379. }) {
  2380. let time = currentTime - startTime;
  2381. const partsAndSegments = getPartsAndSegments(playlist);
  2382. let startIndex = 0;
  2383. for (let i = 0; i < partsAndSegments.length; i++) {
  2384. const partAndSegment = partsAndSegments[i];
  2385. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  2386. continue;
  2387. } // skip this if part index does not match.
  2388. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  2389. continue;
  2390. }
  2391. startIndex = i;
  2392. break;
  2393. }
  2394. if (time < 0) {
  2395. // Walk backward from startIndex in the playlist, adding durations
  2396. // until we find a segment that contains `time` and return it
  2397. if (startIndex > 0) {
  2398. for (let i = startIndex - 1; i >= 0; i--) {
  2399. const partAndSegment = partsAndSegments[i];
  2400. time += partAndSegment.duration;
  2401. if (exactManifestTimings) {
  2402. if (time < 0) {
  2403. continue;
  2404. }
  2405. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  2406. continue;
  2407. }
  2408. return {
  2409. partIndex: partAndSegment.partIndex,
  2410. segmentIndex: partAndSegment.segmentIndex,
  2411. startTime: startTime - sumDurations({
  2412. defaultDuration: playlist.targetDuration,
  2413. durationList: partsAndSegments,
  2414. startIndex,
  2415. endIndex: i
  2416. })
  2417. };
  2418. }
  2419. } // We were unable to find a good segment within the playlist
  2420. // so select the first segment
  2421. return {
  2422. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2423. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2424. startTime: currentTime
  2425. };
  2426. } // When startIndex is negative, we first walk forward to first segment
  2427. // adding target durations. If we "run out of time" before getting to
  2428. // the first segment, return the first segment
  2429. if (startIndex < 0) {
  2430. for (let i = startIndex; i < 0; i++) {
  2431. time -= playlist.targetDuration;
  2432. if (time < 0) {
  2433. return {
  2434. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2435. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2436. startTime: currentTime
  2437. };
  2438. }
  2439. }
  2440. startIndex = 0;
  2441. } // Walk forward from startIndex in the playlist, subtracting durations
  2442. // until we find a segment that contains `time` and return it
  2443. for (let i = startIndex; i < partsAndSegments.length; i++) {
  2444. const partAndSegment = partsAndSegments[i];
  2445. time -= partAndSegment.duration;
  2446. if (exactManifestTimings) {
  2447. if (time > 0) {
  2448. continue;
  2449. }
  2450. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  2451. continue;
  2452. }
  2453. return {
  2454. partIndex: partAndSegment.partIndex,
  2455. segmentIndex: partAndSegment.segmentIndex,
  2456. startTime: startTime + sumDurations({
  2457. defaultDuration: playlist.targetDuration,
  2458. durationList: partsAndSegments,
  2459. startIndex,
  2460. endIndex: i
  2461. })
  2462. };
  2463. } // We are out of possible candidates so load the last one...
  2464. return {
  2465. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  2466. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  2467. startTime: currentTime
  2468. };
  2469. };
  2470. /**
  2471. * Check whether the playlist is excluded or not.
  2472. *
  2473. * @param {Object} playlist the media playlist object
  2474. * @return {boolean} whether the playlist is excluded or not
  2475. * @function isExcluded
  2476. */
  2477. const isExcluded = function (playlist) {
  2478. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  2479. };
  2480. /**
  2481. * Check whether the playlist is compatible with current playback configuration or has
  2482. * been excluded permanently for being incompatible.
  2483. *
  2484. * @param {Object} playlist the media playlist object
  2485. * @return {boolean} whether the playlist is incompatible or not
  2486. * @function isIncompatible
  2487. */
  2488. const isIncompatible = function (playlist) {
  2489. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  2490. };
  2491. /**
  2492. * Check whether the playlist is enabled or not.
  2493. *
  2494. * @param {Object} playlist the media playlist object
  2495. * @return {boolean} whether the playlist is enabled or not
  2496. * @function isEnabled
  2497. */
  2498. const isEnabled = function (playlist) {
  2499. const excluded = isExcluded(playlist);
  2500. return !playlist.disabled && !excluded;
  2501. };
  2502. /**
  2503. * Check whether the playlist has been manually disabled through the representations api.
  2504. *
  2505. * @param {Object} playlist the media playlist object
  2506. * @return {boolean} whether the playlist is disabled manually or not
  2507. * @function isDisabled
  2508. */
  2509. const isDisabled = function (playlist) {
  2510. return playlist.disabled;
  2511. };
  2512. /**
  2513. * Returns whether the current playlist is an AES encrypted HLS stream
  2514. *
  2515. * @return {boolean} true if it's an AES encrypted HLS stream
  2516. */
  2517. const isAes = function (media) {
  2518. for (let i = 0; i < media.segments.length; i++) {
  2519. if (media.segments[i].key) {
  2520. return true;
  2521. }
  2522. }
  2523. return false;
  2524. };
  2525. /**
  2526. * Checks if the playlist has a value for the specified attribute
  2527. *
  2528. * @param {string} attr
  2529. * Attribute to check for
  2530. * @param {Object} playlist
  2531. * The media playlist object
  2532. * @return {boolean}
  2533. * Whether the playlist contains a value for the attribute or not
  2534. * @function hasAttribute
  2535. */
  2536. const hasAttribute = function (attr, playlist) {
  2537. return playlist.attributes && playlist.attributes[attr];
  2538. };
  2539. /**
  2540. * Estimates the time required to complete a segment download from the specified playlist
  2541. *
  2542. * @param {number} segmentDuration
  2543. * Duration of requested segment
  2544. * @param {number} bandwidth
  2545. * Current measured bandwidth of the player
  2546. * @param {Object} playlist
  2547. * The media playlist object
  2548. * @param {number=} bytesReceived
  2549. * Number of bytes already received for the request. Defaults to 0
  2550. * @return {number|NaN}
  2551. * The estimated time to request the segment. NaN if bandwidth information for
  2552. * the given playlist is unavailable
  2553. * @function estimateSegmentRequestTime
  2554. */
  2555. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  2556. if (!hasAttribute('BANDWIDTH', playlist)) {
  2557. return NaN;
  2558. }
  2559. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  2560. return (size - bytesReceived * 8) / bandwidth;
  2561. };
  2562. /*
  2563. * Returns whether the current playlist is the lowest rendition
  2564. *
  2565. * @return {Boolean} true if on lowest rendition
  2566. */
  2567. const isLowestEnabledRendition = (main, media) => {
  2568. if (main.playlists.length === 1) {
  2569. return true;
  2570. }
  2571. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  2572. return main.playlists.filter(playlist => {
  2573. if (!isEnabled(playlist)) {
  2574. return false;
  2575. }
  2576. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  2577. }).length === 0;
  2578. };
  2579. const playlistMatch = (a, b) => {
  2580. // both playlits are null
  2581. // or only one playlist is non-null
  2582. // no match
  2583. if (!a && !b || !a && b || a && !b) {
  2584. return false;
  2585. } // playlist objects are the same, match
  2586. if (a === b) {
  2587. return true;
  2588. } // first try to use id as it should be the most
  2589. // accurate
  2590. if (a.id && b.id && a.id === b.id) {
  2591. return true;
  2592. } // next try to use reslovedUri as it should be the
  2593. // second most accurate.
  2594. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  2595. return true;
  2596. } // finally try to use uri as it should be accurate
  2597. // but might miss a few cases for relative uris
  2598. if (a.uri && b.uri && a.uri === b.uri) {
  2599. return true;
  2600. }
  2601. return false;
  2602. };
  2603. const someAudioVariant = function (main, callback) {
  2604. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  2605. let found = false;
  2606. for (const groupName in AUDIO) {
  2607. for (const label in AUDIO[groupName]) {
  2608. found = callback(AUDIO[groupName][label]);
  2609. if (found) {
  2610. break;
  2611. }
  2612. }
  2613. if (found) {
  2614. break;
  2615. }
  2616. }
  2617. return !!found;
  2618. };
  2619. const isAudioOnly = main => {
  2620. // we are audio only if we have no main playlists but do
  2621. // have media group playlists.
  2622. if (!main || !main.playlists || !main.playlists.length) {
  2623. // without audio variants or playlists this
  2624. // is not an audio only main.
  2625. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  2626. return found;
  2627. } // if every playlist has only an audio codec it is audio only
  2628. for (let i = 0; i < main.playlists.length; i++) {
  2629. const playlist = main.playlists[i];
  2630. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  2631. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  2632. continue;
  2633. } // playlist is in an audio group it is audio only
  2634. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  2635. if (found) {
  2636. continue;
  2637. } // if we make it here this playlist isn't audio and we
  2638. // are not audio only
  2639. return false;
  2640. } // if we make it past every playlist without returning, then
  2641. // this is an audio only playlist.
  2642. return true;
  2643. }; // exports
  2644. var Playlist = {
  2645. liveEdgeDelay,
  2646. duration,
  2647. seekable,
  2648. getMediaInfoForTime,
  2649. isEnabled,
  2650. isDisabled,
  2651. isExcluded,
  2652. isIncompatible,
  2653. playlistEnd,
  2654. isAes,
  2655. hasAttribute,
  2656. estimateSegmentRequestTime,
  2657. isLowestEnabledRendition,
  2658. isAudioOnly,
  2659. playlistMatch,
  2660. segmentDurationWithParts
  2661. };
  2662. const {
  2663. log
  2664. } = videojs__default["default"];
  2665. const createPlaylistID = (index, uri) => {
  2666. return `${index}-${uri}`;
  2667. }; // default function for creating a group id
  2668. const groupID = (type, group, label) => {
  2669. return `placeholder-uri-${type}-${group}-${label}`;
  2670. };
  2671. /**
  2672. * Parses a given m3u8 playlist
  2673. *
  2674. * @param {Function} [onwarn]
  2675. * a function to call when the parser triggers a warning event.
  2676. * @param {Function} [oninfo]
  2677. * a function to call when the parser triggers an info event.
  2678. * @param {string} manifestString
  2679. * The downloaded manifest string
  2680. * @param {Object[]} [customTagParsers]
  2681. * An array of custom tag parsers for the m3u8-parser instance
  2682. * @param {Object[]} [customTagMappers]
  2683. * An array of custom tag mappers for the m3u8-parser instance
  2684. * @param {boolean} [llhls]
  2685. * Whether to keep ll-hls features in the manifest after parsing.
  2686. * @return {Object}
  2687. * The manifest object
  2688. */
  2689. const parseManifest = ({
  2690. onwarn,
  2691. oninfo,
  2692. manifestString,
  2693. customTagParsers = [],
  2694. customTagMappers = [],
  2695. llhls
  2696. }) => {
  2697. const parser = new Parser();
  2698. if (onwarn) {
  2699. parser.on('warn', onwarn);
  2700. }
  2701. if (oninfo) {
  2702. parser.on('info', oninfo);
  2703. }
  2704. customTagParsers.forEach(customParser => parser.addParser(customParser));
  2705. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  2706. parser.push(manifestString);
  2707. parser.end();
  2708. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  2709. // if we don't want llhls support.
  2710. if (!llhls) {
  2711. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  2712. if (manifest.hasOwnProperty(k)) {
  2713. delete manifest[k];
  2714. }
  2715. });
  2716. if (manifest.segments) {
  2717. manifest.segments.forEach(function (segment) {
  2718. ['parts', 'preloadHints'].forEach(function (k) {
  2719. if (segment.hasOwnProperty(k)) {
  2720. delete segment[k];
  2721. }
  2722. });
  2723. });
  2724. }
  2725. }
  2726. if (!manifest.targetDuration) {
  2727. let targetDuration = 10;
  2728. if (manifest.segments && manifest.segments.length) {
  2729. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  2730. }
  2731. if (onwarn) {
  2732. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  2733. }
  2734. manifest.targetDuration = targetDuration;
  2735. }
  2736. const parts = getLastParts(manifest);
  2737. if (parts.length && !manifest.partTargetDuration) {
  2738. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  2739. if (onwarn) {
  2740. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  2741. log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
  2742. }
  2743. manifest.partTargetDuration = partTargetDuration;
  2744. }
  2745. return manifest;
  2746. };
  2747. /**
  2748. * Loops through all supported media groups in main and calls the provided
  2749. * callback for each group
  2750. *
  2751. * @param {Object} main
  2752. * The parsed main manifest object
  2753. * @param {Function} callback
  2754. * Callback to call for each media group
  2755. */
  2756. const forEachMediaGroup$1 = (main, callback) => {
  2757. if (!main.mediaGroups) {
  2758. return;
  2759. }
  2760. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  2761. if (!main.mediaGroups[mediaType]) {
  2762. return;
  2763. }
  2764. for (const groupKey in main.mediaGroups[mediaType]) {
  2765. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  2766. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  2767. callback(mediaProperties, mediaType, groupKey, labelKey);
  2768. }
  2769. }
  2770. });
  2771. };
  2772. /**
  2773. * Adds properties and attributes to the playlist to keep consistent functionality for
  2774. * playlists throughout VHS.
  2775. *
  2776. * @param {Object} config
  2777. * Arguments object
  2778. * @param {Object} config.playlist
  2779. * The media playlist
  2780. * @param {string} [config.uri]
  2781. * The uri to the media playlist (if media playlist is not from within a main
  2782. * playlist)
  2783. * @param {string} id
  2784. * ID to use for the playlist
  2785. */
  2786. const setupMediaPlaylist = ({
  2787. playlist,
  2788. uri,
  2789. id
  2790. }) => {
  2791. playlist.id = id;
  2792. playlist.playlistErrors_ = 0;
  2793. if (uri) {
  2794. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  2795. // playlists do not contain their own source URI, but one is needed for consistency in
  2796. // VHS.
  2797. playlist.uri = uri;
  2798. } // For HLS main playlists, even though certain attributes MUST be defined, the
  2799. // stream may still be played without them.
  2800. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  2801. // manifest.
  2802. //
  2803. // To avoid undefined reference errors through the project, and make the code easier
  2804. // to write/read, add an empty attributes object for these cases.
  2805. playlist.attributes = playlist.attributes || {};
  2806. };
  2807. /**
  2808. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  2809. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  2810. * playlist references to the playlists array.
  2811. *
  2812. * @param {Object} main
  2813. * The main playlist
  2814. */
  2815. const setupMediaPlaylists = main => {
  2816. let i = main.playlists.length;
  2817. while (i--) {
  2818. const playlist = main.playlists[i];
  2819. setupMediaPlaylist({
  2820. playlist,
  2821. id: createPlaylistID(i, playlist.uri)
  2822. });
  2823. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  2824. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  2825. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  2826. // the stream can be played without it. Although an attributes property may have been
  2827. // added to the playlist to prevent undefined references, issue a warning to fix the
  2828. // manifest.
  2829. if (!playlist.attributes.BANDWIDTH) {
  2830. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  2831. }
  2832. }
  2833. };
  2834. /**
  2835. * Adds resolvedUri properties to each media group.
  2836. *
  2837. * @param {Object} main
  2838. * The main playlist
  2839. */
  2840. const resolveMediaGroupUris = main => {
  2841. forEachMediaGroup$1(main, properties => {
  2842. if (properties.uri) {
  2843. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  2844. }
  2845. });
  2846. };
  2847. /**
  2848. * Creates a main playlist wrapper to insert a sole media playlist into.
  2849. *
  2850. * @param {Object} media
  2851. * Media playlist
  2852. * @param {string} uri
  2853. * The media URI
  2854. *
  2855. * @return {Object}
  2856. * main playlist
  2857. */
  2858. const mainForMedia = (media, uri) => {
  2859. const id = createPlaylistID(0, uri);
  2860. const main = {
  2861. mediaGroups: {
  2862. 'AUDIO': {},
  2863. 'VIDEO': {},
  2864. 'CLOSED-CAPTIONS': {},
  2865. 'SUBTITLES': {}
  2866. },
  2867. uri: window.location.href,
  2868. resolvedUri: window.location.href,
  2869. playlists: [{
  2870. uri,
  2871. id,
  2872. resolvedUri: uri,
  2873. // m3u8-parser does not attach an attributes property to media playlists so make
  2874. // sure that the property is attached to avoid undefined reference errors
  2875. attributes: {}
  2876. }]
  2877. }; // set up ID reference
  2878. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  2879. main.playlists[uri] = main.playlists[0];
  2880. return main;
  2881. };
  2882. /**
  2883. * Does an in-place update of the main manifest to add updated playlist URI references
  2884. * as well as other properties needed by VHS that aren't included by the parser.
  2885. *
  2886. * @param {Object} main
  2887. * main manifest object
  2888. * @param {string} uri
  2889. * The source URI
  2890. * @param {function} createGroupID
  2891. * A function to determine how to create the groupID for mediaGroups
  2892. */
  2893. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  2894. main.uri = uri;
  2895. for (let i = 0; i < main.playlists.length; i++) {
  2896. if (!main.playlists[i].uri) {
  2897. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  2898. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  2899. // TODO: consider adding dummy URIs in mpd-parser
  2900. const phonyUri = `placeholder-uri-${i}`;
  2901. main.playlists[i].uri = phonyUri;
  2902. }
  2903. }
  2904. const audioOnlyMain = isAudioOnly(main);
  2905. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  2906. // add a playlist array under properties
  2907. if (!properties.playlists || !properties.playlists.length) {
  2908. // If the manifest is audio only and this media group does not have a uri, check
  2909. // if the media group is located in the main list of playlists. If it is, don't add
  2910. // placeholder properties as it shouldn't be considered an alternate audio track.
  2911. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  2912. for (let i = 0; i < main.playlists.length; i++) {
  2913. const p = main.playlists[i];
  2914. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  2915. return;
  2916. }
  2917. }
  2918. }
  2919. properties.playlists = [_extends({}, properties)];
  2920. }
  2921. properties.playlists.forEach(function (p, i) {
  2922. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  2923. const id = createPlaylistID(i, groupId);
  2924. if (p.uri) {
  2925. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  2926. } else {
  2927. // DEPRECATED, this has been added to prevent a breaking change.
  2928. // previously we only ever had a single media group playlist, so
  2929. // we mark the first playlist uri without prepending the index as we used to
  2930. // ideally we would do all of the playlists the same way.
  2931. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  2932. // the placeholder again
  2933. p.resolvedUri = p.uri;
  2934. }
  2935. p.id = p.id || id; // add an empty attributes object, all playlists are
  2936. // expected to have this.
  2937. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  2938. main.playlists[p.id] = p;
  2939. main.playlists[p.uri] = p;
  2940. });
  2941. });
  2942. setupMediaPlaylists(main);
  2943. resolveMediaGroupUris(main);
  2944. };
  2945. /**
  2946. * @file playlist-loader.js
  2947. *
  2948. * A state machine that manages the loading, caching, and updating of
  2949. * M3U8 playlists.
  2950. *
  2951. */
  2952. const {
  2953. EventTarget: EventTarget$1
  2954. } = videojs__default["default"];
  2955. const addLLHLSQueryDirectives = (uri, media) => {
  2956. if (media.endList || !media.serverControl) {
  2957. return uri;
  2958. }
  2959. const parameters = {};
  2960. if (media.serverControl.canBlockReload) {
  2961. const {
  2962. preloadSegment
  2963. } = media; // next msn is a zero based value, length is not.
  2964. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  2965. // that we are going to request a part of that preload segment.
  2966. // the logic below is used to determine that.
  2967. if (preloadSegment) {
  2968. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  2969. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  2970. // length of parts, then we know we had part preload hints
  2971. // and we need to add the _HLS_part= query
  2972. if (nextPart > -1 && nextPart !== parts.length - 1) {
  2973. // add existing parts to our preload hints
  2974. // eslint-disable-next-line
  2975. parameters._HLS_part = nextPart;
  2976. } // this if statement makes sure that we request the msn
  2977. // of the preload segment if:
  2978. // 1. the preload segment had parts (and was not yet a full segment)
  2979. // but was added to our segments array
  2980. // 2. the preload segment had preload hints for parts that are not in
  2981. // the manifest yet.
  2982. // in all other cases we want the segment after the preload segment
  2983. // which will be given by using media.segments.length because it is 1 based
  2984. // rather than 0 based.
  2985. if (nextPart > -1 || parts.length) {
  2986. nextMSN--;
  2987. }
  2988. } // add _HLS_msn= in front of any _HLS_part query
  2989. // eslint-disable-next-line
  2990. parameters._HLS_msn = nextMSN;
  2991. }
  2992. if (media.serverControl && media.serverControl.canSkipUntil) {
  2993. // add _HLS_skip= infront of all other queries.
  2994. // eslint-disable-next-line
  2995. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  2996. }
  2997. if (Object.keys(parameters).length) {
  2998. const parsedUri = new window.URL(uri);
  2999. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  3000. if (!parameters.hasOwnProperty(name)) {
  3001. return;
  3002. }
  3003. parsedUri.searchParams.set(name, parameters[name]);
  3004. });
  3005. uri = parsedUri.toString();
  3006. }
  3007. return uri;
  3008. };
  3009. /**
  3010. * Returns a new segment object with properties and
  3011. * the parts array merged.
  3012. *
  3013. * @param {Object} a the old segment
  3014. * @param {Object} b the new segment
  3015. *
  3016. * @return {Object} the merged segment
  3017. */
  3018. const updateSegment = (a, b) => {
  3019. if (!a) {
  3020. return b;
  3021. }
  3022. const result = merge$1(a, b); // if only the old segment has preload hints
  3023. // and the new one does not, remove preload hints.
  3024. if (a.preloadHints && !b.preloadHints) {
  3025. delete result.preloadHints;
  3026. } // if only the old segment has parts
  3027. // then the parts are no longer valid
  3028. if (a.parts && !b.parts) {
  3029. delete result.parts; // if both segments have parts
  3030. // copy part propeties from the old segment
  3031. // to the new one.
  3032. } else if (a.parts && b.parts) {
  3033. for (let i = 0; i < b.parts.length; i++) {
  3034. if (a.parts && a.parts[i]) {
  3035. result.parts[i] = merge$1(a.parts[i], b.parts[i]);
  3036. }
  3037. }
  3038. } // set skipped to false for segments that have
  3039. // have had information merged from the old segment.
  3040. if (!a.skipped && b.skipped) {
  3041. result.skipped = false;
  3042. } // set preload to false for segments that have
  3043. // had information added in the new segment.
  3044. if (a.preload && !b.preload) {
  3045. result.preload = false;
  3046. }
  3047. return result;
  3048. };
  3049. /**
  3050. * Returns a new array of segments that is the result of merging
  3051. * properties from an older list of segments onto an updated
  3052. * list. No properties on the updated playlist will be ovewritten.
  3053. *
  3054. * @param {Array} original the outdated list of segments
  3055. * @param {Array} update the updated list of segments
  3056. * @param {number=} offset the index of the first update
  3057. * segment in the original segment list. For non-live playlists,
  3058. * this should always be zero and does not need to be
  3059. * specified. For live playlists, it should be the difference
  3060. * between the media sequence numbers in the original and updated
  3061. * playlists.
  3062. * @return {Array} a list of merged segment objects
  3063. */
  3064. const updateSegments = (original, update, offset) => {
  3065. const oldSegments = original.slice();
  3066. const newSegments = update.slice();
  3067. offset = offset || 0;
  3068. const result = [];
  3069. let currentMap;
  3070. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  3071. const oldSegment = oldSegments[newIndex + offset];
  3072. const newSegment = newSegments[newIndex];
  3073. if (oldSegment) {
  3074. currentMap = oldSegment.map || currentMap;
  3075. result.push(updateSegment(oldSegment, newSegment));
  3076. } else {
  3077. // carry over map to new segment if it is missing
  3078. if (currentMap && !newSegment.map) {
  3079. newSegment.map = currentMap;
  3080. }
  3081. result.push(newSegment);
  3082. }
  3083. }
  3084. return result;
  3085. };
  3086. const resolveSegmentUris = (segment, baseUri) => {
  3087. // preloadSegment will not have a uri at all
  3088. // as the segment isn't actually in the manifest yet, only parts
  3089. if (!segment.resolvedUri && segment.uri) {
  3090. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  3091. }
  3092. if (segment.key && !segment.key.resolvedUri) {
  3093. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  3094. }
  3095. if (segment.map && !segment.map.resolvedUri) {
  3096. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  3097. }
  3098. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  3099. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  3100. }
  3101. if (segment.parts && segment.parts.length) {
  3102. segment.parts.forEach(p => {
  3103. if (p.resolvedUri) {
  3104. return;
  3105. }
  3106. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3107. });
  3108. }
  3109. if (segment.preloadHints && segment.preloadHints.length) {
  3110. segment.preloadHints.forEach(p => {
  3111. if (p.resolvedUri) {
  3112. return;
  3113. }
  3114. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3115. });
  3116. }
  3117. };
  3118. const getAllSegments = function (media) {
  3119. const segments = media.segments || [];
  3120. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  3121. // a usable segment, only include a preloadSegment that has
  3122. // parts.
  3123. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  3124. // if preloadHints has a MAP that means that the
  3125. // init segment is going to change. We cannot use any of the parts
  3126. // from this preload segment.
  3127. if (preloadSegment.preloadHints) {
  3128. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  3129. if (preloadSegment.preloadHints[i].type === 'MAP') {
  3130. return segments;
  3131. }
  3132. }
  3133. } // set the duration for our preload segment to target duration.
  3134. preloadSegment.duration = media.targetDuration;
  3135. preloadSegment.preload = true;
  3136. segments.push(preloadSegment);
  3137. }
  3138. return segments;
  3139. }; // consider the playlist unchanged if the playlist object is the same or
  3140. // the number of segments is equal, the media sequence number is unchanged,
  3141. // and this playlist hasn't become the end of the playlist
  3142. const isPlaylistUnchanged = (a, b) => a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
  3143. /**
  3144. * Returns a new main playlist that is the result of merging an
  3145. * updated media playlist into the original version. If the
  3146. * updated media playlist does not match any of the playlist
  3147. * entries in the original main playlist, null is returned.
  3148. *
  3149. * @param {Object} main a parsed main M3U8 object
  3150. * @param {Object} media a parsed media M3U8 object
  3151. * @return {Object} a new object that represents the original
  3152. * main playlist with the updated media playlist merged in, or
  3153. * null if the merge produced no change.
  3154. */
  3155. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  3156. const result = merge$1(main, {});
  3157. const oldMedia = result.playlists[newMedia.id];
  3158. if (!oldMedia) {
  3159. return null;
  3160. }
  3161. if (unchangedCheck(oldMedia, newMedia)) {
  3162. return null;
  3163. }
  3164. newMedia.segments = getAllSegments(newMedia);
  3165. const mergedPlaylist = merge$1(oldMedia, newMedia); // always use the new media's preload segment
  3166. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  3167. delete mergedPlaylist.preloadSegment;
  3168. } // if the update could overlap existing segment information, merge the two segment lists
  3169. if (oldMedia.segments) {
  3170. if (newMedia.skip) {
  3171. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  3172. // old properties into the new segments
  3173. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  3174. newMedia.segments.unshift({
  3175. skipped: true
  3176. });
  3177. }
  3178. }
  3179. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  3180. } // resolve any segment URIs to prevent us from having to do it later
  3181. mergedPlaylist.segments.forEach(segment => {
  3182. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  3183. }); // TODO Right now in the playlists array there are two references to each playlist, one
  3184. // that is referenced by index, and one by URI. The index reference may no longer be
  3185. // necessary.
  3186. for (let i = 0; i < result.playlists.length; i++) {
  3187. if (result.playlists[i].id === newMedia.id) {
  3188. result.playlists[i] = mergedPlaylist;
  3189. }
  3190. }
  3191. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  3192. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  3193. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  3194. if (!properties.playlists) {
  3195. return;
  3196. }
  3197. for (let i = 0; i < properties.playlists.length; i++) {
  3198. if (newMedia.id === properties.playlists[i].id) {
  3199. properties.playlists[i] = mergedPlaylist;
  3200. }
  3201. }
  3202. });
  3203. return result;
  3204. };
  3205. /**
  3206. * Calculates the time to wait before refreshing a live playlist
  3207. *
  3208. * @param {Object} media
  3209. * The current media
  3210. * @param {boolean} update
  3211. * True if there were any updates from the last refresh, false otherwise
  3212. * @return {number}
  3213. * The time in ms to wait before refreshing the live playlist
  3214. */
  3215. const refreshDelay = (media, update) => {
  3216. const segments = media.segments || [];
  3217. const lastSegment = segments[segments.length - 1];
  3218. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  3219. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  3220. if (update && lastDuration) {
  3221. return lastDuration * 1000;
  3222. } // if the playlist is unchanged since the last reload or last segment duration
  3223. // cannot be determined, try again after half the target duration
  3224. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  3225. };
  3226. /**
  3227. * Load a playlist from a remote location
  3228. *
  3229. * @class PlaylistLoader
  3230. * @extends Stream
  3231. * @param {string|Object} src url or object of manifest
  3232. * @param {boolean} withCredentials the withCredentials xhr option
  3233. * @class
  3234. */
  3235. class PlaylistLoader extends EventTarget$1 {
  3236. constructor(src, vhs, options = {}) {
  3237. super();
  3238. if (!src) {
  3239. throw new Error('A non-empty playlist URL or object is required');
  3240. }
  3241. this.logger_ = logger('PlaylistLoader');
  3242. const {
  3243. withCredentials = false
  3244. } = options;
  3245. this.src = src;
  3246. this.vhs_ = vhs;
  3247. this.withCredentials = withCredentials;
  3248. const vhsOptions = vhs.options_;
  3249. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  3250. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  3251. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  3252. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  3253. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  3254. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  3255. }
  3256. handleMediaupdatetimeout_() {
  3257. if (this.state !== 'HAVE_METADATA') {
  3258. // only refresh the media playlist if no other activity is going on
  3259. return;
  3260. }
  3261. const media = this.media();
  3262. let uri = resolveUrl(this.main.uri, media.uri);
  3263. if (this.llhls) {
  3264. uri = addLLHLSQueryDirectives(uri, media);
  3265. }
  3266. this.state = 'HAVE_CURRENT_METADATA';
  3267. this.request = this.vhs_.xhr({
  3268. uri,
  3269. withCredentials: this.withCredentials
  3270. }, (error, req) => {
  3271. // disposed
  3272. if (!this.request) {
  3273. return;
  3274. }
  3275. if (error) {
  3276. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  3277. }
  3278. this.haveMetadata({
  3279. playlistString: this.request.responseText,
  3280. url: this.media().uri,
  3281. id: this.media().id
  3282. });
  3283. });
  3284. }
  3285. playlistRequestError(xhr, playlist, startingState) {
  3286. const {
  3287. uri,
  3288. id
  3289. } = playlist; // any in-flight request is now finished
  3290. this.request = null;
  3291. if (startingState) {
  3292. this.state = startingState;
  3293. }
  3294. this.error = {
  3295. playlist: this.main.playlists[id],
  3296. status: xhr.status,
  3297. message: `HLS playlist request error at URL: ${uri}.`,
  3298. responseText: xhr.responseText,
  3299. code: xhr.status >= 500 ? 4 : 2
  3300. };
  3301. this.trigger('error');
  3302. }
  3303. parseManifest_({
  3304. url,
  3305. manifestString
  3306. }) {
  3307. return parseManifest({
  3308. onwarn: ({
  3309. message
  3310. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  3311. oninfo: ({
  3312. message
  3313. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  3314. manifestString,
  3315. customTagParsers: this.customTagParsers,
  3316. customTagMappers: this.customTagMappers,
  3317. llhls: this.llhls
  3318. });
  3319. }
  3320. /**
  3321. * Update the playlist loader's state in response to a new or updated playlist.
  3322. *
  3323. * @param {string} [playlistString]
  3324. * Playlist string (if playlistObject is not provided)
  3325. * @param {Object} [playlistObject]
  3326. * Playlist object (if playlistString is not provided)
  3327. * @param {string} url
  3328. * URL of playlist
  3329. * @param {string} id
  3330. * ID to use for playlist
  3331. */
  3332. haveMetadata({
  3333. playlistString,
  3334. playlistObject,
  3335. url,
  3336. id
  3337. }) {
  3338. // any in-flight request is now finished
  3339. this.request = null;
  3340. this.state = 'HAVE_METADATA';
  3341. const playlist = playlistObject || this.parseManifest_({
  3342. url,
  3343. manifestString: playlistString
  3344. });
  3345. playlist.lastRequest = Date.now();
  3346. setupMediaPlaylist({
  3347. playlist,
  3348. uri: url,
  3349. id
  3350. }); // merge this playlist into the main manifest
  3351. const update = updateMain$1(this.main, playlist);
  3352. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  3353. this.pendingMedia_ = null;
  3354. if (update) {
  3355. this.main = update;
  3356. this.media_ = this.main.playlists[id];
  3357. } else {
  3358. this.trigger('playlistunchanged');
  3359. }
  3360. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  3361. this.trigger('loadedplaylist');
  3362. }
  3363. /**
  3364. * Abort any outstanding work and clean up.
  3365. */
  3366. dispose() {
  3367. this.trigger('dispose');
  3368. this.stopRequest();
  3369. window.clearTimeout(this.mediaUpdateTimeout);
  3370. window.clearTimeout(this.finalRenditionTimeout);
  3371. this.off();
  3372. }
  3373. stopRequest() {
  3374. if (this.request) {
  3375. const oldRequest = this.request;
  3376. this.request = null;
  3377. oldRequest.onreadystatechange = null;
  3378. oldRequest.abort();
  3379. }
  3380. }
  3381. /**
  3382. * When called without any arguments, returns the currently
  3383. * active media playlist. When called with a single argument,
  3384. * triggers the playlist loader to asynchronously switch to the
  3385. * specified media playlist. Calling this method while the
  3386. * loader is in the HAVE_NOTHING causes an error to be emitted
  3387. * but otherwise has no effect.
  3388. *
  3389. * @param {Object=} playlist the parsed media playlist
  3390. * object to switch to
  3391. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  3392. *
  3393. * @return {Playlist} the current loaded media
  3394. */
  3395. media(playlist, shouldDelay) {
  3396. // getter
  3397. if (!playlist) {
  3398. return this.media_;
  3399. } // setter
  3400. if (this.state === 'HAVE_NOTHING') {
  3401. throw new Error('Cannot switch media playlist from ' + this.state);
  3402. } // find the playlist object if the target playlist has been
  3403. // specified by URI
  3404. if (typeof playlist === 'string') {
  3405. if (!this.main.playlists[playlist]) {
  3406. throw new Error('Unknown playlist URI: ' + playlist);
  3407. }
  3408. playlist = this.main.playlists[playlist];
  3409. }
  3410. window.clearTimeout(this.finalRenditionTimeout);
  3411. if (shouldDelay) {
  3412. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  3413. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  3414. return;
  3415. }
  3416. const startingState = this.state;
  3417. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  3418. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  3419. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  3420. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  3421. playlist.endList && playlist.segments.length) {
  3422. // abort outstanding playlist requests
  3423. if (this.request) {
  3424. this.request.onreadystatechange = null;
  3425. this.request.abort();
  3426. this.request = null;
  3427. }
  3428. this.state = 'HAVE_METADATA';
  3429. this.media_ = playlist; // trigger media change if the active media has been updated
  3430. if (mediaChange) {
  3431. this.trigger('mediachanging');
  3432. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3433. // The initial playlist was a main manifest, and the first media selected was
  3434. // also provided (in the form of a resolved playlist object) as part of the
  3435. // source object (rather than just a URL). Therefore, since the media playlist
  3436. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  3437. // normal flow, and needs an explicit trigger here.
  3438. this.trigger('loadedmetadata');
  3439. } else {
  3440. this.trigger('mediachange');
  3441. }
  3442. }
  3443. return;
  3444. } // We update/set the timeout here so that live playlists
  3445. // that are not a media change will "start" the loader as expected.
  3446. // We expect that this function will start the media update timeout
  3447. // cycle again. This also prevents a playlist switch failure from
  3448. // causing us to stall during live.
  3449. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  3450. if (!mediaChange) {
  3451. return;
  3452. }
  3453. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  3454. if (this.request) {
  3455. if (playlist.resolvedUri === this.request.url) {
  3456. // requesting to switch to the same playlist multiple times
  3457. // has no effect after the first
  3458. return;
  3459. }
  3460. this.request.onreadystatechange = null;
  3461. this.request.abort();
  3462. this.request = null;
  3463. } // request the new playlist
  3464. if (this.media_) {
  3465. this.trigger('mediachanging');
  3466. }
  3467. this.pendingMedia_ = playlist;
  3468. this.request = this.vhs_.xhr({
  3469. uri: playlist.resolvedUri,
  3470. withCredentials: this.withCredentials
  3471. }, (error, req) => {
  3472. // disposed
  3473. if (!this.request) {
  3474. return;
  3475. }
  3476. playlist.lastRequest = Date.now();
  3477. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  3478. if (error) {
  3479. return this.playlistRequestError(this.request, playlist, startingState);
  3480. }
  3481. this.haveMetadata({
  3482. playlistString: req.responseText,
  3483. url: playlist.uri,
  3484. id: playlist.id
  3485. }); // fire loadedmetadata the first time a media playlist is loaded
  3486. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3487. this.trigger('loadedmetadata');
  3488. } else {
  3489. this.trigger('mediachange');
  3490. }
  3491. });
  3492. }
  3493. /**
  3494. * pause loading of the playlist
  3495. */
  3496. pause() {
  3497. if (this.mediaUpdateTimeout) {
  3498. window.clearTimeout(this.mediaUpdateTimeout);
  3499. this.mediaUpdateTimeout = null;
  3500. }
  3501. this.stopRequest();
  3502. if (this.state === 'HAVE_NOTHING') {
  3503. // If we pause the loader before any data has been retrieved, its as if we never
  3504. // started, so reset to an unstarted state.
  3505. this.started = false;
  3506. } // Need to restore state now that no activity is happening
  3507. if (this.state === 'SWITCHING_MEDIA') {
  3508. // if the loader was in the process of switching media, it should either return to
  3509. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  3510. // playlist yet. This is determined by the existence of loader.media_
  3511. if (this.media_) {
  3512. this.state = 'HAVE_METADATA';
  3513. } else {
  3514. this.state = 'HAVE_MAIN_MANIFEST';
  3515. }
  3516. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  3517. this.state = 'HAVE_METADATA';
  3518. }
  3519. }
  3520. /**
  3521. * start loading of the playlist
  3522. */
  3523. load(shouldDelay) {
  3524. if (this.mediaUpdateTimeout) {
  3525. window.clearTimeout(this.mediaUpdateTimeout);
  3526. this.mediaUpdateTimeout = null;
  3527. }
  3528. const media = this.media();
  3529. if (shouldDelay) {
  3530. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  3531. this.mediaUpdateTimeout = window.setTimeout(() => {
  3532. this.mediaUpdateTimeout = null;
  3533. this.load();
  3534. }, delay);
  3535. return;
  3536. }
  3537. if (!this.started) {
  3538. this.start();
  3539. return;
  3540. }
  3541. if (media && !media.endList) {
  3542. this.trigger('mediaupdatetimeout');
  3543. } else {
  3544. this.trigger('loadedplaylist');
  3545. }
  3546. }
  3547. updateMediaUpdateTimeout_(delay) {
  3548. if (this.mediaUpdateTimeout) {
  3549. window.clearTimeout(this.mediaUpdateTimeout);
  3550. this.mediaUpdateTimeout = null;
  3551. } // we only have use mediaupdatetimeout for live playlists.
  3552. if (!this.media() || this.media().endList) {
  3553. return;
  3554. }
  3555. this.mediaUpdateTimeout = window.setTimeout(() => {
  3556. this.mediaUpdateTimeout = null;
  3557. this.trigger('mediaupdatetimeout');
  3558. this.updateMediaUpdateTimeout_(delay);
  3559. }, delay);
  3560. }
  3561. /**
  3562. * start loading of the playlist
  3563. */
  3564. start() {
  3565. this.started = true;
  3566. if (typeof this.src === 'object') {
  3567. // in the case of an entirely constructed manifest object (meaning there's no actual
  3568. // manifest on a server), default the uri to the page's href
  3569. if (!this.src.uri) {
  3570. this.src.uri = window.location.href;
  3571. } // resolvedUri is added on internally after the initial request. Since there's no
  3572. // request for pre-resolved manifests, add on resolvedUri here.
  3573. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  3574. // request can be skipped (since the top level of the manifest, at a minimum, is
  3575. // already available as a parsed manifest object). However, if the manifest object
  3576. // represents a main playlist, some media playlists may need to be resolved before
  3577. // the starting segment list is available. Therefore, go directly to setup of the
  3578. // initial playlist, and let the normal flow continue from there.
  3579. //
  3580. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  3581. // that the first request is asynchronous.
  3582. setTimeout(() => {
  3583. this.setupInitialPlaylist(this.src);
  3584. }, 0);
  3585. return;
  3586. } // request the specified URL
  3587. this.request = this.vhs_.xhr({
  3588. uri: this.src,
  3589. withCredentials: this.withCredentials
  3590. }, (error, req) => {
  3591. // disposed
  3592. if (!this.request) {
  3593. return;
  3594. } // clear the loader's request reference
  3595. this.request = null;
  3596. if (error) {
  3597. this.error = {
  3598. status: req.status,
  3599. message: `HLS playlist request error at URL: ${this.src}.`,
  3600. responseText: req.responseText,
  3601. // MEDIA_ERR_NETWORK
  3602. code: 2
  3603. };
  3604. if (this.state === 'HAVE_NOTHING') {
  3605. this.started = false;
  3606. }
  3607. return this.trigger('error');
  3608. }
  3609. this.src = resolveManifestRedirect(this.src, req);
  3610. const manifest = this.parseManifest_({
  3611. manifestString: req.responseText,
  3612. url: this.src
  3613. });
  3614. this.setupInitialPlaylist(manifest);
  3615. });
  3616. }
  3617. srcUri() {
  3618. return typeof this.src === 'string' ? this.src : this.src.uri;
  3619. }
  3620. /**
  3621. * Given a manifest object that's either a main or media playlist, trigger the proper
  3622. * events and set the state of the playlist loader.
  3623. *
  3624. * If the manifest object represents a main playlist, `loadedplaylist` will be
  3625. * triggered to allow listeners to select a playlist. If none is selected, the loader
  3626. * will default to the first one in the playlists array.
  3627. *
  3628. * If the manifest object represents a media playlist, `loadedplaylist` will be
  3629. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  3630. *
  3631. * In the case of a media playlist, a main playlist object wrapper with one playlist
  3632. * will be created so that all logic can handle playlists in the same fashion (as an
  3633. * assumed manifest object schema).
  3634. *
  3635. * @param {Object} manifest
  3636. * The parsed manifest object
  3637. */
  3638. setupInitialPlaylist(manifest) {
  3639. this.state = 'HAVE_MAIN_MANIFEST';
  3640. if (manifest.playlists) {
  3641. this.main = manifest;
  3642. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  3643. // then resolve URIs in advance, as they are usually done after a playlist request,
  3644. // which may not happen if the playlist is resolved.
  3645. manifest.playlists.forEach(playlist => {
  3646. playlist.segments = getAllSegments(playlist);
  3647. playlist.segments.forEach(segment => {
  3648. resolveSegmentUris(segment, playlist.resolvedUri);
  3649. });
  3650. });
  3651. this.trigger('loadedplaylist');
  3652. if (!this.request) {
  3653. // no media playlist was specifically selected so start
  3654. // from the first listed one
  3655. this.media(this.main.playlists[0]);
  3656. }
  3657. return;
  3658. } // In order to support media playlists passed in as vhs-json, the case where the uri
  3659. // is not provided as part of the manifest should be considered, and an appropriate
  3660. // default used.
  3661. const uri = this.srcUri() || window.location.href;
  3662. this.main = mainForMedia(manifest, uri);
  3663. this.haveMetadata({
  3664. playlistObject: manifest,
  3665. url: uri,
  3666. id: this.main.playlists[0].id
  3667. });
  3668. this.trigger('loadedmetadata');
  3669. }
  3670. }
  3671. /**
  3672. * @file xhr.js
  3673. */
  3674. const {
  3675. xhr: videojsXHR
  3676. } = videojs__default["default"];
  3677. const callbackWrapper = function (request, error, response, callback) {
  3678. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  3679. if (!error && reqResponse) {
  3680. request.responseTime = Date.now();
  3681. request.roundTripTime = request.responseTime - request.requestTime;
  3682. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  3683. if (!request.bandwidth) {
  3684. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  3685. }
  3686. }
  3687. if (response.headers) {
  3688. request.responseHeaders = response.headers;
  3689. } // videojs.xhr now uses a specific code on the error
  3690. // object to signal that a request has timed out instead
  3691. // of setting a boolean on the request object
  3692. if (error && error.code === 'ETIMEDOUT') {
  3693. request.timedout = true;
  3694. } // videojs.xhr no longer considers status codes outside of 200 and 0
  3695. // (for file uris) to be errors, but the old XHR did, so emulate that
  3696. // behavior. Status 206 may be used in response to byterange requests.
  3697. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  3698. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  3699. }
  3700. callback(error, request);
  3701. };
  3702. const xhrFactory = function () {
  3703. const xhr = function XhrFunction(options, callback) {
  3704. // Add a default timeout
  3705. options = merge$1({
  3706. timeout: 45e3
  3707. }, options); // Allow an optional user-specified function to modify the option
  3708. // object before we construct the xhr request
  3709. const beforeRequest = XhrFunction.beforeRequest || videojs__default["default"].Vhs.xhr.beforeRequest;
  3710. if (beforeRequest && typeof beforeRequest === 'function') {
  3711. const newOptions = beforeRequest(options);
  3712. if (newOptions) {
  3713. options = newOptions;
  3714. }
  3715. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  3716. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  3717. const xhrMethod = videojs__default["default"].Vhs.xhr.original === true ? videojsXHR : videojs__default["default"].Vhs.xhr;
  3718. const request = xhrMethod(options, function (error, response) {
  3719. return callbackWrapper(request, error, response, callback);
  3720. });
  3721. const originalAbort = request.abort;
  3722. request.abort = function () {
  3723. request.aborted = true;
  3724. return originalAbort.apply(request, arguments);
  3725. };
  3726. request.uri = options.uri;
  3727. request.requestTime = Date.now();
  3728. return request;
  3729. };
  3730. xhr.original = true;
  3731. return xhr;
  3732. };
  3733. /**
  3734. * Turns segment byterange into a string suitable for use in
  3735. * HTTP Range requests
  3736. *
  3737. * @param {Object} byterange - an object with two values defining the start and end
  3738. * of a byte-range
  3739. */
  3740. const byterangeStr = function (byterange) {
  3741. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  3742. // header uses inclusive ranges
  3743. let byterangeEnd;
  3744. const byterangeStart = byterange.offset;
  3745. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  3746. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  3747. } else {
  3748. byterangeEnd = byterange.offset + byterange.length - 1;
  3749. }
  3750. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  3751. };
  3752. /**
  3753. * Defines headers for use in the xhr request for a particular segment.
  3754. *
  3755. * @param {Object} segment - a simplified copy of the segmentInfo object
  3756. * from SegmentLoader
  3757. */
  3758. const segmentXhrHeaders = function (segment) {
  3759. const headers = {};
  3760. if (segment.byterange) {
  3761. headers.Range = byterangeStr(segment.byterange);
  3762. }
  3763. return headers;
  3764. };
  3765. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  3766. var DASH_REGEX = /^application\/dash\+xml/i;
  3767. /**
  3768. * Returns a string that describes the type of source based on a video source object's
  3769. * media type.
  3770. *
  3771. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  3772. *
  3773. * @param {string} type
  3774. * Video source object media type
  3775. * @return {('hls'|'dash'|'vhs-json'|null)}
  3776. * VHS source type string
  3777. */
  3778. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  3779. if (MPEGURL_REGEX.test(type)) {
  3780. return 'hls';
  3781. }
  3782. if (DASH_REGEX.test(type)) {
  3783. return 'dash';
  3784. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  3785. // source URL.
  3786. //
  3787. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  3788. //
  3789. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  3790. // project, and the +json suffix identifies the structure of the media type.
  3791. if (type === 'application/vnd.videojs.vhs+json') {
  3792. return 'vhs-json';
  3793. }
  3794. return null;
  3795. };
  3796. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  3797. // we used to do this with log2 but BigInt does not support builtin math
  3798. // Math.ceil(log2(x));
  3799. var countBits = function countBits(x) {
  3800. return x.toString(2).length;
  3801. }; // count the number of whole bytes it would take to represent a number
  3802. var countBytes = function countBytes(x) {
  3803. return Math.ceil(countBits(x) / 8);
  3804. };
  3805. var isArrayBufferView = function isArrayBufferView(obj) {
  3806. if (ArrayBuffer.isView === 'function') {
  3807. return ArrayBuffer.isView(obj);
  3808. }
  3809. return obj && obj.buffer instanceof ArrayBuffer;
  3810. };
  3811. var isTypedArray = function isTypedArray(obj) {
  3812. return isArrayBufferView(obj);
  3813. };
  3814. var toUint8 = function toUint8(bytes) {
  3815. if (bytes instanceof Uint8Array) {
  3816. return bytes;
  3817. }
  3818. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  3819. // any non-number or NaN leads to empty uint8array
  3820. // eslint-disable-next-line
  3821. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  3822. bytes = 0;
  3823. } else {
  3824. bytes = [bytes];
  3825. }
  3826. }
  3827. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  3828. };
  3829. var BigInt = window.BigInt || Number;
  3830. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  3831. (function () {
  3832. var a = new Uint16Array([0xFFCC]);
  3833. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  3834. if (b[0] === 0xFF) {
  3835. return 'big';
  3836. }
  3837. if (b[0] === 0xCC) {
  3838. return 'little';
  3839. }
  3840. return 'unknown';
  3841. })();
  3842. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  3843. var _ref = _temp === void 0 ? {} : _temp,
  3844. _ref$signed = _ref.signed,
  3845. signed = _ref$signed === void 0 ? false : _ref$signed,
  3846. _ref$le = _ref.le,
  3847. le = _ref$le === void 0 ? false : _ref$le;
  3848. bytes = toUint8(bytes);
  3849. var fn = le ? 'reduce' : 'reduceRight';
  3850. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  3851. var number = obj.call(bytes, function (total, byte, i) {
  3852. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  3853. return total + BigInt(byte) * BYTE_TABLE[exponent];
  3854. }, BigInt(0));
  3855. if (signed) {
  3856. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  3857. number = BigInt(number);
  3858. if (number > max) {
  3859. number -= max;
  3860. number -= max;
  3861. number -= BigInt(2);
  3862. }
  3863. }
  3864. return Number(number);
  3865. };
  3866. var numberToBytes = function numberToBytes(number, _temp2) {
  3867. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  3868. _ref2$le = _ref2.le,
  3869. le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
  3870. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  3871. number = 0;
  3872. }
  3873. number = BigInt(number);
  3874. var byteCount = countBytes(number);
  3875. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  3876. for (var i = 0; i < byteCount; i++) {
  3877. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  3878. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  3879. if (number < 0) {
  3880. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  3881. bytes[byteIndex] -= i === 0 ? 1 : 2;
  3882. }
  3883. }
  3884. return bytes;
  3885. };
  3886. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  3887. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  3888. string = string.toString();
  3889. }
  3890. if (typeof string !== 'string') {
  3891. return new Uint8Array();
  3892. } // If the string already is bytes, we don't have to do this
  3893. // otherwise we do this so that we split multi length characters
  3894. // into individual bytes
  3895. if (!stringIsBytes) {
  3896. string = unescape(encodeURIComponent(string));
  3897. }
  3898. var view = new Uint8Array(string.length);
  3899. for (var i = 0; i < string.length; i++) {
  3900. view[i] = string.charCodeAt(i);
  3901. }
  3902. return view;
  3903. };
  3904. var concatTypedArrays = function concatTypedArrays() {
  3905. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  3906. buffers[_key] = arguments[_key];
  3907. }
  3908. buffers = buffers.filter(function (b) {
  3909. return b && (b.byteLength || b.length) && typeof b !== 'string';
  3910. });
  3911. if (buffers.length <= 1) {
  3912. // for 0 length we will return empty uint8
  3913. // for 1 length we return the first uint8
  3914. return toUint8(buffers[0]);
  3915. }
  3916. var totalLen = buffers.reduce(function (total, buf, i) {
  3917. return total + (buf.byteLength || buf.length);
  3918. }, 0);
  3919. var tempBuffer = new Uint8Array(totalLen);
  3920. var offset = 0;
  3921. buffers.forEach(function (buf) {
  3922. buf = toUint8(buf);
  3923. tempBuffer.set(buf, offset);
  3924. offset += buf.byteLength;
  3925. });
  3926. return tempBuffer;
  3927. };
  3928. /**
  3929. * Check if the bytes "b" are contained within bytes "a".
  3930. *
  3931. * @param {Uint8Array|Array} a
  3932. * Bytes to check in
  3933. *
  3934. * @param {Uint8Array|Array} b
  3935. * Bytes to check for
  3936. *
  3937. * @param {Object} options
  3938. * options
  3939. *
  3940. * @param {Array|Uint8Array} [offset=0]
  3941. * offset to use when looking at bytes in a
  3942. *
  3943. * @param {Array|Uint8Array} [mask=[]]
  3944. * mask to use on bytes before comparison.
  3945. *
  3946. * @return {boolean}
  3947. * If all bytes in b are inside of a, taking into account
  3948. * bit masks.
  3949. */
  3950. var bytesMatch = function bytesMatch(a, b, _temp3) {
  3951. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  3952. _ref3$offset = _ref3.offset,
  3953. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  3954. _ref3$mask = _ref3.mask,
  3955. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  3956. a = toUint8(a);
  3957. b = toUint8(b); // ie 11 does not support uint8 every
  3958. var fn = b.every ? b.every : Array.prototype.every;
  3959. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  3960. fn.call(b, function (bByte, i) {
  3961. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  3962. return bByte === aByte;
  3963. });
  3964. };
  3965. /**
  3966. * @file bin-utils.js
  3967. */
  3968. /**
  3969. * convert a TimeRange to text
  3970. *
  3971. * @param {TimeRange} range the timerange to use for conversion
  3972. * @param {number} i the iterator on the range to convert
  3973. * @return {string} the range in string format
  3974. */
  3975. const textRange = function (range, i) {
  3976. return range.start(i) + '-' + range.end(i);
  3977. };
  3978. /**
  3979. * format a number as hex string
  3980. *
  3981. * @param {number} e The number
  3982. * @param {number} i the iterator
  3983. * @return {string} the hex formatted number as a string
  3984. */
  3985. const formatHexString = function (e, i) {
  3986. const value = e.toString(16);
  3987. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  3988. };
  3989. const formatAsciiString = function (e) {
  3990. if (e >= 0x20 && e < 0x7e) {
  3991. return String.fromCharCode(e);
  3992. }
  3993. return '.';
  3994. };
  3995. /**
  3996. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  3997. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  3998. *
  3999. * @param {Object} message
  4000. * Object of properties and values to send to the web worker
  4001. * @return {Object}
  4002. * Modified message with TypedArray values expanded
  4003. * @function createTransferableMessage
  4004. */
  4005. const createTransferableMessage = function (message) {
  4006. const transferable = {};
  4007. Object.keys(message).forEach(key => {
  4008. const value = message[key];
  4009. if (isArrayBufferView(value)) {
  4010. transferable[key] = {
  4011. bytes: value.buffer,
  4012. byteOffset: value.byteOffset,
  4013. byteLength: value.byteLength
  4014. };
  4015. } else {
  4016. transferable[key] = value;
  4017. }
  4018. });
  4019. return transferable;
  4020. };
  4021. /**
  4022. * Returns a unique string identifier for a media initialization
  4023. * segment.
  4024. *
  4025. * @param {Object} initSegment
  4026. * the init segment object.
  4027. *
  4028. * @return {string} the generated init segment id
  4029. */
  4030. const initSegmentId = function (initSegment) {
  4031. const byterange = initSegment.byterange || {
  4032. length: Infinity,
  4033. offset: 0
  4034. };
  4035. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  4036. };
  4037. /**
  4038. * Returns a unique string identifier for a media segment key.
  4039. *
  4040. * @param {Object} key the encryption key
  4041. * @return {string} the unique id for the media segment key.
  4042. */
  4043. const segmentKeyId = function (key) {
  4044. return key.resolvedUri;
  4045. };
  4046. /**
  4047. * utils to help dump binary data to the console
  4048. *
  4049. * @param {Array|TypedArray} data
  4050. * data to dump to a string
  4051. *
  4052. * @return {string} the data as a hex string.
  4053. */
  4054. const hexDump = data => {
  4055. const bytes = Array.prototype.slice.call(data);
  4056. const step = 16;
  4057. let result = '';
  4058. let hex;
  4059. let ascii;
  4060. for (let j = 0; j < bytes.length / step; j++) {
  4061. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  4062. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  4063. result += hex + ' ' + ascii + '\n';
  4064. }
  4065. return result;
  4066. };
  4067. const tagDump = ({
  4068. bytes
  4069. }) => hexDump(bytes);
  4070. const textRanges = ranges => {
  4071. let result = '';
  4072. let i;
  4073. for (i = 0; i < ranges.length; i++) {
  4074. result += textRange(ranges, i) + ' ';
  4075. }
  4076. return result;
  4077. };
  4078. var utils = /*#__PURE__*/Object.freeze({
  4079. __proto__: null,
  4080. createTransferableMessage: createTransferableMessage,
  4081. initSegmentId: initSegmentId,
  4082. segmentKeyId: segmentKeyId,
  4083. hexDump: hexDump,
  4084. tagDump: tagDump,
  4085. textRanges: textRanges
  4086. });
  4087. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  4088. // 25% was arbitrarily chosen, and may need to be refined over time.
  4089. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  4090. /**
  4091. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  4092. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  4093. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  4094. *
  4095. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  4096. * point" (a point where we have a mapping from program time to player time, with player
  4097. * time being the post transmux start of the segment).
  4098. *
  4099. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  4100. *
  4101. * @param {number} playerTime the player time
  4102. * @param {Object} segment the segment which contains the player time
  4103. * @return {Date} program time
  4104. */
  4105. const playerTimeToProgramTime = (playerTime, segment) => {
  4106. if (!segment.dateTimeObject) {
  4107. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  4108. // be used to map the start of a segment with a real world time).
  4109. return null;
  4110. }
  4111. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  4112. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  4113. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  4114. const offsetFromSegmentStart = playerTime - startOfSegment;
  4115. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  4116. };
  4117. const originalSegmentVideoDuration = videoTimingInfo => {
  4118. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  4119. };
  4120. /**
  4121. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  4122. * returned segment might be an estimate or an accurate match.
  4123. *
  4124. * @param {string} programTime The ISO-8601 programTime to find a match for
  4125. * @param {Object} playlist A playlist object to search within
  4126. */
  4127. const findSegmentForProgramTime = (programTime, playlist) => {
  4128. // Assumptions:
  4129. // - verifyProgramDateTimeTags has already been run
  4130. // - live streams have been started
  4131. let dateTimeObject;
  4132. try {
  4133. dateTimeObject = new Date(programTime);
  4134. } catch (e) {
  4135. return null;
  4136. }
  4137. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4138. return null;
  4139. }
  4140. let segment = playlist.segments[0];
  4141. if (dateTimeObject < segment.dateTimeObject) {
  4142. // Requested time is before stream start.
  4143. return null;
  4144. }
  4145. for (let i = 0; i < playlist.segments.length - 1; i++) {
  4146. segment = playlist.segments[i];
  4147. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  4148. if (dateTimeObject < nextSegmentStart) {
  4149. break;
  4150. }
  4151. }
  4152. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4153. const lastSegmentStart = lastSegment.dateTimeObject;
  4154. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  4155. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  4156. if (dateTimeObject > lastSegmentEnd) {
  4157. // Beyond the end of the stream, or our best guess of the end of the stream.
  4158. return null;
  4159. }
  4160. if (dateTimeObject > lastSegmentStart) {
  4161. segment = lastSegment;
  4162. }
  4163. return {
  4164. segment,
  4165. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  4166. // Although, given that all segments have accurate date time objects, the segment
  4167. // selected should be accurate, unless the video has been transmuxed at some point
  4168. // (determined by the presence of the videoTimingInfo object), the segment's "player
  4169. // time" (the start time in the player) can't be considered accurate.
  4170. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4171. };
  4172. };
  4173. /**
  4174. * Finds a segment that contains the given player time(in seconds).
  4175. *
  4176. * @param {number} time The player time to find a match for
  4177. * @param {Object} playlist A playlist object to search within
  4178. */
  4179. const findSegmentForPlayerTime = (time, playlist) => {
  4180. // Assumptions:
  4181. // - there will always be a segment.duration
  4182. // - we can start from zero
  4183. // - segments are in time order
  4184. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4185. return null;
  4186. }
  4187. let segmentEnd = 0;
  4188. let segment;
  4189. for (let i = 0; i < playlist.segments.length; i++) {
  4190. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  4191. // should contain the most accurate values we have for the segment's player times.
  4192. //
  4193. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  4194. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  4195. // calculate an end value.
  4196. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  4197. if (time <= segmentEnd) {
  4198. break;
  4199. }
  4200. }
  4201. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4202. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  4203. // The time requested is beyond the stream end.
  4204. return null;
  4205. }
  4206. if (time > segmentEnd) {
  4207. // The time is within or beyond the last segment.
  4208. //
  4209. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  4210. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  4211. // Technically, because the duration value is only an estimate, the time may still
  4212. // exist in the last segment, however, there isn't enough information to make even
  4213. // a reasonable estimate.
  4214. return null;
  4215. }
  4216. segment = lastSegment;
  4217. }
  4218. return {
  4219. segment,
  4220. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  4221. // Because videoTimingInfo is only set after transmux, it is the only way to get
  4222. // accurate timing values.
  4223. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4224. };
  4225. };
  4226. /**
  4227. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  4228. * If the offset returned is positive, the programTime occurs after the
  4229. * comparisonTimestamp.
  4230. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  4231. *
  4232. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  4233. * @param {string} programTime The programTime as an ISO-8601 string
  4234. * @return {number} offset
  4235. */
  4236. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  4237. let segmentDateTime;
  4238. let programDateTime;
  4239. try {
  4240. segmentDateTime = new Date(comparisonTimeStamp);
  4241. programDateTime = new Date(programTime);
  4242. } catch (e) {// TODO handle error
  4243. }
  4244. const segmentTimeEpoch = segmentDateTime.getTime();
  4245. const programTimeEpoch = programDateTime.getTime();
  4246. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  4247. };
  4248. /**
  4249. * Checks that all segments in this playlist have programDateTime tags.
  4250. *
  4251. * @param {Object} playlist A playlist object
  4252. */
  4253. const verifyProgramDateTimeTags = playlist => {
  4254. if (!playlist.segments || playlist.segments.length === 0) {
  4255. return false;
  4256. }
  4257. for (let i = 0; i < playlist.segments.length; i++) {
  4258. const segment = playlist.segments[i];
  4259. if (!segment.dateTimeObject) {
  4260. return false;
  4261. }
  4262. }
  4263. return true;
  4264. };
  4265. /**
  4266. * Returns the programTime of the media given a playlist and a playerTime.
  4267. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  4268. * If the segments containing the time requested have not been buffered yet, an estimate
  4269. * may be returned to the callback.
  4270. *
  4271. * @param {Object} args
  4272. * @param {Object} args.playlist A playlist object to search within
  4273. * @param {number} time A playerTime in seconds
  4274. * @param {Function} callback(err, programTime)
  4275. * @return {string} err.message A detailed error message
  4276. * @return {Object} programTime
  4277. * @return {number} programTime.mediaSeconds The streamTime in seconds
  4278. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  4279. */
  4280. const getProgramTime = ({
  4281. playlist,
  4282. time = undefined,
  4283. callback
  4284. }) => {
  4285. if (!callback) {
  4286. throw new Error('getProgramTime: callback must be provided');
  4287. }
  4288. if (!playlist || time === undefined) {
  4289. return callback({
  4290. message: 'getProgramTime: playlist and time must be provided'
  4291. });
  4292. }
  4293. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  4294. if (!matchedSegment) {
  4295. return callback({
  4296. message: 'valid programTime was not found'
  4297. });
  4298. }
  4299. if (matchedSegment.type === 'estimate') {
  4300. return callback({
  4301. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  4302. seekTime: matchedSegment.estimatedStart
  4303. });
  4304. }
  4305. const programTimeObject = {
  4306. mediaSeconds: time
  4307. };
  4308. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  4309. if (programTime) {
  4310. programTimeObject.programDateTime = programTime.toISOString();
  4311. }
  4312. return callback(null, programTimeObject);
  4313. };
  4314. /**
  4315. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  4316. *
  4317. * @param {Object} args
  4318. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  4319. * @param {Object} args.playlist A playlist to look within
  4320. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  4321. * @param {Function} args.seekTo A method to perform a seek
  4322. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  4323. * @param {Object} args.tech The tech to seek on
  4324. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  4325. * @return {string} err.message A detailed error message
  4326. * @return {number} newTime The exact time that was seeked to in seconds
  4327. */
  4328. const seekToProgramTime = ({
  4329. programTime,
  4330. playlist,
  4331. retryCount = 2,
  4332. seekTo,
  4333. pauseAfterSeek = true,
  4334. tech,
  4335. callback
  4336. }) => {
  4337. if (!callback) {
  4338. throw new Error('seekToProgramTime: callback must be provided');
  4339. }
  4340. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  4341. return callback({
  4342. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  4343. });
  4344. }
  4345. if (!playlist.endList && !tech.hasStarted_) {
  4346. return callback({
  4347. message: 'player must be playing a live stream to start buffering'
  4348. });
  4349. }
  4350. if (!verifyProgramDateTimeTags(playlist)) {
  4351. return callback({
  4352. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  4353. });
  4354. }
  4355. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  4356. if (!matchedSegment) {
  4357. return callback({
  4358. message: `${programTime} was not found in the stream`
  4359. });
  4360. }
  4361. const segment = matchedSegment.segment;
  4362. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  4363. if (matchedSegment.type === 'estimate') {
  4364. // we've run out of retries
  4365. if (retryCount === 0) {
  4366. return callback({
  4367. message: `${programTime} is not buffered yet. Try again`
  4368. });
  4369. }
  4370. seekTo(matchedSegment.estimatedStart + mediaOffset);
  4371. tech.one('seeked', () => {
  4372. seekToProgramTime({
  4373. programTime,
  4374. playlist,
  4375. retryCount: retryCount - 1,
  4376. seekTo,
  4377. pauseAfterSeek,
  4378. tech,
  4379. callback
  4380. });
  4381. });
  4382. return;
  4383. } // Since the segment.start value is determined from the buffered end or ending time
  4384. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  4385. // modifications.
  4386. const seekToTime = segment.start + mediaOffset;
  4387. const seekedCallback = () => {
  4388. return callback(null, tech.currentTime());
  4389. }; // listen for seeked event
  4390. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  4391. if (pauseAfterSeek) {
  4392. tech.pause();
  4393. }
  4394. seekTo(seekToTime);
  4395. };
  4396. /**
  4397. * Loops through all supported media groups in master and calls the provided
  4398. * callback for each group
  4399. *
  4400. * @param {Object} master
  4401. * The parsed master manifest object
  4402. * @param {string[]} groups
  4403. * The media groups to call the callback for
  4404. * @param {Function} callback
  4405. * Callback to call for each media group
  4406. */
  4407. var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
  4408. groups.forEach(function (mediaType) {
  4409. for (var groupKey in master.mediaGroups[mediaType]) {
  4410. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  4411. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  4412. callback(mediaProperties, mediaType, groupKey, labelKey);
  4413. }
  4414. }
  4415. });
  4416. };
  4417. /*! @name mpd-parser @version 1.0.1 @license Apache-2.0 */
  4418. const isObject = obj => {
  4419. return !!obj && typeof obj === 'object';
  4420. };
  4421. const merge = (...objects) => {
  4422. return objects.reduce((result, source) => {
  4423. if (typeof source !== 'object') {
  4424. return result;
  4425. }
  4426. Object.keys(source).forEach(key => {
  4427. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  4428. result[key] = result[key].concat(source[key]);
  4429. } else if (isObject(result[key]) && isObject(source[key])) {
  4430. result[key] = merge(result[key], source[key]);
  4431. } else {
  4432. result[key] = source[key];
  4433. }
  4434. });
  4435. return result;
  4436. }, {});
  4437. };
  4438. const values = o => Object.keys(o).map(k => o[k]);
  4439. const range = (start, end) => {
  4440. const result = [];
  4441. for (let i = start; i < end; i++) {
  4442. result.push(i);
  4443. }
  4444. return result;
  4445. };
  4446. const flatten = lists => lists.reduce((x, y) => x.concat(y), []);
  4447. const from = list => {
  4448. if (!list.length) {
  4449. return [];
  4450. }
  4451. const result = [];
  4452. for (let i = 0; i < list.length; i++) {
  4453. result.push(list[i]);
  4454. }
  4455. return result;
  4456. };
  4457. const findIndexes = (l, key) => l.reduce((a, e, i) => {
  4458. if (e[key]) {
  4459. a.push(i);
  4460. }
  4461. return a;
  4462. }, []);
  4463. /**
  4464. * Returns a union of the included lists provided each element can be identified by a key.
  4465. *
  4466. * @param {Array} list - list of lists to get the union of
  4467. * @param {Function} keyFunction - the function to use as a key for each element
  4468. *
  4469. * @return {Array} the union of the arrays
  4470. */
  4471. const union = (lists, keyFunction) => {
  4472. return values(lists.reduce((acc, list) => {
  4473. list.forEach(el => {
  4474. acc[keyFunction(el)] = el;
  4475. });
  4476. return acc;
  4477. }, {}));
  4478. };
  4479. var errors = {
  4480. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  4481. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  4482. DASH_INVALID_XML: 'DASH_INVALID_XML',
  4483. NO_BASE_URL: 'NO_BASE_URL',
  4484. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  4485. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  4486. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  4487. };
  4488. /**
  4489. * @typedef {Object} SingleUri
  4490. * @property {string} uri - relative location of segment
  4491. * @property {string} resolvedUri - resolved location of segment
  4492. * @property {Object} byterange - Object containing information on how to make byte range
  4493. * requests following byte-range-spec per RFC2616.
  4494. * @property {String} byterange.length - length of range request
  4495. * @property {String} byterange.offset - byte offset of range request
  4496. *
  4497. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  4498. */
  4499. /**
  4500. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  4501. * that conforms to how m3u8-parser is structured
  4502. *
  4503. * @see https://github.com/videojs/m3u8-parser
  4504. *
  4505. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  4506. * @param {string} source - source url for segment
  4507. * @param {string} range - optional range used for range calls,
  4508. * follows RFC 2616, Clause 14.35.1
  4509. * @return {SingleUri} full segment information transformed into a format similar
  4510. * to m3u8-parser
  4511. */
  4512. const urlTypeToSegment = ({
  4513. baseUrl = '',
  4514. source = '',
  4515. range = '',
  4516. indexRange = ''
  4517. }) => {
  4518. const segment = {
  4519. uri: source,
  4520. resolvedUri: resolveUrl$1(baseUrl || '', source)
  4521. };
  4522. if (range || indexRange) {
  4523. const rangeStr = range ? range : indexRange;
  4524. const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  4525. let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  4526. let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  4527. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  4528. startRange = Number(startRange);
  4529. }
  4530. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  4531. endRange = Number(endRange);
  4532. }
  4533. let length;
  4534. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  4535. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  4536. } else {
  4537. length = endRange - startRange + 1;
  4538. }
  4539. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  4540. length = Number(length);
  4541. } // byterange should be inclusive according to
  4542. // RFC 2616, Clause 14.35.1
  4543. segment.byterange = {
  4544. length,
  4545. offset: startRange
  4546. };
  4547. }
  4548. return segment;
  4549. };
  4550. const byteRangeToString = byterange => {
  4551. // `endRange` is one less than `offset + length` because the HTTP range
  4552. // header uses inclusive ranges
  4553. let endRange;
  4554. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  4555. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  4556. } else {
  4557. endRange = byterange.offset + byterange.length - 1;
  4558. }
  4559. return `${byterange.offset}-${endRange}`;
  4560. };
  4561. /**
  4562. * parse the end number attribue that can be a string
  4563. * number, or undefined.
  4564. *
  4565. * @param {string|number|undefined} endNumber
  4566. * The end number attribute.
  4567. *
  4568. * @return {number|null}
  4569. * The result of parsing the end number.
  4570. */
  4571. const parseEndNumber = endNumber => {
  4572. if (endNumber && typeof endNumber !== 'number') {
  4573. endNumber = parseInt(endNumber, 10);
  4574. }
  4575. if (isNaN(endNumber)) {
  4576. return null;
  4577. }
  4578. return endNumber;
  4579. };
  4580. /**
  4581. * Functions for calculating the range of available segments in static and dynamic
  4582. * manifests.
  4583. */
  4584. const segmentRange = {
  4585. /**
  4586. * Returns the entire range of available segments for a static MPD
  4587. *
  4588. * @param {Object} attributes
  4589. * Inheritied MPD attributes
  4590. * @return {{ start: number, end: number }}
  4591. * The start and end numbers for available segments
  4592. */
  4593. static(attributes) {
  4594. const {
  4595. duration,
  4596. timescale = 1,
  4597. sourceDuration,
  4598. periodDuration
  4599. } = attributes;
  4600. const endNumber = parseEndNumber(attributes.endNumber);
  4601. const segmentDuration = duration / timescale;
  4602. if (typeof endNumber === 'number') {
  4603. return {
  4604. start: 0,
  4605. end: endNumber
  4606. };
  4607. }
  4608. if (typeof periodDuration === 'number') {
  4609. return {
  4610. start: 0,
  4611. end: periodDuration / segmentDuration
  4612. };
  4613. }
  4614. return {
  4615. start: 0,
  4616. end: sourceDuration / segmentDuration
  4617. };
  4618. },
  4619. /**
  4620. * Returns the current live window range of available segments for a dynamic MPD
  4621. *
  4622. * @param {Object} attributes
  4623. * Inheritied MPD attributes
  4624. * @return {{ start: number, end: number }}
  4625. * The start and end numbers for available segments
  4626. */
  4627. dynamic(attributes) {
  4628. const {
  4629. NOW,
  4630. clientOffset,
  4631. availabilityStartTime,
  4632. timescale = 1,
  4633. duration,
  4634. periodStart = 0,
  4635. minimumUpdatePeriod = 0,
  4636. timeShiftBufferDepth = Infinity
  4637. } = attributes;
  4638. const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  4639. // after retrieving UTC server time.
  4640. const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  4641. // Convert the period start time to EPOCH.
  4642. const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  4643. const periodEndWC = now + minimumUpdatePeriod;
  4644. const periodDuration = periodEndWC - periodStartWC;
  4645. const segmentCount = Math.ceil(periodDuration * timescale / duration);
  4646. const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  4647. const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  4648. return {
  4649. start: Math.max(0, availableStart),
  4650. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  4651. };
  4652. }
  4653. };
  4654. /**
  4655. * Maps a range of numbers to objects with information needed to build the corresponding
  4656. * segment list
  4657. *
  4658. * @name toSegmentsCallback
  4659. * @function
  4660. * @param {number} number
  4661. * Number of the segment
  4662. * @param {number} index
  4663. * Index of the number in the range list
  4664. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  4665. * Object with segment timing and duration info
  4666. */
  4667. /**
  4668. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  4669. * information needed to build the segment list.
  4670. *
  4671. * @param {Object} attributes
  4672. * Inherited MPD attributes
  4673. * @return {toSegmentsCallback}
  4674. * Callback map function
  4675. */
  4676. const toSegments = attributes => number => {
  4677. const {
  4678. duration,
  4679. timescale = 1,
  4680. periodStart,
  4681. startNumber = 1
  4682. } = attributes;
  4683. return {
  4684. number: startNumber + number,
  4685. duration: duration / timescale,
  4686. timeline: periodStart,
  4687. time: number * duration
  4688. };
  4689. };
  4690. /**
  4691. * Returns a list of objects containing segment timing and duration info used for
  4692. * building the list of segments. This uses the @duration attribute specified
  4693. * in the MPD manifest to derive the range of segments.
  4694. *
  4695. * @param {Object} attributes
  4696. * Inherited MPD attributes
  4697. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  4698. * List of Objects with segment timing and duration info
  4699. */
  4700. const parseByDuration = attributes => {
  4701. const {
  4702. type,
  4703. duration,
  4704. timescale = 1,
  4705. periodDuration,
  4706. sourceDuration
  4707. } = attributes;
  4708. const {
  4709. start,
  4710. end
  4711. } = segmentRange[type](attributes);
  4712. const segments = range(start, end).map(toSegments(attributes));
  4713. if (type === 'static') {
  4714. const index = segments.length - 1; // section is either a period or the full source
  4715. const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  4716. segments[index].duration = sectionDuration - duration / timescale * index;
  4717. }
  4718. return segments;
  4719. };
  4720. /**
  4721. * Translates SegmentBase into a set of segments.
  4722. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  4723. * node should be translated into segment.
  4724. *
  4725. * @param {Object} attributes
  4726. * Object containing all inherited attributes from parent elements with attribute
  4727. * names as keys
  4728. * @return {Object.<Array>} list of segments
  4729. */
  4730. const segmentsFromBase = attributes => {
  4731. const {
  4732. baseUrl,
  4733. initialization = {},
  4734. sourceDuration,
  4735. indexRange = '',
  4736. periodStart,
  4737. presentationTime,
  4738. number = 0,
  4739. duration
  4740. } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  4741. if (!baseUrl) {
  4742. throw new Error(errors.NO_BASE_URL);
  4743. }
  4744. const initSegment = urlTypeToSegment({
  4745. baseUrl,
  4746. source: initialization.sourceURL,
  4747. range: initialization.range
  4748. });
  4749. const segment = urlTypeToSegment({
  4750. baseUrl,
  4751. source: baseUrl,
  4752. indexRange
  4753. });
  4754. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  4755. // (since SegmentBase is only for one total segment)
  4756. if (duration) {
  4757. const segmentTimeInfo = parseByDuration(attributes);
  4758. if (segmentTimeInfo.length) {
  4759. segment.duration = segmentTimeInfo[0].duration;
  4760. segment.timeline = segmentTimeInfo[0].timeline;
  4761. }
  4762. } else if (sourceDuration) {
  4763. segment.duration = sourceDuration;
  4764. segment.timeline = periodStart;
  4765. } // If presentation time is provided, these segments are being generated by SIDX
  4766. // references, and should use the time provided. For the general case of SegmentBase,
  4767. // there should only be one segment in the period, so its presentation time is the same
  4768. // as its period start.
  4769. segment.presentationTime = presentationTime || periodStart;
  4770. segment.number = number;
  4771. return [segment];
  4772. };
  4773. /**
  4774. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  4775. * according to the sidx information given.
  4776. *
  4777. * playlist.sidx has metadadata about the sidx where-as the sidx param
  4778. * is the parsed sidx box itself.
  4779. *
  4780. * @param {Object} playlist the playlist to update the sidx information for
  4781. * @param {Object} sidx the parsed sidx box
  4782. * @return {Object} the playlist object with the updated sidx information
  4783. */
  4784. const addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {
  4785. // Retain init segment information
  4786. const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  4787. const sourceDuration = playlist.sidx.duration; // Retain source timeline
  4788. const timeline = playlist.timeline || 0;
  4789. const sidxByteRange = playlist.sidx.byterange;
  4790. const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  4791. const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  4792. const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);
  4793. const segments = [];
  4794. const type = playlist.endList ? 'static' : 'dynamic';
  4795. const periodStart = playlist.sidx.timeline;
  4796. let presentationTime = periodStart;
  4797. let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  4798. let startIndex; // eslint-disable-next-line
  4799. if (typeof sidx.firstOffset === 'bigint') {
  4800. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  4801. } else {
  4802. startIndex = sidxEnd + sidx.firstOffset;
  4803. }
  4804. for (let i = 0; i < mediaReferences.length; i++) {
  4805. const reference = sidx.references[i]; // size of the referenced (sub)segment
  4806. const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  4807. // this will be converted to seconds when generating segments
  4808. const duration = reference.subsegmentDuration; // should be an inclusive range
  4809. let endIndex; // eslint-disable-next-line
  4810. if (typeof startIndex === 'bigint') {
  4811. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  4812. } else {
  4813. endIndex = startIndex + size - 1;
  4814. }
  4815. const indexRange = `${startIndex}-${endIndex}`;
  4816. const attributes = {
  4817. baseUrl,
  4818. timescale,
  4819. timeline,
  4820. periodStart,
  4821. presentationTime,
  4822. number,
  4823. duration,
  4824. sourceDuration,
  4825. indexRange,
  4826. type
  4827. };
  4828. const segment = segmentsFromBase(attributes)[0];
  4829. if (initSegment) {
  4830. segment.map = initSegment;
  4831. }
  4832. segments.push(segment);
  4833. if (typeof startIndex === 'bigint') {
  4834. startIndex += window.BigInt(size);
  4835. } else {
  4836. startIndex += size;
  4837. }
  4838. presentationTime += duration / timescale;
  4839. number++;
  4840. }
  4841. playlist.segments = segments;
  4842. return playlist;
  4843. };
  4844. const SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  4845. const TIME_FUDGE = 1 / 60;
  4846. /**
  4847. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  4848. *
  4849. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  4850. *
  4851. * @return {TimelineStart[]} the combined and deduped timeline starts
  4852. */
  4853. const getUniqueTimelineStarts = timelineStarts => {
  4854. return union(timelineStarts, ({
  4855. timeline
  4856. }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);
  4857. };
  4858. /**
  4859. * Finds the playlist with the matching NAME attribute.
  4860. *
  4861. * @param {Array} playlists - playlists to search through
  4862. * @param {string} name - the NAME attribute to search for
  4863. *
  4864. * @return {Object|null} the matching playlist object, or null
  4865. */
  4866. const findPlaylistWithName = (playlists, name) => {
  4867. for (let i = 0; i < playlists.length; i++) {
  4868. if (playlists[i].attributes.NAME === name) {
  4869. return playlists[i];
  4870. }
  4871. }
  4872. return null;
  4873. };
  4874. /**
  4875. * Gets a flattened array of media group playlists.
  4876. *
  4877. * @param {Object} manifest - the main manifest object
  4878. *
  4879. * @return {Array} the media group playlists
  4880. */
  4881. const getMediaGroupPlaylists = manifest => {
  4882. let mediaGroupPlaylists = [];
  4883. forEachMediaGroup(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {
  4884. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  4885. });
  4886. return mediaGroupPlaylists;
  4887. };
  4888. /**
  4889. * Updates the playlist's media sequence numbers.
  4890. *
  4891. * @param {Object} config - options object
  4892. * @param {Object} config.playlist - the playlist to update
  4893. * @param {number} config.mediaSequence - the mediaSequence number to start with
  4894. */
  4895. const updateMediaSequenceForPlaylist = ({
  4896. playlist,
  4897. mediaSequence
  4898. }) => {
  4899. playlist.mediaSequence = mediaSequence;
  4900. playlist.segments.forEach((segment, index) => {
  4901. segment.number = playlist.mediaSequence + index;
  4902. });
  4903. };
  4904. /**
  4905. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  4906. * and a complete list of timeline starts.
  4907. *
  4908. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  4909. * will be updated.
  4910. *
  4911. * Since early available timelines are not supported, at least one segment must be present.
  4912. *
  4913. * @param {Object} config - options object
  4914. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  4915. * @param {Object[]} newPlaylists - the new playlists to update
  4916. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  4917. */
  4918. const updateSequenceNumbers = ({
  4919. oldPlaylists,
  4920. newPlaylists,
  4921. timelineStarts
  4922. }) => {
  4923. newPlaylists.forEach(playlist => {
  4924. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  4925. timeline
  4926. }) {
  4927. return timeline === playlist.timeline;
  4928. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  4929. // (see ISO_23009-1-2012 5.3.5.2).
  4930. //
  4931. // If the same Representation existed in a prior Period, it will retain the same NAME.
  4932. const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  4933. if (!oldPlaylist) {
  4934. // Since this is a new playlist, the media sequence values can start from 0 without
  4935. // consequence.
  4936. return;
  4937. } // TODO better support for live SIDX
  4938. //
  4939. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  4940. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  4941. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  4942. // not supported when the SIDX properties change on refreshes.
  4943. //
  4944. // In the future, if support needs to be added, the merging logic here can be called
  4945. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  4946. // thrown due to undefined references.
  4947. if (playlist.sidx) {
  4948. return;
  4949. } // Since we don't yet support early available timelines, we don't need to support
  4950. // playlists with no segments.
  4951. const firstNewSegment = playlist.segments[0];
  4952. const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {
  4953. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  4954. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  4955. // In this case the media sequence should account for this update, and the new segments
  4956. // should be marked as discontinuous from the prior content, since the last prior
  4957. // timeline was removed.
  4958. if (oldMatchingSegmentIndex === -1) {
  4959. updateMediaSequenceForPlaylist({
  4960. playlist,
  4961. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  4962. });
  4963. playlist.segments[0].discontinuity = true;
  4964. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  4965. //
  4966. // If the new playlist's timeline is the same as the last seen segment's timeline,
  4967. // then a discontinuity can be added to identify that there's potentially missing
  4968. // content. If there's no missing content, the discontinuity should still be rather
  4969. // harmless. It's possible that if segment durations are accurate enough, that the
  4970. // existence of a gap can be determined using the presentation times and durations,
  4971. // but if the segment timing info is off, it may introduce more problems than simply
  4972. // adding the discontinuity.
  4973. //
  4974. // If the new playlist's timeline is different from the last seen segment's timeline,
  4975. // then a discontinuity can be added to identify that this is the first seen segment
  4976. // of a new timeline. However, the logic at the start of this function that
  4977. // determined the disconinuity sequence by timeline index is now off by one (the
  4978. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  4979. // we added it), so the disconinuity sequence must be decremented.
  4980. //
  4981. // A period may also have a duration of zero, so the case of no segments is handled
  4982. // here even though we don't yet support early available periods.
  4983. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  4984. playlist.discontinuitySequence--;
  4985. }
  4986. return;
  4987. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  4988. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  4989. // timeline's matching one, but instead should be the one prior, and the first segment
  4990. // of the new manifest should be marked with a discontinuity.
  4991. //
  4992. // The reason for this special case is that discontinuity sequence shows how many
  4993. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  4994. // the first segment of a new "timeline." Because of this, while DASH will retain that
  4995. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  4996. // sequence, and that first segment is an indicator, but can be removed before that
  4997. // timeline is gone.
  4998. const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  4999. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  5000. firstNewSegment.discontinuity = true;
  5001. playlist.discontinuityStarts.unshift(0);
  5002. playlist.discontinuitySequence--;
  5003. }
  5004. updateMediaSequenceForPlaylist({
  5005. playlist,
  5006. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  5007. });
  5008. });
  5009. };
  5010. /**
  5011. * Given an old parsed manifest object and a new parsed manifest object, updates the
  5012. * sequence and timing values within the new manifest to ensure that it lines up with the
  5013. * old.
  5014. *
  5015. * @param {Array} oldManifest - the old main manifest object
  5016. * @param {Array} newManifest - the new main manifest object
  5017. *
  5018. * @return {Object} the updated new manifest object
  5019. */
  5020. const positionManifestOnTimeline = ({
  5021. oldManifest,
  5022. newManifest
  5023. }) => {
  5024. // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  5025. //
  5026. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  5027. //
  5028. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  5029. //
  5030. // Because of this change, and the difficulty of supporting periods with changing start
  5031. // times, periods with changing start times are not supported. This makes the logic much
  5032. // simpler, since periods with the same start time can be considerred the same period
  5033. // across refreshes.
  5034. //
  5035. // To give an example as to the difficulty of handling periods where the start time may
  5036. // change, if a single period manifest is refreshed with another manifest with a single
  5037. // period, and both the start and end times are increased, then the only way to determine
  5038. // if it's a new period or an old one that has changed is to look through the segments of
  5039. // each playlist and determine the presentation time bounds to find a match. In addition,
  5040. // if the period start changed to exceed the old period end, then there would be no
  5041. // match, and it would not be possible to determine whether the refreshed period is a new
  5042. // one or the old one.
  5043. const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  5044. const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  5045. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  5046. // of properties are saved for each seen Period. Even long running live streams won't
  5047. // generate too many Periods, unless the stream is watched for decades. In the future,
  5048. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  5049. // but it may not become an issue, and the additional info can be useful for debugging.
  5050. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  5051. updateSequenceNumbers({
  5052. oldPlaylists,
  5053. newPlaylists,
  5054. timelineStarts: newManifest.timelineStarts
  5055. });
  5056. return newManifest;
  5057. };
  5058. const generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  5059. const mergeDiscontiguousPlaylists = playlists => {
  5060. const mergedPlaylists = values(playlists.reduce((acc, playlist) => {
  5061. // assuming playlist IDs are the same across periods
  5062. // TODO: handle multiperiod where representation sets are not the same
  5063. // across periods
  5064. const name = playlist.attributes.id + (playlist.attributes.lang || '');
  5065. if (!acc[name]) {
  5066. // First Period
  5067. acc[name] = playlist;
  5068. acc[name].attributes.timelineStarts = [];
  5069. } else {
  5070. // Subsequent Periods
  5071. if (playlist.segments) {
  5072. // first segment of subsequent periods signal a discontinuity
  5073. if (playlist.segments[0]) {
  5074. playlist.segments[0].discontinuity = true;
  5075. }
  5076. acc[name].segments.push(...playlist.segments);
  5077. } // bubble up contentProtection, this assumes all DRM content
  5078. // has the same contentProtection
  5079. if (playlist.attributes.contentProtection) {
  5080. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  5081. }
  5082. }
  5083. acc[name].attributes.timelineStarts.push({
  5084. // Although they represent the same number, it's important to have both to make it
  5085. // compatible with HLS potentially having a similar attribute.
  5086. start: playlist.attributes.periodStart,
  5087. timeline: playlist.attributes.periodStart
  5088. });
  5089. return acc;
  5090. }, {}));
  5091. return mergedPlaylists.map(playlist => {
  5092. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  5093. return playlist;
  5094. });
  5095. };
  5096. const addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {
  5097. const sidxKey = generateSidxKey(playlist.sidx);
  5098. const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  5099. if (sidxMatch) {
  5100. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  5101. }
  5102. return playlist;
  5103. };
  5104. const addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {
  5105. if (!Object.keys(sidxMapping).length) {
  5106. return playlists;
  5107. }
  5108. for (const i in playlists) {
  5109. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  5110. }
  5111. return playlists;
  5112. };
  5113. const formatAudioPlaylist = ({
  5114. attributes,
  5115. segments,
  5116. sidx,
  5117. mediaSequence,
  5118. discontinuitySequence,
  5119. discontinuityStarts
  5120. }, isAudioOnly) => {
  5121. const playlist = {
  5122. attributes: {
  5123. NAME: attributes.id,
  5124. BANDWIDTH: attributes.bandwidth,
  5125. CODECS: attributes.codecs,
  5126. ['PROGRAM-ID']: 1
  5127. },
  5128. uri: '',
  5129. endList: attributes.type === 'static',
  5130. timeline: attributes.periodStart,
  5131. resolvedUri: '',
  5132. targetDuration: attributes.duration,
  5133. discontinuitySequence,
  5134. discontinuityStarts,
  5135. timelineStarts: attributes.timelineStarts,
  5136. mediaSequence,
  5137. segments
  5138. };
  5139. if (attributes.contentProtection) {
  5140. playlist.contentProtection = attributes.contentProtection;
  5141. }
  5142. if (sidx) {
  5143. playlist.sidx = sidx;
  5144. }
  5145. if (isAudioOnly) {
  5146. playlist.attributes.AUDIO = 'audio';
  5147. playlist.attributes.SUBTITLES = 'subs';
  5148. }
  5149. return playlist;
  5150. };
  5151. const formatVttPlaylist = ({
  5152. attributes,
  5153. segments,
  5154. mediaSequence,
  5155. discontinuityStarts,
  5156. discontinuitySequence
  5157. }) => {
  5158. if (typeof segments === 'undefined') {
  5159. // vtt tracks may use single file in BaseURL
  5160. segments = [{
  5161. uri: attributes.baseUrl,
  5162. timeline: attributes.periodStart,
  5163. resolvedUri: attributes.baseUrl || '',
  5164. duration: attributes.sourceDuration,
  5165. number: 0
  5166. }]; // targetDuration should be the same duration as the only segment
  5167. attributes.duration = attributes.sourceDuration;
  5168. }
  5169. const m3u8Attributes = {
  5170. NAME: attributes.id,
  5171. BANDWIDTH: attributes.bandwidth,
  5172. ['PROGRAM-ID']: 1
  5173. };
  5174. if (attributes.codecs) {
  5175. m3u8Attributes.CODECS = attributes.codecs;
  5176. }
  5177. return {
  5178. attributes: m3u8Attributes,
  5179. uri: '',
  5180. endList: attributes.type === 'static',
  5181. timeline: attributes.periodStart,
  5182. resolvedUri: attributes.baseUrl || '',
  5183. targetDuration: attributes.duration,
  5184. timelineStarts: attributes.timelineStarts,
  5185. discontinuityStarts,
  5186. discontinuitySequence,
  5187. mediaSequence,
  5188. segments
  5189. };
  5190. };
  5191. const organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {
  5192. let mainPlaylist;
  5193. const formattedPlaylists = playlists.reduce((a, playlist) => {
  5194. const role = playlist.attributes.role && playlist.attributes.role.value || '';
  5195. const language = playlist.attributes.lang || '';
  5196. let label = playlist.attributes.label || 'main';
  5197. if (language && !playlist.attributes.label) {
  5198. const roleLabel = role ? ` (${role})` : '';
  5199. label = `${playlist.attributes.lang}${roleLabel}`;
  5200. }
  5201. if (!a[label]) {
  5202. a[label] = {
  5203. language,
  5204. autoselect: true,
  5205. default: role === 'main',
  5206. playlists: [],
  5207. uri: ''
  5208. };
  5209. }
  5210. const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  5211. a[label].playlists.push(formatted);
  5212. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  5213. mainPlaylist = playlist;
  5214. mainPlaylist.default = true;
  5215. }
  5216. return a;
  5217. }, {}); // if no playlists have role "main", mark the first as main
  5218. if (!mainPlaylist) {
  5219. const firstLabel = Object.keys(formattedPlaylists)[0];
  5220. formattedPlaylists[firstLabel].default = true;
  5221. }
  5222. return formattedPlaylists;
  5223. };
  5224. const organizeVttPlaylists = (playlists, sidxMapping = {}) => {
  5225. return playlists.reduce((a, playlist) => {
  5226. const label = playlist.attributes.lang || 'text';
  5227. if (!a[label]) {
  5228. a[label] = {
  5229. language: label,
  5230. default: false,
  5231. autoselect: false,
  5232. playlists: [],
  5233. uri: ''
  5234. };
  5235. }
  5236. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  5237. return a;
  5238. }, {});
  5239. };
  5240. const organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {
  5241. if (!svc) {
  5242. return svcObj;
  5243. }
  5244. svc.forEach(service => {
  5245. const {
  5246. channel,
  5247. language
  5248. } = service;
  5249. svcObj[language] = {
  5250. autoselect: false,
  5251. default: false,
  5252. instreamId: channel,
  5253. language
  5254. };
  5255. if (service.hasOwnProperty('aspectRatio')) {
  5256. svcObj[language].aspectRatio = service.aspectRatio;
  5257. }
  5258. if (service.hasOwnProperty('easyReader')) {
  5259. svcObj[language].easyReader = service.easyReader;
  5260. }
  5261. if (service.hasOwnProperty('3D')) {
  5262. svcObj[language]['3D'] = service['3D'];
  5263. }
  5264. });
  5265. return svcObj;
  5266. }, {});
  5267. const formatVideoPlaylist = ({
  5268. attributes,
  5269. segments,
  5270. sidx,
  5271. discontinuityStarts
  5272. }) => {
  5273. const playlist = {
  5274. attributes: {
  5275. NAME: attributes.id,
  5276. AUDIO: 'audio',
  5277. SUBTITLES: 'subs',
  5278. RESOLUTION: {
  5279. width: attributes.width,
  5280. height: attributes.height
  5281. },
  5282. CODECS: attributes.codecs,
  5283. BANDWIDTH: attributes.bandwidth,
  5284. ['PROGRAM-ID']: 1
  5285. },
  5286. uri: '',
  5287. endList: attributes.type === 'static',
  5288. timeline: attributes.periodStart,
  5289. resolvedUri: '',
  5290. targetDuration: attributes.duration,
  5291. discontinuityStarts,
  5292. timelineStarts: attributes.timelineStarts,
  5293. segments
  5294. };
  5295. if (attributes.frameRate) {
  5296. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  5297. }
  5298. if (attributes.contentProtection) {
  5299. playlist.contentProtection = attributes.contentProtection;
  5300. }
  5301. if (sidx) {
  5302. playlist.sidx = sidx;
  5303. }
  5304. return playlist;
  5305. };
  5306. const videoOnly = ({
  5307. attributes
  5308. }) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  5309. const audioOnly = ({
  5310. attributes
  5311. }) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  5312. const vttOnly = ({
  5313. attributes
  5314. }) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  5315. /**
  5316. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  5317. * be the same number.
  5318. *
  5319. * @typedef {Object} TimelineStart
  5320. * @property {number} start - the start time of the timeline
  5321. * @property {number} timeline - the timeline number
  5322. */
  5323. /**
  5324. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  5325. *
  5326. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  5327. * DASH specific attribute used in constructing segment URI's from templates. However, from
  5328. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  5329. * value, which should start at the original media sequence value (or 0) and increment by 1
  5330. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  5331. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  5332. * from a 0 mediaSequence value and increment from there.
  5333. *
  5334. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  5335. * debugging and making sense of the manifest.
  5336. *
  5337. * For live playlists, to account for values increasing in manifests when periods are
  5338. * removed on refreshes, merging logic should be used to update the numbers to their
  5339. * appropriate values (to ensure they're sequential and increasing).
  5340. *
  5341. * @param {Object[]} playlists - the playlists to update
  5342. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  5343. */
  5344. const addMediaSequenceValues = (playlists, timelineStarts) => {
  5345. // increment all segments sequentially
  5346. playlists.forEach(playlist => {
  5347. playlist.mediaSequence = 0;
  5348. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  5349. timeline
  5350. }) {
  5351. return timeline === playlist.timeline;
  5352. });
  5353. if (!playlist.segments) {
  5354. return;
  5355. }
  5356. playlist.segments.forEach((segment, index) => {
  5357. segment.number = index;
  5358. });
  5359. });
  5360. };
  5361. /**
  5362. * Given a media group object, flattens all playlists within the media group into a single
  5363. * array.
  5364. *
  5365. * @param {Object} mediaGroupObject - the media group object
  5366. *
  5367. * @return {Object[]}
  5368. * The media group playlists
  5369. */
  5370. const flattenMediaGroupPlaylists = mediaGroupObject => {
  5371. if (!mediaGroupObject) {
  5372. return [];
  5373. }
  5374. return Object.keys(mediaGroupObject).reduce((acc, label) => {
  5375. const labelContents = mediaGroupObject[label];
  5376. return acc.concat(labelContents.playlists);
  5377. }, []);
  5378. };
  5379. const toM3u8 = ({
  5380. dashPlaylists,
  5381. locations,
  5382. sidxMapping = {},
  5383. previousManifest
  5384. }) => {
  5385. if (!dashPlaylists.length) {
  5386. return {};
  5387. } // grab all main manifest attributes
  5388. const {
  5389. sourceDuration: duration,
  5390. type,
  5391. suggestedPresentationDelay,
  5392. minimumUpdatePeriod
  5393. } = dashPlaylists[0].attributes;
  5394. const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  5395. const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  5396. const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  5397. const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);
  5398. const manifest = {
  5399. allowCache: true,
  5400. discontinuityStarts: [],
  5401. segments: [],
  5402. endList: true,
  5403. mediaGroups: {
  5404. AUDIO: {},
  5405. VIDEO: {},
  5406. ['CLOSED-CAPTIONS']: {},
  5407. SUBTITLES: {}
  5408. },
  5409. uri: '',
  5410. duration,
  5411. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  5412. };
  5413. if (minimumUpdatePeriod >= 0) {
  5414. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  5415. }
  5416. if (locations) {
  5417. manifest.locations = locations;
  5418. }
  5419. if (type === 'dynamic') {
  5420. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  5421. }
  5422. const isAudioOnly = manifest.playlists.length === 0;
  5423. const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  5424. const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  5425. const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  5426. const playlistTimelineStarts = formattedPlaylists.map(({
  5427. timelineStarts
  5428. }) => timelineStarts);
  5429. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  5430. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  5431. if (organizedAudioGroup) {
  5432. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  5433. }
  5434. if (organizedVttGroup) {
  5435. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  5436. }
  5437. if (captions.length) {
  5438. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  5439. }
  5440. if (previousManifest) {
  5441. return positionManifestOnTimeline({
  5442. oldManifest: previousManifest,
  5443. newManifest: manifest
  5444. });
  5445. }
  5446. return manifest;
  5447. };
  5448. /**
  5449. * Calculates the R (repetition) value for a live stream (for the final segment
  5450. * in a manifest where the r value is negative 1)
  5451. *
  5452. * @param {Object} attributes
  5453. * Object containing all inherited attributes from parent elements with attribute
  5454. * names as keys
  5455. * @param {number} time
  5456. * current time (typically the total time up until the final segment)
  5457. * @param {number} duration
  5458. * duration property for the given <S />
  5459. *
  5460. * @return {number}
  5461. * R value to reach the end of the given period
  5462. */
  5463. const getLiveRValue = (attributes, time, duration) => {
  5464. const {
  5465. NOW,
  5466. clientOffset,
  5467. availabilityStartTime,
  5468. timescale = 1,
  5469. periodStart = 0,
  5470. minimumUpdatePeriod = 0
  5471. } = attributes;
  5472. const now = (NOW + clientOffset) / 1000;
  5473. const periodStartWC = availabilityStartTime + periodStart;
  5474. const periodEndWC = now + minimumUpdatePeriod;
  5475. const periodDuration = periodEndWC - periodStartWC;
  5476. return Math.ceil((periodDuration * timescale - time) / duration);
  5477. };
  5478. /**
  5479. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  5480. * timing and duration
  5481. *
  5482. * @param {Object} attributes
  5483. * Object containing all inherited attributes from parent elements with attribute
  5484. * names as keys
  5485. * @param {Object[]} segmentTimeline
  5486. * List of objects representing the attributes of each S element contained within
  5487. *
  5488. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  5489. * List of Objects with segment timing and duration info
  5490. */
  5491. const parseByTimeline = (attributes, segmentTimeline) => {
  5492. const {
  5493. type,
  5494. minimumUpdatePeriod = 0,
  5495. media = '',
  5496. sourceDuration,
  5497. timescale = 1,
  5498. startNumber = 1,
  5499. periodStart: timeline
  5500. } = attributes;
  5501. const segments = [];
  5502. let time = -1;
  5503. for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  5504. const S = segmentTimeline[sIndex];
  5505. const duration = S.d;
  5506. const repeat = S.r || 0;
  5507. const segmentTime = S.t || 0;
  5508. if (time < 0) {
  5509. // first segment
  5510. time = segmentTime;
  5511. }
  5512. if (segmentTime && segmentTime > time) {
  5513. // discontinuity
  5514. // TODO: How to handle this type of discontinuity
  5515. // timeline++ here would treat it like HLS discontuity and content would
  5516. // get appended without gap
  5517. // E.G.
  5518. // <S t="0" d="1" />
  5519. // <S d="1" />
  5520. // <S d="1" />
  5521. // <S t="5" d="1" />
  5522. // would have $Time$ values of [0, 1, 2, 5]
  5523. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  5524. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  5525. // does the value of sourceDuration consider this when calculating arbitrary
  5526. // negative @r repeat value?
  5527. // E.G. Same elements as above with this added at the end
  5528. // <S d="1" r="-1" />
  5529. // with a sourceDuration of 10
  5530. // Would the 2 gaps be included in the time duration calculations resulting in
  5531. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  5532. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  5533. time = segmentTime;
  5534. }
  5535. let count;
  5536. if (repeat < 0) {
  5537. const nextS = sIndex + 1;
  5538. if (nextS === segmentTimeline.length) {
  5539. // last segment
  5540. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  5541. count = getLiveRValue(attributes, time, duration);
  5542. } else {
  5543. // TODO: This may be incorrect depending on conclusion of TODO above
  5544. count = (sourceDuration * timescale - time) / duration;
  5545. }
  5546. } else {
  5547. count = (segmentTimeline[nextS].t - time) / duration;
  5548. }
  5549. } else {
  5550. count = repeat + 1;
  5551. }
  5552. const end = startNumber + segments.length + count;
  5553. let number = startNumber + segments.length;
  5554. while (number < end) {
  5555. segments.push({
  5556. number,
  5557. duration: duration / timescale,
  5558. time,
  5559. timeline
  5560. });
  5561. time += duration;
  5562. number++;
  5563. }
  5564. }
  5565. return segments;
  5566. };
  5567. const identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  5568. /**
  5569. * Replaces template identifiers with corresponding values. To be used as the callback
  5570. * for String.prototype.replace
  5571. *
  5572. * @name replaceCallback
  5573. * @function
  5574. * @param {string} match
  5575. * Entire match of identifier
  5576. * @param {string} identifier
  5577. * Name of matched identifier
  5578. * @param {string} format
  5579. * Format tag string. Its presence indicates that padding is expected
  5580. * @param {string} width
  5581. * Desired length of the replaced value. Values less than this width shall be left
  5582. * zero padded
  5583. * @return {string}
  5584. * Replacement for the matched identifier
  5585. */
  5586. /**
  5587. * Returns a function to be used as a callback for String.prototype.replace to replace
  5588. * template identifiers
  5589. *
  5590. * @param {Obect} values
  5591. * Object containing values that shall be used to replace known identifiers
  5592. * @param {number} values.RepresentationID
  5593. * Value of the Representation@id attribute
  5594. * @param {number} values.Number
  5595. * Number of the corresponding segment
  5596. * @param {number} values.Bandwidth
  5597. * Value of the Representation@bandwidth attribute.
  5598. * @param {number} values.Time
  5599. * Timestamp value of the corresponding segment
  5600. * @return {replaceCallback}
  5601. * Callback to be used with String.prototype.replace to replace identifiers
  5602. */
  5603. const identifierReplacement = values => (match, identifier, format, width) => {
  5604. if (match === '$$') {
  5605. // escape sequence
  5606. return '$';
  5607. }
  5608. if (typeof values[identifier] === 'undefined') {
  5609. return match;
  5610. }
  5611. const value = '' + values[identifier];
  5612. if (identifier === 'RepresentationID') {
  5613. // Format tag shall not be present with RepresentationID
  5614. return value;
  5615. }
  5616. if (!format) {
  5617. width = 1;
  5618. } else {
  5619. width = parseInt(width, 10);
  5620. }
  5621. if (value.length >= width) {
  5622. return value;
  5623. }
  5624. return `${new Array(width - value.length + 1).join('0')}${value}`;
  5625. };
  5626. /**
  5627. * Constructs a segment url from a template string
  5628. *
  5629. * @param {string} url
  5630. * Template string to construct url from
  5631. * @param {Obect} values
  5632. * Object containing values that shall be used to replace known identifiers
  5633. * @param {number} values.RepresentationID
  5634. * Value of the Representation@id attribute
  5635. * @param {number} values.Number
  5636. * Number of the corresponding segment
  5637. * @param {number} values.Bandwidth
  5638. * Value of the Representation@bandwidth attribute.
  5639. * @param {number} values.Time
  5640. * Timestamp value of the corresponding segment
  5641. * @return {string}
  5642. * Segment url with identifiers replaced
  5643. */
  5644. const constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));
  5645. /**
  5646. * Generates a list of objects containing timing and duration information about each
  5647. * segment needed to generate segment uris and the complete segment object
  5648. *
  5649. * @param {Object} attributes
  5650. * Object containing all inherited attributes from parent elements with attribute
  5651. * names as keys
  5652. * @param {Object[]|undefined} segmentTimeline
  5653. * List of objects representing the attributes of each S element contained within
  5654. * the SegmentTimeline element
  5655. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  5656. * List of Objects with segment timing and duration info
  5657. */
  5658. const parseTemplateInfo = (attributes, segmentTimeline) => {
  5659. if (!attributes.duration && !segmentTimeline) {
  5660. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  5661. // one media segment
  5662. return [{
  5663. number: attributes.startNumber || 1,
  5664. duration: attributes.sourceDuration,
  5665. time: 0,
  5666. timeline: attributes.periodStart
  5667. }];
  5668. }
  5669. if (attributes.duration) {
  5670. return parseByDuration(attributes);
  5671. }
  5672. return parseByTimeline(attributes, segmentTimeline);
  5673. };
  5674. /**
  5675. * Generates a list of segments using information provided by the SegmentTemplate element
  5676. *
  5677. * @param {Object} attributes
  5678. * Object containing all inherited attributes from parent elements with attribute
  5679. * names as keys
  5680. * @param {Object[]|undefined} segmentTimeline
  5681. * List of objects representing the attributes of each S element contained within
  5682. * the SegmentTimeline element
  5683. * @return {Object[]}
  5684. * List of segment objects
  5685. */
  5686. const segmentsFromTemplate = (attributes, segmentTimeline) => {
  5687. const templateValues = {
  5688. RepresentationID: attributes.id,
  5689. Bandwidth: attributes.bandwidth || 0
  5690. };
  5691. const {
  5692. initialization = {
  5693. sourceURL: '',
  5694. range: ''
  5695. }
  5696. } = attributes;
  5697. const mapSegment = urlTypeToSegment({
  5698. baseUrl: attributes.baseUrl,
  5699. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  5700. range: initialization.range
  5701. });
  5702. const segments = parseTemplateInfo(attributes, segmentTimeline);
  5703. return segments.map(segment => {
  5704. templateValues.Number = segment.number;
  5705. templateValues.Time = segment.time;
  5706. const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  5707. // - if timescale isn't present on any level, default to 1.
  5708. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  5709. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  5710. const presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is
  5711. // calculated in mpd-parser prior to this, so it's assumed to be available.
  5712. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  5713. const map = {
  5714. uri,
  5715. timeline: segment.timeline,
  5716. duration: segment.duration,
  5717. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  5718. map: mapSegment,
  5719. number: segment.number,
  5720. presentationTime
  5721. };
  5722. return map;
  5723. });
  5724. };
  5725. /**
  5726. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  5727. * to an object that matches the output of a segment in videojs/mpd-parser
  5728. *
  5729. * @param {Object} attributes
  5730. * Object containing all inherited attributes from parent elements with attribute
  5731. * names as keys
  5732. * @param {Object} segmentUrl
  5733. * <SegmentURL> node to translate into a segment object
  5734. * @return {Object} translated segment object
  5735. */
  5736. const SegmentURLToSegmentObject = (attributes, segmentUrl) => {
  5737. const {
  5738. baseUrl,
  5739. initialization = {}
  5740. } = attributes;
  5741. const initSegment = urlTypeToSegment({
  5742. baseUrl,
  5743. source: initialization.sourceURL,
  5744. range: initialization.range
  5745. });
  5746. const segment = urlTypeToSegment({
  5747. baseUrl,
  5748. source: segmentUrl.media,
  5749. range: segmentUrl.mediaRange
  5750. });
  5751. segment.map = initSegment;
  5752. return segment;
  5753. };
  5754. /**
  5755. * Generates a list of segments using information provided by the SegmentList element
  5756. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  5757. * node should be translated into segment.
  5758. *
  5759. * @param {Object} attributes
  5760. * Object containing all inherited attributes from parent elements with attribute
  5761. * names as keys
  5762. * @param {Object[]|undefined} segmentTimeline
  5763. * List of objects representing the attributes of each S element contained within
  5764. * the SegmentTimeline element
  5765. * @return {Object.<Array>} list of segments
  5766. */
  5767. const segmentsFromList = (attributes, segmentTimeline) => {
  5768. const {
  5769. duration,
  5770. segmentUrls = [],
  5771. periodStart
  5772. } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  5773. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  5774. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  5775. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  5776. }
  5777. const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));
  5778. let segmentTimeInfo;
  5779. if (duration) {
  5780. segmentTimeInfo = parseByDuration(attributes);
  5781. }
  5782. if (segmentTimeline) {
  5783. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  5784. }
  5785. const segments = segmentTimeInfo.map((segmentTime, index) => {
  5786. if (segmentUrlMap[index]) {
  5787. const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  5788. // - if timescale isn't present on any level, default to 1.
  5789. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  5790. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  5791. segment.timeline = segmentTime.timeline;
  5792. segment.duration = segmentTime.duration;
  5793. segment.number = segmentTime.number;
  5794. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  5795. return segment;
  5796. } // Since we're mapping we should get rid of any blank segments (in case
  5797. // the given SegmentTimeline is handling for more elements than we have
  5798. // SegmentURLs for).
  5799. }).filter(segment => segment);
  5800. return segments;
  5801. };
  5802. const generateSegments = ({
  5803. attributes,
  5804. segmentInfo
  5805. }) => {
  5806. let segmentAttributes;
  5807. let segmentsFn;
  5808. if (segmentInfo.template) {
  5809. segmentsFn = segmentsFromTemplate;
  5810. segmentAttributes = merge(attributes, segmentInfo.template);
  5811. } else if (segmentInfo.base) {
  5812. segmentsFn = segmentsFromBase;
  5813. segmentAttributes = merge(attributes, segmentInfo.base);
  5814. } else if (segmentInfo.list) {
  5815. segmentsFn = segmentsFromList;
  5816. segmentAttributes = merge(attributes, segmentInfo.list);
  5817. }
  5818. const segmentsInfo = {
  5819. attributes
  5820. };
  5821. if (!segmentsFn) {
  5822. return segmentsInfo;
  5823. }
  5824. const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  5825. // must be in seconds. Since we've generated the segment list, we no longer need
  5826. // @duration to be in @timescale units, so we can convert it here.
  5827. if (segmentAttributes.duration) {
  5828. const {
  5829. duration,
  5830. timescale = 1
  5831. } = segmentAttributes;
  5832. segmentAttributes.duration = duration / timescale;
  5833. } else if (segments.length) {
  5834. // if there is no @duration attribute, use the largest segment duration as
  5835. // as target duration
  5836. segmentAttributes.duration = segments.reduce((max, segment) => {
  5837. return Math.max(max, Math.ceil(segment.duration));
  5838. }, 0);
  5839. } else {
  5840. segmentAttributes.duration = 0;
  5841. }
  5842. segmentsInfo.attributes = segmentAttributes;
  5843. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  5844. if (segmentInfo.base && segmentAttributes.indexRange) {
  5845. segmentsInfo.sidx = segments[0];
  5846. segmentsInfo.segments = [];
  5847. }
  5848. return segmentsInfo;
  5849. };
  5850. const toPlaylists = representations => representations.map(generateSegments);
  5851. const findChildren = (element, name) => from(element.childNodes).filter(({
  5852. tagName
  5853. }) => tagName === name);
  5854. const getContent = element => element.textContent.trim();
  5855. /**
  5856. * Converts the provided string that may contain a division operation to a number.
  5857. *
  5858. * @param {string} value - the provided string value
  5859. *
  5860. * @return {number} the parsed string value
  5861. */
  5862. const parseDivisionValue = value => {
  5863. return parseFloat(value.split('/').reduce((prev, current) => prev / current));
  5864. };
  5865. const parseDuration = str => {
  5866. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  5867. const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  5868. const SECONDS_IN_DAY = 24 * 60 * 60;
  5869. const SECONDS_IN_HOUR = 60 * 60;
  5870. const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  5871. const durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  5872. const match = durationRegex.exec(str);
  5873. if (!match) {
  5874. return 0;
  5875. }
  5876. const [year, month, day, hour, minute, second] = match.slice(1);
  5877. return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
  5878. };
  5879. const parseDate = str => {
  5880. // Date format without timezone according to ISO 8601
  5881. // YYY-MM-DDThh:mm:ss.ssssss
  5882. const dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
  5883. // expressed by ending with 'Z'
  5884. if (dateRegex.test(str)) {
  5885. str += 'Z';
  5886. }
  5887. return Date.parse(str);
  5888. };
  5889. const parsers = {
  5890. /**
  5891. * Specifies the duration of the entire Media Presentation. Format is a duration string
  5892. * as specified in ISO 8601
  5893. *
  5894. * @param {string} value
  5895. * value of attribute as a string
  5896. * @return {number}
  5897. * The duration in seconds
  5898. */
  5899. mediaPresentationDuration(value) {
  5900. return parseDuration(value);
  5901. },
  5902. /**
  5903. * Specifies the Segment availability start time for all Segments referred to in this
  5904. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  5905. * time. Format is a date string as specified in ISO 8601
  5906. *
  5907. * @param {string} value
  5908. * value of attribute as a string
  5909. * @return {number}
  5910. * The date as seconds from unix epoch
  5911. */
  5912. availabilityStartTime(value) {
  5913. return parseDate(value) / 1000;
  5914. },
  5915. /**
  5916. * Specifies the smallest period between potential changes to the MPD. Format is a
  5917. * duration string as specified in ISO 8601
  5918. *
  5919. * @param {string} value
  5920. * value of attribute as a string
  5921. * @return {number}
  5922. * The duration in seconds
  5923. */
  5924. minimumUpdatePeriod(value) {
  5925. return parseDuration(value);
  5926. },
  5927. /**
  5928. * Specifies the suggested presentation delay. Format is a
  5929. * duration string as specified in ISO 8601
  5930. *
  5931. * @param {string} value
  5932. * value of attribute as a string
  5933. * @return {number}
  5934. * The duration in seconds
  5935. */
  5936. suggestedPresentationDelay(value) {
  5937. return parseDuration(value);
  5938. },
  5939. /**
  5940. * specifices the type of mpd. Can be either "static" or "dynamic"
  5941. *
  5942. * @param {string} value
  5943. * value of attribute as a string
  5944. *
  5945. * @return {string}
  5946. * The type as a string
  5947. */
  5948. type(value) {
  5949. return value;
  5950. },
  5951. /**
  5952. * Specifies the duration of the smallest time shifting buffer for any Representation
  5953. * in the MPD. Format is a duration string as specified in ISO 8601
  5954. *
  5955. * @param {string} value
  5956. * value of attribute as a string
  5957. * @return {number}
  5958. * The duration in seconds
  5959. */
  5960. timeShiftBufferDepth(value) {
  5961. return parseDuration(value);
  5962. },
  5963. /**
  5964. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  5965. * Format is a duration string as specified in ISO 8601
  5966. *
  5967. * @param {string} value
  5968. * value of attribute as a string
  5969. * @return {number}
  5970. * The duration in seconds
  5971. */
  5972. start(value) {
  5973. return parseDuration(value);
  5974. },
  5975. /**
  5976. * Specifies the width of the visual presentation
  5977. *
  5978. * @param {string} value
  5979. * value of attribute as a string
  5980. * @return {number}
  5981. * The parsed width
  5982. */
  5983. width(value) {
  5984. return parseInt(value, 10);
  5985. },
  5986. /**
  5987. * Specifies the height of the visual presentation
  5988. *
  5989. * @param {string} value
  5990. * value of attribute as a string
  5991. * @return {number}
  5992. * The parsed height
  5993. */
  5994. height(value) {
  5995. return parseInt(value, 10);
  5996. },
  5997. /**
  5998. * Specifies the bitrate of the representation
  5999. *
  6000. * @param {string} value
  6001. * value of attribute as a string
  6002. * @return {number}
  6003. * The parsed bandwidth
  6004. */
  6005. bandwidth(value) {
  6006. return parseInt(value, 10);
  6007. },
  6008. /**
  6009. * Specifies the frame rate of the representation
  6010. *
  6011. * @param {string} value
  6012. * value of attribute as a string
  6013. * @return {number}
  6014. * The parsed frame rate
  6015. */
  6016. frameRate(value) {
  6017. return parseDivisionValue(value);
  6018. },
  6019. /**
  6020. * Specifies the number of the first Media Segment in this Representation in the Period
  6021. *
  6022. * @param {string} value
  6023. * value of attribute as a string
  6024. * @return {number}
  6025. * The parsed number
  6026. */
  6027. startNumber(value) {
  6028. return parseInt(value, 10);
  6029. },
  6030. /**
  6031. * Specifies the timescale in units per seconds
  6032. *
  6033. * @param {string} value
  6034. * value of attribute as a string
  6035. * @return {number}
  6036. * The parsed timescale
  6037. */
  6038. timescale(value) {
  6039. return parseInt(value, 10);
  6040. },
  6041. /**
  6042. * Specifies the presentationTimeOffset.
  6043. *
  6044. * @param {string} value
  6045. * value of the attribute as a string
  6046. *
  6047. * @return {number}
  6048. * The parsed presentationTimeOffset
  6049. */
  6050. presentationTimeOffset(value) {
  6051. return parseInt(value, 10);
  6052. },
  6053. /**
  6054. * Specifies the constant approximate Segment duration
  6055. * NOTE: The <Period> element also contains an @duration attribute. This duration
  6056. * specifies the duration of the Period. This attribute is currently not
  6057. * supported by the rest of the parser, however we still check for it to prevent
  6058. * errors.
  6059. *
  6060. * @param {string} value
  6061. * value of attribute as a string
  6062. * @return {number}
  6063. * The parsed duration
  6064. */
  6065. duration(value) {
  6066. const parsedValue = parseInt(value, 10);
  6067. if (isNaN(parsedValue)) {
  6068. return parseDuration(value);
  6069. }
  6070. return parsedValue;
  6071. },
  6072. /**
  6073. * Specifies the Segment duration, in units of the value of the @timescale.
  6074. *
  6075. * @param {string} value
  6076. * value of attribute as a string
  6077. * @return {number}
  6078. * The parsed duration
  6079. */
  6080. d(value) {
  6081. return parseInt(value, 10);
  6082. },
  6083. /**
  6084. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  6085. * starts relative to the beginning of the Period
  6086. *
  6087. * @param {string} value
  6088. * value of attribute as a string
  6089. * @return {number}
  6090. * The parsed time
  6091. */
  6092. t(value) {
  6093. return parseInt(value, 10);
  6094. },
  6095. /**
  6096. * Specifies the repeat count of the number of following contiguous Segments with the
  6097. * same duration expressed by the value of @d
  6098. *
  6099. * @param {string} value
  6100. * value of attribute as a string
  6101. * @return {number}
  6102. * The parsed number
  6103. */
  6104. r(value) {
  6105. return parseInt(value, 10);
  6106. },
  6107. /**
  6108. * Default parser for all other attributes. Acts as a no-op and just returns the value
  6109. * as a string
  6110. *
  6111. * @param {string} value
  6112. * value of attribute as a string
  6113. * @return {string}
  6114. * Unparsed value
  6115. */
  6116. DEFAULT(value) {
  6117. return value;
  6118. }
  6119. };
  6120. /**
  6121. * Gets all the attributes and values of the provided node, parses attributes with known
  6122. * types, and returns an object with attribute names mapped to values.
  6123. *
  6124. * @param {Node} el
  6125. * The node to parse attributes from
  6126. * @return {Object}
  6127. * Object with all attributes of el parsed
  6128. */
  6129. const parseAttributes = el => {
  6130. if (!(el && el.attributes)) {
  6131. return {};
  6132. }
  6133. return from(el.attributes).reduce((a, e) => {
  6134. const parseFn = parsers[e.name] || parsers.DEFAULT;
  6135. a[e.name] = parseFn(e.value);
  6136. return a;
  6137. }, {});
  6138. };
  6139. const keySystemsMap = {
  6140. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  6141. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  6142. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  6143. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  6144. };
  6145. /**
  6146. * Builds a list of urls that is the product of the reference urls and BaseURL values
  6147. *
  6148. * @param {string[]} referenceUrls
  6149. * List of reference urls to resolve to
  6150. * @param {Node[]} baseUrlElements
  6151. * List of BaseURL nodes from the mpd
  6152. * @return {string[]}
  6153. * List of resolved urls
  6154. */
  6155. const buildBaseUrls = (referenceUrls, baseUrlElements) => {
  6156. if (!baseUrlElements.length) {
  6157. return referenceUrls;
  6158. }
  6159. return flatten(referenceUrls.map(function (reference) {
  6160. return baseUrlElements.map(function (baseUrlElement) {
  6161. return resolveUrl$1(reference, getContent(baseUrlElement));
  6162. });
  6163. }));
  6164. };
  6165. /**
  6166. * Contains all Segment information for its containing AdaptationSet
  6167. *
  6168. * @typedef {Object} SegmentInformation
  6169. * @property {Object|undefined} template
  6170. * Contains the attributes for the SegmentTemplate node
  6171. * @property {Object[]|undefined} segmentTimeline
  6172. * Contains a list of atrributes for each S node within the SegmentTimeline node
  6173. * @property {Object|undefined} list
  6174. * Contains the attributes for the SegmentList node
  6175. * @property {Object|undefined} base
  6176. * Contains the attributes for the SegmentBase node
  6177. */
  6178. /**
  6179. * Returns all available Segment information contained within the AdaptationSet node
  6180. *
  6181. * @param {Node} adaptationSet
  6182. * The AdaptationSet node to get Segment information from
  6183. * @return {SegmentInformation}
  6184. * The Segment information contained within the provided AdaptationSet
  6185. */
  6186. const getSegmentInformation = adaptationSet => {
  6187. const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  6188. const segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  6189. const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge({
  6190. tag: 'SegmentURL'
  6191. }, parseAttributes(s)));
  6192. const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  6193. const segmentTimelineParentNode = segmentList || segmentTemplate;
  6194. const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  6195. const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  6196. const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  6197. // @initialization and an <Initialization> node. @initialization can be templated,
  6198. // while the node can have a url and range specified. If the <SegmentTemplate> has
  6199. // both @initialization and an <Initialization> subelement we opt to override with
  6200. // the node, as this interaction is not defined in the spec.
  6201. const template = segmentTemplate && parseAttributes(segmentTemplate);
  6202. if (template && segmentInitialization) {
  6203. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  6204. } else if (template && template.initialization) {
  6205. // If it is @initialization we convert it to an object since this is the format that
  6206. // later functions will rely on for the initialization segment. This is only valid
  6207. // for <SegmentTemplate>
  6208. template.initialization = {
  6209. sourceURL: template.initialization
  6210. };
  6211. }
  6212. const segmentInfo = {
  6213. template,
  6214. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),
  6215. list: segmentList && merge(parseAttributes(segmentList), {
  6216. segmentUrls,
  6217. initialization: parseAttributes(segmentInitialization)
  6218. }),
  6219. base: segmentBase && merge(parseAttributes(segmentBase), {
  6220. initialization: parseAttributes(segmentInitialization)
  6221. })
  6222. };
  6223. Object.keys(segmentInfo).forEach(key => {
  6224. if (!segmentInfo[key]) {
  6225. delete segmentInfo[key];
  6226. }
  6227. });
  6228. return segmentInfo;
  6229. };
  6230. /**
  6231. * Contains Segment information and attributes needed to construct a Playlist object
  6232. * from a Representation
  6233. *
  6234. * @typedef {Object} RepresentationInformation
  6235. * @property {SegmentInformation} segmentInfo
  6236. * Segment information for this Representation
  6237. * @property {Object} attributes
  6238. * Inherited attributes for this Representation
  6239. */
  6240. /**
  6241. * Maps a Representation node to an object containing Segment information and attributes
  6242. *
  6243. * @name inheritBaseUrlsCallback
  6244. * @function
  6245. * @param {Node} representation
  6246. * Representation node from the mpd
  6247. * @return {RepresentationInformation}
  6248. * Representation information needed to construct a Playlist object
  6249. */
  6250. /**
  6251. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  6252. * Segment information and attributes using inherited BaseURL nodes.
  6253. *
  6254. * @param {Object} adaptationSetAttributes
  6255. * Contains attributes inherited by the AdaptationSet
  6256. * @param {string[]} adaptationSetBaseUrls
  6257. * Contains list of resolved base urls inherited by the AdaptationSet
  6258. * @param {SegmentInformation} adaptationSetSegmentInfo
  6259. * Contains Segment information for the AdaptationSet
  6260. * @return {inheritBaseUrlsCallback}
  6261. * Callback map function
  6262. */
  6263. const inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {
  6264. const repBaseUrlElements = findChildren(representation, 'BaseURL');
  6265. const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  6266. const attributes = merge(adaptationSetAttributes, parseAttributes(representation));
  6267. const representationSegmentInfo = getSegmentInformation(representation);
  6268. return repBaseUrls.map(baseUrl => {
  6269. return {
  6270. segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
  6271. attributes: merge(attributes, {
  6272. baseUrl
  6273. })
  6274. };
  6275. });
  6276. };
  6277. /**
  6278. * Tranforms a series of content protection nodes to
  6279. * an object containing pssh data by key system
  6280. *
  6281. * @param {Node[]} contentProtectionNodes
  6282. * Content protection nodes
  6283. * @return {Object}
  6284. * Object containing pssh data by key system
  6285. */
  6286. const generateKeySystemInformation = contentProtectionNodes => {
  6287. return contentProtectionNodes.reduce((acc, node) => {
  6288. const attributes = parseAttributes(node); // Although it could be argued that according to the UUID RFC spec the UUID string (a-f chars) should be generated
  6289. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  6290. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  6291. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  6292. if (attributes.schemeIdUri) {
  6293. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  6294. }
  6295. const keySystem = keySystemsMap[attributes.schemeIdUri];
  6296. if (keySystem) {
  6297. acc[keySystem] = {
  6298. attributes
  6299. };
  6300. const psshNode = findChildren(node, 'cenc:pssh')[0];
  6301. if (psshNode) {
  6302. const pssh = getContent(psshNode);
  6303. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  6304. }
  6305. }
  6306. return acc;
  6307. }, {});
  6308. }; // defined in ANSI_SCTE 214-1 2016
  6309. const parseCaptionServiceMetadata = service => {
  6310. // 608 captions
  6311. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  6312. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6313. return values.map(value => {
  6314. let channel;
  6315. let language; // default language to value
  6316. language = value;
  6317. if (/^CC\d=/.test(value)) {
  6318. [channel, language] = value.split('=');
  6319. } else if (/^CC\d$/.test(value)) {
  6320. channel = value;
  6321. }
  6322. return {
  6323. channel,
  6324. language
  6325. };
  6326. });
  6327. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  6328. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6329. return values.map(value => {
  6330. const flags = {
  6331. // service or channel number 1-63
  6332. 'channel': undefined,
  6333. // language is a 3ALPHA per ISO 639.2/B
  6334. // field is required
  6335. 'language': undefined,
  6336. // BIT 1/0 or ?
  6337. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  6338. 'aspectRatio': 1,
  6339. // BIT 1/0
  6340. // easy reader flag indicated the text is tailed to the needs of beginning readers
  6341. // default 0, or off
  6342. 'easyReader': 0,
  6343. // BIT 1/0
  6344. // If 3d metadata is present (CEA-708.1) then 1
  6345. // default 0
  6346. '3D': 0
  6347. };
  6348. if (/=/.test(value)) {
  6349. const [channel, opts = ''] = value.split('=');
  6350. flags.channel = channel;
  6351. flags.language = value;
  6352. opts.split(',').forEach(opt => {
  6353. const [name, val] = opt.split(':');
  6354. if (name === 'lang') {
  6355. flags.language = val; // er for easyReadery
  6356. } else if (name === 'er') {
  6357. flags.easyReader = Number(val); // war for wide aspect ratio
  6358. } else if (name === 'war') {
  6359. flags.aspectRatio = Number(val);
  6360. } else if (name === '3D') {
  6361. flags['3D'] = Number(val);
  6362. }
  6363. });
  6364. } else {
  6365. flags.language = value;
  6366. }
  6367. if (flags.channel) {
  6368. flags.channel = 'SERVICE' + flags.channel;
  6369. }
  6370. return flags;
  6371. });
  6372. }
  6373. };
  6374. /**
  6375. * Maps an AdaptationSet node to a list of Representation information objects
  6376. *
  6377. * @name toRepresentationsCallback
  6378. * @function
  6379. * @param {Node} adaptationSet
  6380. * AdaptationSet node from the mpd
  6381. * @return {RepresentationInformation[]}
  6382. * List of objects containing Representaion information
  6383. */
  6384. /**
  6385. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  6386. * Representation information objects
  6387. *
  6388. * @param {Object} periodAttributes
  6389. * Contains attributes inherited by the Period
  6390. * @param {string[]} periodBaseUrls
  6391. * Contains list of resolved base urls inherited by the Period
  6392. * @param {string[]} periodSegmentInfo
  6393. * Contains Segment Information at the period level
  6394. * @return {toRepresentationsCallback}
  6395. * Callback map function
  6396. */
  6397. const toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {
  6398. const adaptationSetAttributes = parseAttributes(adaptationSet);
  6399. const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  6400. const role = findChildren(adaptationSet, 'Role')[0];
  6401. const roleAttributes = {
  6402. role: parseAttributes(role)
  6403. };
  6404. let attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
  6405. const accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  6406. const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  6407. if (captionServices) {
  6408. attrs = merge(attrs, {
  6409. captionServices
  6410. });
  6411. }
  6412. const label = findChildren(adaptationSet, 'Label')[0];
  6413. if (label && label.childNodes.length) {
  6414. const labelVal = label.childNodes[0].nodeValue.trim();
  6415. attrs = merge(attrs, {
  6416. label: labelVal
  6417. });
  6418. }
  6419. const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  6420. if (Object.keys(contentProtection).length) {
  6421. attrs = merge(attrs, {
  6422. contentProtection
  6423. });
  6424. }
  6425. const segmentInfo = getSegmentInformation(adaptationSet);
  6426. const representations = findChildren(adaptationSet, 'Representation');
  6427. const adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
  6428. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  6429. };
  6430. /**
  6431. * Contains all period information for mapping nodes onto adaptation sets.
  6432. *
  6433. * @typedef {Object} PeriodInformation
  6434. * @property {Node} period.node
  6435. * Period node from the mpd
  6436. * @property {Object} period.attributes
  6437. * Parsed period attributes from node plus any added
  6438. */
  6439. /**
  6440. * Maps a PeriodInformation object to a list of Representation information objects for all
  6441. * AdaptationSet nodes contained within the Period.
  6442. *
  6443. * @name toAdaptationSetsCallback
  6444. * @function
  6445. * @param {PeriodInformation} period
  6446. * Period object containing necessary period information
  6447. * @param {number} periodStart
  6448. * Start time of the Period within the mpd
  6449. * @return {RepresentationInformation[]}
  6450. * List of objects containing Representaion information
  6451. */
  6452. /**
  6453. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  6454. * Representation information objects
  6455. *
  6456. * @param {Object} mpdAttributes
  6457. * Contains attributes inherited by the mpd
  6458. * @param {string[]} mpdBaseUrls
  6459. * Contains list of resolved base urls inherited by the mpd
  6460. * @return {toAdaptationSetsCallback}
  6461. * Callback map function
  6462. */
  6463. const toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {
  6464. const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  6465. const periodAttributes = merge(mpdAttributes, {
  6466. periodStart: period.attributes.start
  6467. });
  6468. if (typeof period.attributes.duration === 'number') {
  6469. periodAttributes.periodDuration = period.attributes.duration;
  6470. }
  6471. const adaptationSets = findChildren(period.node, 'AdaptationSet');
  6472. const periodSegmentInfo = getSegmentInformation(period.node);
  6473. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  6474. };
  6475. /**
  6476. * Gets Period@start property for a given period.
  6477. *
  6478. * @param {Object} options
  6479. * Options object
  6480. * @param {Object} options.attributes
  6481. * Period attributes
  6482. * @param {Object} [options.priorPeriodAttributes]
  6483. * Prior period attributes (if prior period is available)
  6484. * @param {string} options.mpdType
  6485. * The MPD@type these periods came from
  6486. * @return {number|null}
  6487. * The period start, or null if it's an early available period or error
  6488. */
  6489. const getPeriodStart = ({
  6490. attributes,
  6491. priorPeriodAttributes,
  6492. mpdType
  6493. }) => {
  6494. // Summary of period start time calculation from DASH spec section 5.3.2.1
  6495. //
  6496. // A period's start is the first period's start + time elapsed after playing all
  6497. // prior periods to this one. Periods continue one after the other in time (without
  6498. // gaps) until the end of the presentation.
  6499. //
  6500. // The value of Period@start should be:
  6501. // 1. if Period@start is present: value of Period@start
  6502. // 2. if previous period exists and it has @duration: previous Period@start +
  6503. // previous Period@duration
  6504. // 3. if this is first period and MPD@type is 'static': 0
  6505. // 4. in all other cases, consider the period an "early available period" (note: not
  6506. // currently supported)
  6507. // (1)
  6508. if (typeof attributes.start === 'number') {
  6509. return attributes.start;
  6510. } // (2)
  6511. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  6512. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  6513. } // (3)
  6514. if (!priorPeriodAttributes && mpdType === 'static') {
  6515. return 0;
  6516. } // (4)
  6517. // There is currently no logic for calculating the Period@start value if there is
  6518. // no Period@start or prior Period@start and Period@duration available. This is not made
  6519. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  6520. // nothing about any other resolution strategies, it's implied. Thus, this case should
  6521. // be considered an early available period, or error, and null should suffice for both
  6522. // of those cases.
  6523. return null;
  6524. };
  6525. /**
  6526. * Traverses the mpd xml tree to generate a list of Representation information objects
  6527. * that have inherited attributes from parent nodes
  6528. *
  6529. * @param {Node} mpd
  6530. * The root node of the mpd
  6531. * @param {Object} options
  6532. * Available options for inheritAttributes
  6533. * @param {string} options.manifestUri
  6534. * The uri source of the mpd
  6535. * @param {number} options.NOW
  6536. * Current time per DASH IOP. Default is current time in ms since epoch
  6537. * @param {number} options.clientOffset
  6538. * Client time difference from NOW (in milliseconds)
  6539. * @return {RepresentationInformation[]}
  6540. * List of objects containing Representation information
  6541. */
  6542. const inheritAttributes = (mpd, options = {}) => {
  6543. const {
  6544. manifestUri = '',
  6545. NOW = Date.now(),
  6546. clientOffset = 0
  6547. } = options;
  6548. const periodNodes = findChildren(mpd, 'Period');
  6549. if (!periodNodes.length) {
  6550. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  6551. }
  6552. const locations = findChildren(mpd, 'Location');
  6553. const mpdAttributes = parseAttributes(mpd);
  6554. const mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  6555. mpdAttributes.type = mpdAttributes.type || 'static';
  6556. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  6557. mpdAttributes.NOW = NOW;
  6558. mpdAttributes.clientOffset = clientOffset;
  6559. if (locations.length) {
  6560. mpdAttributes.locations = locations.map(getContent);
  6561. }
  6562. const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  6563. // adding properties that require looking at prior periods is to parse attributes and add
  6564. // missing ones before toAdaptationSets is called. If more such properties are added, it
  6565. // may be better to refactor toAdaptationSets.
  6566. periodNodes.forEach((node, index) => {
  6567. const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  6568. // for this period.
  6569. const priorPeriod = periods[index - 1];
  6570. attributes.start = getPeriodStart({
  6571. attributes,
  6572. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  6573. mpdType: mpdAttributes.type
  6574. });
  6575. periods.push({
  6576. node,
  6577. attributes
  6578. });
  6579. });
  6580. return {
  6581. locations: mpdAttributes.locations,
  6582. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  6583. };
  6584. };
  6585. const stringToMpdXml = manifestString => {
  6586. if (manifestString === '') {
  6587. throw new Error(errors.DASH_EMPTY_MANIFEST);
  6588. }
  6589. const parser = new xmldom.DOMParser();
  6590. let xml;
  6591. let mpd;
  6592. try {
  6593. xml = parser.parseFromString(manifestString, 'application/xml');
  6594. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  6595. } catch (e) {// ie 11 throwsw on invalid xml
  6596. }
  6597. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  6598. throw new Error(errors.DASH_INVALID_XML);
  6599. }
  6600. return mpd;
  6601. };
  6602. /**
  6603. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  6604. *
  6605. * @param {string} mpd
  6606. * XML string of the MPD manifest
  6607. * @return {Object|null}
  6608. * Attributes of UTCTiming node specified in the manifest. Null if none found
  6609. */
  6610. const parseUTCTimingScheme = mpd => {
  6611. const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  6612. if (!UTCTimingNode) {
  6613. return null;
  6614. }
  6615. const attributes = parseAttributes(UTCTimingNode);
  6616. switch (attributes.schemeIdUri) {
  6617. case 'urn:mpeg:dash:utc:http-head:2014':
  6618. case 'urn:mpeg:dash:utc:http-head:2012':
  6619. attributes.method = 'HEAD';
  6620. break;
  6621. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  6622. case 'urn:mpeg:dash:utc:http-iso:2014':
  6623. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  6624. case 'urn:mpeg:dash:utc:http-iso:2012':
  6625. attributes.method = 'GET';
  6626. break;
  6627. case 'urn:mpeg:dash:utc:direct:2014':
  6628. case 'urn:mpeg:dash:utc:direct:2012':
  6629. attributes.method = 'DIRECT';
  6630. attributes.value = Date.parse(attributes.value);
  6631. break;
  6632. case 'urn:mpeg:dash:utc:http-ntp:2014':
  6633. case 'urn:mpeg:dash:utc:ntp:2014':
  6634. case 'urn:mpeg:dash:utc:sntp:2014':
  6635. default:
  6636. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  6637. }
  6638. return attributes;
  6639. };
  6640. /*
  6641. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  6642. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  6643. *
  6644. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  6645. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  6646. * updated to reflect its position relative to the prior manifest.
  6647. *
  6648. * @param {string} manifestString - the DASH manifest as a string
  6649. * @param {options} [options] - any options
  6650. *
  6651. * @return {Object} the manifest object
  6652. */
  6653. const parse = (manifestString, options = {}) => {
  6654. const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  6655. const playlists = toPlaylists(parsedManifestInfo.representationInfo);
  6656. return toM3u8({
  6657. dashPlaylists: playlists,
  6658. locations: parsedManifestInfo.locations,
  6659. sidxMapping: options.sidxMapping,
  6660. previousManifest: options.previousManifest
  6661. });
  6662. };
  6663. /**
  6664. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  6665. *
  6666. * @param {string} manifestString
  6667. * XML string of the MPD manifest
  6668. * @return {Object|null}
  6669. * Attributes of UTCTiming node specified in the manifest. Null if none found
  6670. */
  6671. const parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));
  6672. var MAX_UINT32 = Math.pow(2, 32);
  6673. var getUint64$1 = function (uint8) {
  6674. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  6675. var value;
  6676. if (dv.getBigUint64) {
  6677. value = dv.getBigUint64(0);
  6678. if (value < Number.MAX_SAFE_INTEGER) {
  6679. return Number(value);
  6680. }
  6681. return value;
  6682. }
  6683. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  6684. };
  6685. var numbers = {
  6686. getUint64: getUint64$1,
  6687. MAX_UINT32: MAX_UINT32
  6688. };
  6689. var getUint64 = numbers.getUint64;
  6690. var parseSidx = function (data) {
  6691. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  6692. result = {
  6693. version: data[0],
  6694. flags: new Uint8Array(data.subarray(1, 4)),
  6695. references: [],
  6696. referenceId: view.getUint32(4),
  6697. timescale: view.getUint32(8)
  6698. },
  6699. i = 12;
  6700. if (result.version === 0) {
  6701. result.earliestPresentationTime = view.getUint32(i);
  6702. result.firstOffset = view.getUint32(i + 4);
  6703. i += 8;
  6704. } else {
  6705. // read 64 bits
  6706. result.earliestPresentationTime = getUint64(data.subarray(i));
  6707. result.firstOffset = getUint64(data.subarray(i + 8));
  6708. i += 16;
  6709. }
  6710. i += 2; // reserved
  6711. var referenceCount = view.getUint16(i);
  6712. i += 2; // start of references
  6713. for (; referenceCount > 0; i += 12, referenceCount--) {
  6714. result.references.push({
  6715. referenceType: (data[i] & 0x80) >>> 7,
  6716. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  6717. subsegmentDuration: view.getUint32(i + 4),
  6718. startsWithSap: !!(data[i + 8] & 0x80),
  6719. sapType: (data[i + 8] & 0x70) >>> 4,
  6720. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  6721. });
  6722. }
  6723. return result;
  6724. };
  6725. var parseSidx_1 = parseSidx;
  6726. var ID3 = toUint8([0x49, 0x44, 0x33]);
  6727. var getId3Size = function getId3Size(bytes, offset) {
  6728. if (offset === void 0) {
  6729. offset = 0;
  6730. }
  6731. bytes = toUint8(bytes);
  6732. var flags = bytes[offset + 5];
  6733. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  6734. var footerPresent = (flags & 16) >> 4;
  6735. if (footerPresent) {
  6736. return returnSize + 20;
  6737. }
  6738. return returnSize + 10;
  6739. };
  6740. var getId3Offset = function getId3Offset(bytes, offset) {
  6741. if (offset === void 0) {
  6742. offset = 0;
  6743. }
  6744. bytes = toUint8(bytes);
  6745. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  6746. offset: offset
  6747. })) {
  6748. return offset;
  6749. }
  6750. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  6751. // have multiple ID3 tag sections even though
  6752. // they should not.
  6753. return getId3Offset(bytes, offset);
  6754. };
  6755. var normalizePath$1 = function normalizePath(path) {
  6756. if (typeof path === 'string') {
  6757. return stringToBytes(path);
  6758. }
  6759. if (typeof path === 'number') {
  6760. return path;
  6761. }
  6762. return path;
  6763. };
  6764. var normalizePaths$1 = function normalizePaths(paths) {
  6765. if (!Array.isArray(paths)) {
  6766. return [normalizePath$1(paths)];
  6767. }
  6768. return paths.map(function (p) {
  6769. return normalizePath$1(p);
  6770. });
  6771. };
  6772. /**
  6773. * find any number of boxes by name given a path to it in an iso bmff
  6774. * such as mp4.
  6775. *
  6776. * @param {TypedArray} bytes
  6777. * bytes for the iso bmff to search for boxes in
  6778. *
  6779. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  6780. * An array of paths or a single path representing the name
  6781. * of boxes to search through in bytes. Paths may be
  6782. * uint8 (character codes) or strings.
  6783. *
  6784. * @param {boolean} [complete=false]
  6785. * Should we search only for complete boxes on the final path.
  6786. * This is very useful when you do not want to get back partial boxes
  6787. * in the case of streaming files.
  6788. *
  6789. * @return {Uint8Array[]}
  6790. * An array of the end paths that we found.
  6791. */
  6792. var findBox = function findBox(bytes, paths, complete) {
  6793. if (complete === void 0) {
  6794. complete = false;
  6795. }
  6796. paths = normalizePaths$1(paths);
  6797. bytes = toUint8(bytes);
  6798. var results = [];
  6799. if (!paths.length) {
  6800. // short-circuit the search for empty paths
  6801. return results;
  6802. }
  6803. var i = 0;
  6804. while (i < bytes.length) {
  6805. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  6806. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  6807. if (size === 0) {
  6808. break;
  6809. }
  6810. var end = i + size;
  6811. if (end > bytes.length) {
  6812. // this box is bigger than the number of bytes we have
  6813. // and complete is set, we cannot find any more boxes.
  6814. if (complete) {
  6815. break;
  6816. }
  6817. end = bytes.length;
  6818. }
  6819. var data = bytes.subarray(i + 8, end);
  6820. if (bytesMatch(type, paths[0])) {
  6821. if (paths.length === 1) {
  6822. // this is the end of the path and we've found the box we were
  6823. // looking for
  6824. results.push(data);
  6825. } else {
  6826. // recursively search for the next box along the path
  6827. results.push.apply(results, findBox(data, paths.slice(1), complete));
  6828. }
  6829. }
  6830. i = end;
  6831. } // we've finished searching all of bytes
  6832. return results;
  6833. };
  6834. // https://matroska-org.github.io/libebml/specs.html
  6835. // https://www.matroska.org/technical/elements.html
  6836. // https://www.webmproject.org/docs/container/
  6837. var EBML_TAGS = {
  6838. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  6839. DocType: toUint8([0x42, 0x82]),
  6840. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  6841. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  6842. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  6843. Track: toUint8([0xAE]),
  6844. TrackNumber: toUint8([0xd7]),
  6845. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  6846. TrackEntry: toUint8([0xAE]),
  6847. TrackType: toUint8([0x83]),
  6848. FlagDefault: toUint8([0x88]),
  6849. CodecID: toUint8([0x86]),
  6850. CodecPrivate: toUint8([0x63, 0xA2]),
  6851. VideoTrack: toUint8([0xe0]),
  6852. AudioTrack: toUint8([0xe1]),
  6853. // Not used yet, but will be used for live webm/mkv
  6854. // see https://www.matroska.org/technical/basics.html#block-structure
  6855. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  6856. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  6857. Timestamp: toUint8([0xE7]),
  6858. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  6859. BlockGroup: toUint8([0xA0]),
  6860. BlockDuration: toUint8([0x9B]),
  6861. Block: toUint8([0xA1]),
  6862. SimpleBlock: toUint8([0xA3])
  6863. };
  6864. /**
  6865. * This is a simple table to determine the length
  6866. * of things in ebml. The length is one based (starts at 1,
  6867. * rather than zero) and for every zero bit before a one bit
  6868. * we add one to length. We also need this table because in some
  6869. * case we have to xor all the length bits from another value.
  6870. */
  6871. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  6872. var getLength = function getLength(byte) {
  6873. var len = 1;
  6874. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  6875. if (byte & LENGTH_TABLE[i]) {
  6876. break;
  6877. }
  6878. len++;
  6879. }
  6880. return len;
  6881. }; // length in ebml is stored in the first 4 to 8 bits
  6882. // of the first byte. 4 for the id length and 8 for the
  6883. // data size length. Length is measured by converting the number to binary
  6884. // then 1 + the number of zeros before a 1 is encountered starting
  6885. // from the left.
  6886. var getvint = function getvint(bytes, offset, removeLength, signed) {
  6887. if (removeLength === void 0) {
  6888. removeLength = true;
  6889. }
  6890. if (signed === void 0) {
  6891. signed = false;
  6892. }
  6893. var length = getLength(bytes[offset]);
  6894. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  6895. // as they will be modified below to remove the dataSizeLen bits and we do not
  6896. // want to modify the original data. normally we could just call slice on
  6897. // uint8array but ie 11 does not support that...
  6898. if (removeLength) {
  6899. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  6900. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  6901. }
  6902. return {
  6903. length: length,
  6904. value: bytesToNumber(valueBytes, {
  6905. signed: signed
  6906. }),
  6907. bytes: valueBytes
  6908. };
  6909. };
  6910. var normalizePath = function normalizePath(path) {
  6911. if (typeof path === 'string') {
  6912. return path.match(/.{1,2}/g).map(function (p) {
  6913. return normalizePath(p);
  6914. });
  6915. }
  6916. if (typeof path === 'number') {
  6917. return numberToBytes(path);
  6918. }
  6919. return path;
  6920. };
  6921. var normalizePaths = function normalizePaths(paths) {
  6922. if (!Array.isArray(paths)) {
  6923. return [normalizePath(paths)];
  6924. }
  6925. return paths.map(function (p) {
  6926. return normalizePath(p);
  6927. });
  6928. };
  6929. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  6930. if (offset >= bytes.length) {
  6931. return bytes.length;
  6932. }
  6933. var innerid = getvint(bytes, offset, false);
  6934. if (bytesMatch(id.bytes, innerid.bytes)) {
  6935. return offset;
  6936. }
  6937. var dataHeader = getvint(bytes, offset + innerid.length);
  6938. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  6939. };
  6940. /**
  6941. * Notes on the EBLM format.
  6942. *
  6943. * EBLM uses "vints" tags. Every vint tag contains
  6944. * two parts
  6945. *
  6946. * 1. The length from the first byte. You get this by
  6947. * converting the byte to binary and counting the zeros
  6948. * before a 1. Then you add 1 to that. Examples
  6949. * 00011111 = length 4 because there are 3 zeros before a 1.
  6950. * 00100000 = length 3 because there are 2 zeros before a 1.
  6951. * 00000011 = length 7 because there are 6 zeros before a 1.
  6952. *
  6953. * 2. The bits used for length are removed from the first byte
  6954. * Then all the bytes are merged into a value. NOTE: this
  6955. * is not the case for id ebml tags as there id includes
  6956. * length bits.
  6957. *
  6958. */
  6959. var findEbml = function findEbml(bytes, paths) {
  6960. paths = normalizePaths(paths);
  6961. bytes = toUint8(bytes);
  6962. var results = [];
  6963. if (!paths.length) {
  6964. return results;
  6965. }
  6966. var i = 0;
  6967. while (i < bytes.length) {
  6968. var id = getvint(bytes, i, false);
  6969. var dataHeader = getvint(bytes, i + id.length);
  6970. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  6971. if (dataHeader.value === 0x7f) {
  6972. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  6973. if (dataHeader.value !== bytes.length) {
  6974. dataHeader.value -= dataStart;
  6975. }
  6976. }
  6977. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  6978. var data = bytes.subarray(dataStart, dataEnd);
  6979. if (bytesMatch(paths[0], id.bytes)) {
  6980. if (paths.length === 1) {
  6981. // this is the end of the paths and we've found the tag we were
  6982. // looking for
  6983. results.push(data);
  6984. } else {
  6985. // recursively search for the next tag inside of the data
  6986. // of this one
  6987. results = results.concat(findEbml(data, paths.slice(1)));
  6988. }
  6989. }
  6990. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  6991. i += totalLength;
  6992. }
  6993. return results;
  6994. }; // see https://www.matroska.org/technical/basics.html#block-structure
  6995. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  6996. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  6997. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  6998. /**
  6999. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  7000. * Sequence Payload"
  7001. *
  7002. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  7003. * unit
  7004. * @return {Uint8Array} the RBSP without any Emulation
  7005. * Prevention Bytes
  7006. */
  7007. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  7008. var positions = [];
  7009. var i = 1; // Find all `Emulation Prevention Bytes`
  7010. while (i < bytes.length - 2) {
  7011. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  7012. positions.push(i + 2);
  7013. i++;
  7014. }
  7015. i++;
  7016. } // If no Emulation Prevention Bytes were found just return the original
  7017. // array
  7018. if (positions.length === 0) {
  7019. return bytes;
  7020. } // Create a new array to hold the NAL unit data
  7021. var newLength = bytes.length - positions.length;
  7022. var newData = new Uint8Array(newLength);
  7023. var sourceIndex = 0;
  7024. for (i = 0; i < newLength; sourceIndex++, i++) {
  7025. if (sourceIndex === positions[0]) {
  7026. // Skip this byte
  7027. sourceIndex++; // Remove this position index
  7028. positions.shift();
  7029. }
  7030. newData[i] = bytes[sourceIndex];
  7031. }
  7032. return newData;
  7033. };
  7034. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  7035. if (nalLimit === void 0) {
  7036. nalLimit = Infinity;
  7037. }
  7038. bytes = toUint8(bytes);
  7039. types = [].concat(types);
  7040. var i = 0;
  7041. var nalStart;
  7042. var nalsFound = 0; // keep searching until:
  7043. // we reach the end of bytes
  7044. // we reach the maximum number of nals they want to seach
  7045. // NOTE: that we disregard nalLimit when we have found the start
  7046. // of the nal we want so that we can find the end of the nal we want.
  7047. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  7048. var nalOffset = void 0;
  7049. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  7050. nalOffset = 4;
  7051. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  7052. nalOffset = 3;
  7053. } // we are unsynced,
  7054. // find the next nal unit
  7055. if (!nalOffset) {
  7056. i++;
  7057. continue;
  7058. }
  7059. nalsFound++;
  7060. if (nalStart) {
  7061. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  7062. }
  7063. var nalType = void 0;
  7064. if (dataType === 'h264') {
  7065. nalType = bytes[i + nalOffset] & 0x1f;
  7066. } else if (dataType === 'h265') {
  7067. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  7068. }
  7069. if (types.indexOf(nalType) !== -1) {
  7070. nalStart = i + nalOffset;
  7071. } // nal header is 1 length for h264, and 2 for h265
  7072. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  7073. }
  7074. return bytes.subarray(0, 0);
  7075. };
  7076. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  7077. return findNal(bytes, 'h264', type, nalLimit);
  7078. };
  7079. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  7080. return findNal(bytes, 'h265', type, nalLimit);
  7081. };
  7082. var CONSTANTS = {
  7083. // "webm" string literal in hex
  7084. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  7085. // "matroska" string literal in hex
  7086. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  7087. // "fLaC" string literal in hex
  7088. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  7089. // "OggS" string literal in hex
  7090. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  7091. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  7092. // of ac-3
  7093. 'ac3': toUint8([0x0b, 0x77]),
  7094. // "RIFF" string literal in hex used for wav and avi
  7095. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  7096. // "AVI" string literal in hex
  7097. 'avi': toUint8([0x41, 0x56, 0x49]),
  7098. // "WAVE" string literal in hex
  7099. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  7100. // "ftyp3g" string literal in hex
  7101. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  7102. // "ftyp" string literal in hex
  7103. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  7104. // "styp" string literal in hex
  7105. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  7106. // "ftypqt" string literal in hex
  7107. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  7108. // moov string literal in hex
  7109. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  7110. // moof string literal in hex
  7111. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  7112. };
  7113. var _isLikely = {
  7114. aac: function aac(bytes) {
  7115. var offset = getId3Offset(bytes);
  7116. return bytesMatch(bytes, [0xFF, 0x10], {
  7117. offset: offset,
  7118. mask: [0xFF, 0x16]
  7119. });
  7120. },
  7121. mp3: function mp3(bytes) {
  7122. var offset = getId3Offset(bytes);
  7123. return bytesMatch(bytes, [0xFF, 0x02], {
  7124. offset: offset,
  7125. mask: [0xFF, 0x06]
  7126. });
  7127. },
  7128. webm: function webm(bytes) {
  7129. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  7130. return bytesMatch(docType, CONSTANTS.webm);
  7131. },
  7132. mkv: function mkv(bytes) {
  7133. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  7134. return bytesMatch(docType, CONSTANTS.matroska);
  7135. },
  7136. mp4: function mp4(bytes) {
  7137. // if this file is another base media file format, it is not mp4
  7138. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  7139. return false;
  7140. } // if this file starts with a ftyp or styp box its mp4
  7141. if (bytesMatch(bytes, CONSTANTS.mp4, {
  7142. offset: 4
  7143. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  7144. offset: 4
  7145. })) {
  7146. return true;
  7147. } // if this file starts with a moof/moov box its mp4
  7148. if (bytesMatch(bytes, CONSTANTS.moof, {
  7149. offset: 4
  7150. }) || bytesMatch(bytes, CONSTANTS.moov, {
  7151. offset: 4
  7152. })) {
  7153. return true;
  7154. }
  7155. },
  7156. mov: function mov(bytes) {
  7157. return bytesMatch(bytes, CONSTANTS.mov, {
  7158. offset: 4
  7159. });
  7160. },
  7161. '3gp': function gp(bytes) {
  7162. return bytesMatch(bytes, CONSTANTS['3gp'], {
  7163. offset: 4
  7164. });
  7165. },
  7166. ac3: function ac3(bytes) {
  7167. var offset = getId3Offset(bytes);
  7168. return bytesMatch(bytes, CONSTANTS.ac3, {
  7169. offset: offset
  7170. });
  7171. },
  7172. ts: function ts(bytes) {
  7173. if (bytes.length < 189 && bytes.length >= 1) {
  7174. return bytes[0] === 0x47;
  7175. }
  7176. var i = 0; // check the first 376 bytes for two matching sync bytes
  7177. while (i + 188 < bytes.length && i < 188) {
  7178. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  7179. return true;
  7180. }
  7181. i += 1;
  7182. }
  7183. return false;
  7184. },
  7185. flac: function flac(bytes) {
  7186. var offset = getId3Offset(bytes);
  7187. return bytesMatch(bytes, CONSTANTS.flac, {
  7188. offset: offset
  7189. });
  7190. },
  7191. ogg: function ogg(bytes) {
  7192. return bytesMatch(bytes, CONSTANTS.ogg);
  7193. },
  7194. avi: function avi(bytes) {
  7195. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  7196. offset: 8
  7197. });
  7198. },
  7199. wav: function wav(bytes) {
  7200. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  7201. offset: 8
  7202. });
  7203. },
  7204. 'h264': function h264(bytes) {
  7205. // find seq_parameter_set_rbsp
  7206. return findH264Nal(bytes, 7, 3).length;
  7207. },
  7208. 'h265': function h265(bytes) {
  7209. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  7210. return findH265Nal(bytes, [32, 33], 3).length;
  7211. }
  7212. }; // get all the isLikely functions
  7213. // but make sure 'ts' is above h264 and h265
  7214. // but below everything else as it is the least specific
  7215. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  7216. .filter(function (t) {
  7217. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  7218. }) // add it back to the bottom
  7219. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  7220. isLikelyTypes.forEach(function (type) {
  7221. var isLikelyFn = _isLikely[type];
  7222. _isLikely[type] = function (bytes) {
  7223. return isLikelyFn(toUint8(bytes));
  7224. };
  7225. }); // export after wrapping
  7226. var isLikely = _isLikely; // A useful list of file signatures can be found here
  7227. // https://en.wikipedia.org/wiki/List_of_file_signatures
  7228. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  7229. bytes = toUint8(bytes);
  7230. for (var i = 0; i < isLikelyTypes.length; i++) {
  7231. var type = isLikelyTypes[i];
  7232. if (isLikely[type](bytes)) {
  7233. return type;
  7234. }
  7235. }
  7236. return '';
  7237. }; // fmp4 is not a container
  7238. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  7239. return findBox(bytes, ['moof']).length > 0;
  7240. };
  7241. // which will only happen if the request is complete.
  7242. const callbackOnCompleted = (request, cb) => {
  7243. if (request.readyState === 4) {
  7244. return cb();
  7245. }
  7246. return;
  7247. };
  7248. const containerRequest = (uri, xhr, cb) => {
  7249. let bytes = [];
  7250. let id3Offset;
  7251. let finished = false;
  7252. const endRequestAndCallback = function (err, req, type, _bytes) {
  7253. req.abort();
  7254. finished = true;
  7255. return cb(err, req, type, _bytes);
  7256. };
  7257. const progressListener = function (error, request) {
  7258. if (finished) {
  7259. return;
  7260. }
  7261. if (error) {
  7262. return endRequestAndCallback(error, request, '', bytes);
  7263. } // grap the new part of content that was just downloaded
  7264. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  7265. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  7266. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  7267. // or we need at least two bytes after an id3Offset
  7268. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  7269. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7270. }
  7271. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  7272. // to see the second sync byte, wait until we have enough data
  7273. // before declaring it ts
  7274. if (type === 'ts' && bytes.length < 188) {
  7275. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7276. } // this may be an unsynced ts segment
  7277. // wait for 376 bytes before detecting no container
  7278. if (!type && bytes.length < 376) {
  7279. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7280. }
  7281. return endRequestAndCallback(null, request, type, bytes);
  7282. };
  7283. const options = {
  7284. uri,
  7285. beforeSend(request) {
  7286. // this forces the browser to pass the bytes to us unprocessed
  7287. request.overrideMimeType('text/plain; charset=x-user-defined');
  7288. request.addEventListener('progress', function ({
  7289. total,
  7290. loaded
  7291. }) {
  7292. return callbackWrapper(request, null, {
  7293. statusCode: request.status
  7294. }, progressListener);
  7295. });
  7296. }
  7297. };
  7298. const request = xhr(options, function (error, response) {
  7299. return callbackWrapper(request, error, response, progressListener);
  7300. });
  7301. return request;
  7302. };
  7303. const {
  7304. EventTarget
  7305. } = videojs__default["default"];
  7306. const dashPlaylistUnchanged = function (a, b) {
  7307. if (!isPlaylistUnchanged(a, b)) {
  7308. return false;
  7309. } // for dash the above check will often return true in scenarios where
  7310. // the playlist actually has changed because mediaSequence isn't a
  7311. // dash thing, and we often set it to 1. So if the playlists have the same amount
  7312. // of segments we return true.
  7313. // So for dash we need to make sure that the underlying segments are different.
  7314. // if sidx changed then the playlists are different.
  7315. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  7316. return false;
  7317. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  7318. return false;
  7319. } // one or the other does not have segments
  7320. // there was a change.
  7321. if (a.segments && !b.segments || !a.segments && b.segments) {
  7322. return false;
  7323. } // neither has segments nothing changed
  7324. if (!a.segments && !b.segments) {
  7325. return true;
  7326. } // check segments themselves
  7327. for (let i = 0; i < a.segments.length; i++) {
  7328. const aSegment = a.segments[i];
  7329. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  7330. if (aSegment.uri !== bSegment.uri) {
  7331. return false;
  7332. } // neither segment has a byterange, there will be no byterange change.
  7333. if (!aSegment.byterange && !bSegment.byterange) {
  7334. continue;
  7335. }
  7336. const aByterange = aSegment.byterange;
  7337. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  7338. if (aByterange && !bByterange || !aByterange && bByterange) {
  7339. return false;
  7340. } // if both segments have byterange with different offsets, there was a change.
  7341. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  7342. return false;
  7343. }
  7344. } // if everything was the same with segments, this is the same playlist.
  7345. return true;
  7346. };
  7347. /**
  7348. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  7349. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  7350. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  7351. * periods without continuous playback this function may need modification as well as the parser.
  7352. */
  7353. const dashGroupId = (type, group, label, playlist) => {
  7354. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  7355. const playlistId = playlist.attributes.NAME || label;
  7356. return `placeholder-uri-${type}-${group}-${playlistId}`;
  7357. };
  7358. /**
  7359. * Parses the main XML string and updates playlist URI references.
  7360. *
  7361. * @param {Object} config
  7362. * Object of arguments
  7363. * @param {string} config.mainXml
  7364. * The mpd XML
  7365. * @param {string} config.srcUrl
  7366. * The mpd URL
  7367. * @param {Date} config.clientOffset
  7368. * A time difference between server and client
  7369. * @param {Object} config.sidxMapping
  7370. * SIDX mappings for moof/mdat URIs and byte ranges
  7371. * @return {Object}
  7372. * The parsed mpd manifest object
  7373. */
  7374. const parseMainXml = ({
  7375. mainXml,
  7376. srcUrl,
  7377. clientOffset,
  7378. sidxMapping,
  7379. previousManifest
  7380. }) => {
  7381. const manifest = parse(mainXml, {
  7382. manifestUri: srcUrl,
  7383. clientOffset,
  7384. sidxMapping,
  7385. previousManifest
  7386. });
  7387. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  7388. return manifest;
  7389. };
  7390. /**
  7391. * Removes any mediaGroup labels that no longer exist in the newMain
  7392. *
  7393. * @param {Object} update
  7394. * The previous mpd object being updated
  7395. * @param {Object} newMain
  7396. * The new mpd object
  7397. */
  7398. const removeOldMediaGroupLabels = (update, newMain) => {
  7399. forEachMediaGroup$1(update, (properties, type, group, label) => {
  7400. if (!(label in newMain.mediaGroups[type][group])) {
  7401. delete update.mediaGroups[type][group][label];
  7402. }
  7403. });
  7404. };
  7405. /**
  7406. * Returns a new main manifest that is the result of merging an updated main manifest
  7407. * into the original version.
  7408. *
  7409. * @param {Object} oldMain
  7410. * The old parsed mpd object
  7411. * @param {Object} newMain
  7412. * The updated parsed mpd object
  7413. * @return {Object}
  7414. * A new object representing the original main manifest with the updated media
  7415. * playlists merged in
  7416. */
  7417. const updateMain = (oldMain, newMain, sidxMapping) => {
  7418. let noChanges = true;
  7419. let update = merge$1(oldMain, {
  7420. // These are top level properties that can be updated
  7421. duration: newMain.duration,
  7422. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  7423. timelineStarts: newMain.timelineStarts
  7424. }); // First update the playlists in playlist list
  7425. for (let i = 0; i < newMain.playlists.length; i++) {
  7426. const playlist = newMain.playlists[i];
  7427. if (playlist.sidx) {
  7428. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  7429. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  7430. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  7431. }
  7432. }
  7433. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  7434. if (playlistUpdate) {
  7435. update = playlistUpdate;
  7436. noChanges = false;
  7437. }
  7438. } // Then update media group playlists
  7439. forEachMediaGroup$1(newMain, (properties, type, group, label) => {
  7440. if (properties.playlists && properties.playlists.length) {
  7441. const id = properties.playlists[0].id;
  7442. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  7443. if (playlistUpdate) {
  7444. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  7445. if (!(label in update.mediaGroups[type][group])) {
  7446. update.mediaGroups[type][group][label] = properties;
  7447. } // update the playlist reference within media groups
  7448. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  7449. noChanges = false;
  7450. }
  7451. }
  7452. }); // remove mediaGroup labels and references that no longer exist in the newMain
  7453. removeOldMediaGroupLabels(update, newMain);
  7454. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  7455. noChanges = false;
  7456. }
  7457. if (noChanges) {
  7458. return null;
  7459. }
  7460. return update;
  7461. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  7462. // If the SIDXs have maps, the two maps should match,
  7463. // both `a` and `b` missing SIDXs is considered matching.
  7464. // If `a` or `b` but not both have a map, they aren't matching.
  7465. const equivalentSidx = (a, b) => {
  7466. const neitherMap = Boolean(!a.map && !b.map);
  7467. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  7468. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  7469. }; // exported for testing
  7470. const compareSidxEntry = (playlists, oldSidxMapping) => {
  7471. const newSidxMapping = {};
  7472. for (const id in playlists) {
  7473. const playlist = playlists[id];
  7474. const currentSidxInfo = playlist.sidx;
  7475. if (currentSidxInfo) {
  7476. const key = generateSidxKey(currentSidxInfo);
  7477. if (!oldSidxMapping[key]) {
  7478. break;
  7479. }
  7480. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  7481. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  7482. newSidxMapping[key] = oldSidxMapping[key];
  7483. }
  7484. }
  7485. }
  7486. return newSidxMapping;
  7487. };
  7488. /**
  7489. * A function that filters out changed items as they need to be requested separately.
  7490. *
  7491. * The method is exported for testing
  7492. *
  7493. * @param {Object} main the parsed mpd XML returned via mpd-parser
  7494. * @param {Object} oldSidxMapping the SIDX to compare against
  7495. */
  7496. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  7497. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  7498. let mediaGroupSidx = videoSidx;
  7499. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  7500. if (properties.playlists && properties.playlists.length) {
  7501. const playlists = properties.playlists;
  7502. mediaGroupSidx = merge$1(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  7503. }
  7504. });
  7505. return mediaGroupSidx;
  7506. };
  7507. class DashPlaylistLoader extends EventTarget {
  7508. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  7509. // playlist loader setups from media groups will expect to be able to pass a playlist
  7510. // (since there aren't external URLs to media playlists with DASH)
  7511. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  7512. super();
  7513. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  7514. if (!mainPlaylistLoader) {
  7515. this.isMain_ = true;
  7516. }
  7517. const {
  7518. withCredentials = false
  7519. } = options;
  7520. this.vhs_ = vhs;
  7521. this.withCredentials = withCredentials;
  7522. if (!srcUrlOrPlaylist) {
  7523. throw new Error('A non-empty playlist URL or object is required');
  7524. } // event naming?
  7525. this.on('minimumUpdatePeriod', () => {
  7526. this.refreshXml_();
  7527. }); // live playlist staleness timeout
  7528. this.on('mediaupdatetimeout', () => {
  7529. this.refreshMedia_(this.media().id);
  7530. });
  7531. this.state = 'HAVE_NOTHING';
  7532. this.loadedPlaylists_ = {};
  7533. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  7534. // The mainPlaylistLoader will be created with a string
  7535. if (this.isMain_) {
  7536. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  7537. // once multi-period is refactored
  7538. this.mainPlaylistLoader_.sidxMapping_ = {};
  7539. } else {
  7540. this.childPlaylist_ = srcUrlOrPlaylist;
  7541. }
  7542. }
  7543. requestErrored_(err, request, startingState) {
  7544. // disposed
  7545. if (!this.request) {
  7546. return true;
  7547. } // pending request is cleared
  7548. this.request = null;
  7549. if (err) {
  7550. // use the provided error object or create one
  7551. // based on the request/response
  7552. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  7553. status: request.status,
  7554. message: 'DASH request error at URL: ' + request.uri,
  7555. response: request.response,
  7556. // MEDIA_ERR_NETWORK
  7557. code: 2
  7558. };
  7559. if (startingState) {
  7560. this.state = startingState;
  7561. }
  7562. this.trigger('error');
  7563. return true;
  7564. }
  7565. }
  7566. /**
  7567. * Verify that the container of the sidx segment can be parsed
  7568. * and if it can, get and parse that segment.
  7569. */
  7570. addSidxSegments_(playlist, startingState, cb) {
  7571. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  7572. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  7573. // keep this function async
  7574. this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
  7575. return;
  7576. } // resolve the segment URL relative to the playlist
  7577. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  7578. const fin = (err, request) => {
  7579. if (this.requestErrored_(err, request, startingState)) {
  7580. return;
  7581. }
  7582. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  7583. let sidx;
  7584. try {
  7585. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  7586. } catch (e) {
  7587. // sidx parsing failed.
  7588. this.requestErrored_(e, request, startingState);
  7589. return;
  7590. }
  7591. sidxMapping[sidxKey] = {
  7592. sidxInfo: playlist.sidx,
  7593. sidx
  7594. };
  7595. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  7596. return cb(true);
  7597. };
  7598. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  7599. if (err) {
  7600. return fin(err, request);
  7601. }
  7602. if (!container || container !== 'mp4') {
  7603. return fin({
  7604. status: request.status,
  7605. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  7606. // response is just bytes in this case
  7607. // but we really don't want to return that.
  7608. response: '',
  7609. playlist,
  7610. internal: true,
  7611. playlistExclusionDuration: Infinity,
  7612. // MEDIA_ERR_NETWORK
  7613. code: 2
  7614. }, request);
  7615. } // if we already downloaded the sidx bytes in the container request, use them
  7616. const {
  7617. offset,
  7618. length
  7619. } = playlist.sidx.byterange;
  7620. if (bytes.length >= length + offset) {
  7621. return fin(err, {
  7622. response: bytes.subarray(offset, offset + length),
  7623. status: request.status,
  7624. uri: request.uri
  7625. });
  7626. } // otherwise request sidx bytes
  7627. this.request = this.vhs_.xhr({
  7628. uri,
  7629. responseType: 'arraybuffer',
  7630. headers: segmentXhrHeaders({
  7631. byterange: playlist.sidx.byterange
  7632. })
  7633. }, fin);
  7634. });
  7635. }
  7636. dispose() {
  7637. this.trigger('dispose');
  7638. this.stopRequest();
  7639. this.loadedPlaylists_ = {};
  7640. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  7641. window.clearTimeout(this.mediaRequest_);
  7642. window.clearTimeout(this.mediaUpdateTimeout);
  7643. this.mediaUpdateTimeout = null;
  7644. this.mediaRequest_ = null;
  7645. this.minimumUpdatePeriodTimeout_ = null;
  7646. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  7647. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  7648. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  7649. }
  7650. this.off();
  7651. }
  7652. hasPendingRequest() {
  7653. return this.request || this.mediaRequest_;
  7654. }
  7655. stopRequest() {
  7656. if (this.request) {
  7657. const oldRequest = this.request;
  7658. this.request = null;
  7659. oldRequest.onreadystatechange = null;
  7660. oldRequest.abort();
  7661. }
  7662. }
  7663. media(playlist) {
  7664. // getter
  7665. if (!playlist) {
  7666. return this.media_;
  7667. } // setter
  7668. if (this.state === 'HAVE_NOTHING') {
  7669. throw new Error('Cannot switch media playlist from ' + this.state);
  7670. }
  7671. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  7672. if (typeof playlist === 'string') {
  7673. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  7674. throw new Error('Unknown playlist URI: ' + playlist);
  7675. }
  7676. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  7677. }
  7678. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  7679. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  7680. this.state = 'HAVE_METADATA';
  7681. this.media_ = playlist; // trigger media change if the active media has been updated
  7682. if (mediaChange) {
  7683. this.trigger('mediachanging');
  7684. this.trigger('mediachange');
  7685. }
  7686. return;
  7687. } // switching to the active playlist is a no-op
  7688. if (!mediaChange) {
  7689. return;
  7690. } // switching from an already loaded playlist
  7691. if (this.media_) {
  7692. this.trigger('mediachanging');
  7693. }
  7694. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  7695. // everything is ready just continue to haveMetadata
  7696. this.haveMetadata({
  7697. startingState,
  7698. playlist
  7699. });
  7700. });
  7701. }
  7702. haveMetadata({
  7703. startingState,
  7704. playlist
  7705. }) {
  7706. this.state = 'HAVE_METADATA';
  7707. this.loadedPlaylists_[playlist.id] = playlist;
  7708. this.mediaRequest_ = null; // This will trigger loadedplaylist
  7709. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  7710. // to resolve setup of media groups
  7711. if (startingState === 'HAVE_MAIN_MANIFEST') {
  7712. this.trigger('loadedmetadata');
  7713. } else {
  7714. // trigger media change if the active media has been updated
  7715. this.trigger('mediachange');
  7716. }
  7717. }
  7718. pause() {
  7719. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  7720. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  7721. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  7722. }
  7723. this.stopRequest();
  7724. window.clearTimeout(this.mediaUpdateTimeout);
  7725. this.mediaUpdateTimeout = null;
  7726. if (this.isMain_) {
  7727. window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  7728. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  7729. }
  7730. if (this.state === 'HAVE_NOTHING') {
  7731. // If we pause the loader before any data has been retrieved, its as if we never
  7732. // started, so reset to an unstarted state.
  7733. this.started = false;
  7734. }
  7735. }
  7736. load(isFinalRendition) {
  7737. window.clearTimeout(this.mediaUpdateTimeout);
  7738. this.mediaUpdateTimeout = null;
  7739. const media = this.media();
  7740. if (isFinalRendition) {
  7741. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  7742. this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
  7743. return;
  7744. } // because the playlists are internal to the manifest, load should either load the
  7745. // main manifest, or do nothing but trigger an event
  7746. if (!this.started) {
  7747. this.start();
  7748. return;
  7749. }
  7750. if (media && !media.endList) {
  7751. // Check to see if this is the main loader and the MUP was cleared (this happens
  7752. // when the loader was paused). `media` should be set at this point since one is always
  7753. // set during `start()`.
  7754. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  7755. // Trigger minimumUpdatePeriod to refresh the main manifest
  7756. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  7757. this.updateMinimumUpdatePeriodTimeout_();
  7758. }
  7759. this.trigger('mediaupdatetimeout');
  7760. } else {
  7761. this.trigger('loadedplaylist');
  7762. }
  7763. }
  7764. start() {
  7765. this.started = true; // We don't need to request the main manifest again
  7766. // Call this asynchronously to match the xhr request behavior below
  7767. if (!this.isMain_) {
  7768. this.mediaRequest_ = window.setTimeout(() => this.haveMain_(), 0);
  7769. return;
  7770. }
  7771. this.requestMain_((req, mainChanged) => {
  7772. this.haveMain_();
  7773. if (!this.hasPendingRequest() && !this.media_) {
  7774. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  7775. }
  7776. });
  7777. }
  7778. requestMain_(cb) {
  7779. this.request = this.vhs_.xhr({
  7780. uri: this.mainPlaylistLoader_.srcUrl,
  7781. withCredentials: this.withCredentials
  7782. }, (error, req) => {
  7783. if (this.requestErrored_(error, req)) {
  7784. if (this.state === 'HAVE_NOTHING') {
  7785. this.started = false;
  7786. }
  7787. return;
  7788. }
  7789. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  7790. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  7791. if (req.responseHeaders && req.responseHeaders.date) {
  7792. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  7793. } else {
  7794. this.mainLoaded_ = Date.now();
  7795. }
  7796. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  7797. if (mainChanged) {
  7798. this.handleMain_();
  7799. this.syncClientServerClock_(() => {
  7800. return cb(req, mainChanged);
  7801. });
  7802. return;
  7803. }
  7804. return cb(req, mainChanged);
  7805. });
  7806. }
  7807. /**
  7808. * Parses the main xml for UTCTiming node to sync the client clock to the server
  7809. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  7810. *
  7811. * @param {Function} done
  7812. * Function to call when clock sync has completed
  7813. */
  7814. syncClientServerClock_(done) {
  7815. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  7816. // server clock
  7817. if (utcTiming === null) {
  7818. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  7819. return done();
  7820. }
  7821. if (utcTiming.method === 'DIRECT') {
  7822. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  7823. return done();
  7824. }
  7825. this.request = this.vhs_.xhr({
  7826. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  7827. method: utcTiming.method,
  7828. withCredentials: this.withCredentials
  7829. }, (error, req) => {
  7830. // disposed
  7831. if (!this.request) {
  7832. return;
  7833. }
  7834. if (error) {
  7835. // sync request failed, fall back to using date header from mpd
  7836. // TODO: log warning
  7837. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  7838. return done();
  7839. }
  7840. let serverTime;
  7841. if (utcTiming.method === 'HEAD') {
  7842. if (!req.responseHeaders || !req.responseHeaders.date) {
  7843. // expected date header not preset, fall back to using date header from mpd
  7844. // TODO: log warning
  7845. serverTime = this.mainLoaded_;
  7846. } else {
  7847. serverTime = Date.parse(req.responseHeaders.date);
  7848. }
  7849. } else {
  7850. serverTime = Date.parse(req.responseText);
  7851. }
  7852. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  7853. done();
  7854. });
  7855. }
  7856. haveMain_() {
  7857. this.state = 'HAVE_MAIN_MANIFEST';
  7858. if (this.isMain_) {
  7859. // We have the main playlist at this point, so
  7860. // trigger this to allow PlaylistController
  7861. // to make an initial playlist selection
  7862. this.trigger('loadedplaylist');
  7863. } else if (!this.media_) {
  7864. // no media playlist was specifically selected so select
  7865. // the one the child playlist loader was created with
  7866. this.media(this.childPlaylist_);
  7867. }
  7868. }
  7869. handleMain_() {
  7870. // clear media request
  7871. this.mediaRequest_ = null;
  7872. const oldMain = this.mainPlaylistLoader_.main;
  7873. let newMain = parseMainXml({
  7874. mainXml: this.mainPlaylistLoader_.mainXml_,
  7875. srcUrl: this.mainPlaylistLoader_.srcUrl,
  7876. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  7877. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  7878. previousManifest: oldMain
  7879. }); // if we have an old main to compare the new main against
  7880. if (oldMain) {
  7881. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  7882. } // only update main if we have a new main
  7883. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  7884. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  7885. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  7886. this.mainPlaylistLoader_.srcUrl = location;
  7887. }
  7888. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  7889. this.updateMinimumUpdatePeriodTimeout_();
  7890. }
  7891. return Boolean(newMain);
  7892. }
  7893. updateMinimumUpdatePeriodTimeout_() {
  7894. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  7895. // a new one will be added if needed.
  7896. if (mpl.createMupOnMedia_) {
  7897. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  7898. mpl.createMupOnMedia_ = null;
  7899. } // clear any pending timeouts
  7900. if (mpl.minimumUpdatePeriodTimeout_) {
  7901. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  7902. mpl.minimumUpdatePeriodTimeout_ = null;
  7903. }
  7904. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  7905. // MPD has no future validity, so a new one will need to be acquired when new
  7906. // media segments are to be made available. Thus, we use the target duration
  7907. // in this case
  7908. if (mup === 0) {
  7909. if (mpl.media()) {
  7910. mup = mpl.media().targetDuration * 1000;
  7911. } else {
  7912. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  7913. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  7914. }
  7915. } // if minimumUpdatePeriod is invalid or <= zero, which
  7916. // can happen when a live video becomes VOD. skip timeout
  7917. // creation.
  7918. if (typeof mup !== 'number' || mup <= 0) {
  7919. if (mup < 0) {
  7920. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  7921. }
  7922. return;
  7923. }
  7924. this.createMUPTimeout_(mup);
  7925. }
  7926. createMUPTimeout_(mup) {
  7927. const mpl = this.mainPlaylistLoader_;
  7928. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
  7929. mpl.minimumUpdatePeriodTimeout_ = null;
  7930. mpl.trigger('minimumUpdatePeriod');
  7931. mpl.createMUPTimeout_(mup);
  7932. }, mup);
  7933. }
  7934. /**
  7935. * Sends request to refresh the main xml and updates the parsed main manifest
  7936. */
  7937. refreshXml_() {
  7938. this.requestMain_((req, mainChanged) => {
  7939. if (!mainChanged) {
  7940. return;
  7941. }
  7942. if (this.media_) {
  7943. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  7944. } // This will filter out updated sidx info from the mapping
  7945. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  7946. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  7947. // TODO: do we need to reload the current playlist?
  7948. this.refreshMedia_(this.media().id);
  7949. });
  7950. });
  7951. }
  7952. /**
  7953. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  7954. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  7955. * from the main loader.
  7956. */
  7957. refreshMedia_(mediaID) {
  7958. if (!mediaID) {
  7959. throw new Error('refreshMedia_ must take a media id');
  7960. } // for main we have to reparse the main xml
  7961. // to re-create segments based on current timing values
  7962. // which may change media. We only skip updating the main manifest
  7963. // if this is the first time this.media_ is being set.
  7964. // as main was just parsed in that case.
  7965. if (this.media_ && this.isMain_) {
  7966. this.handleMain_();
  7967. }
  7968. const playlists = this.mainPlaylistLoader_.main.playlists;
  7969. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  7970. if (mediaChanged) {
  7971. this.media_ = playlists[mediaID];
  7972. } else {
  7973. this.trigger('playlistunchanged');
  7974. }
  7975. if (!this.mediaUpdateTimeout) {
  7976. const createMediaUpdateTimeout = () => {
  7977. if (this.media().endList) {
  7978. return;
  7979. }
  7980. this.mediaUpdateTimeout = window.setTimeout(() => {
  7981. this.trigger('mediaupdatetimeout');
  7982. createMediaUpdateTimeout();
  7983. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  7984. };
  7985. createMediaUpdateTimeout();
  7986. }
  7987. this.trigger('loadedplaylist');
  7988. }
  7989. }
  7990. var Config = {
  7991. GOAL_BUFFER_LENGTH: 30,
  7992. MAX_GOAL_BUFFER_LENGTH: 60,
  7993. BACK_BUFFER_LENGTH: 30,
  7994. GOAL_BUFFER_LENGTH_RATE: 1,
  7995. // 0.5 MB/s
  7996. INITIAL_BANDWIDTH: 4194304,
  7997. // A fudge factor to apply to advertised playlist bitrates to account for
  7998. // temporary flucations in client bandwidth
  7999. BANDWIDTH_VARIANCE: 1.2,
  8000. // How much of the buffer must be filled before we consider upswitching
  8001. BUFFER_LOW_WATER_LINE: 0,
  8002. MAX_BUFFER_LOW_WATER_LINE: 30,
  8003. // TODO: Remove this when experimentalBufferBasedABR is removed
  8004. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  8005. BUFFER_LOW_WATER_LINE_RATE: 1,
  8006. // If the buffer is greater than the high water line, we won't switch down
  8007. BUFFER_HIGH_WATER_LINE: 30
  8008. };
  8009. const stringToArrayBuffer = string => {
  8010. const view = new Uint8Array(new ArrayBuffer(string.length));
  8011. for (let i = 0; i < string.length; i++) {
  8012. view[i] = string.charCodeAt(i);
  8013. }
  8014. return view.buffer;
  8015. };
  8016. /* global Blob, BlobBuilder, Worker */
  8017. // unify worker interface
  8018. const browserWorkerPolyFill = function (workerObj) {
  8019. // node only supports on/off
  8020. workerObj.on = workerObj.addEventListener;
  8021. workerObj.off = workerObj.removeEventListener;
  8022. return workerObj;
  8023. };
  8024. const createObjectURL = function (str) {
  8025. try {
  8026. return URL.createObjectURL(new Blob([str], {
  8027. type: 'application/javascript'
  8028. }));
  8029. } catch (e) {
  8030. const blob = new BlobBuilder();
  8031. blob.append(str);
  8032. return URL.createObjectURL(blob.getBlob());
  8033. }
  8034. };
  8035. const factory = function (code) {
  8036. return function () {
  8037. const objectUrl = createObjectURL(code);
  8038. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  8039. worker.objURL = objectUrl;
  8040. const terminate = worker.terminate;
  8041. worker.on = worker.addEventListener;
  8042. worker.off = worker.removeEventListener;
  8043. worker.terminate = function () {
  8044. URL.revokeObjectURL(objectUrl);
  8045. return terminate.call(this);
  8046. };
  8047. return worker;
  8048. };
  8049. };
  8050. const transform = function (code) {
  8051. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  8052. };
  8053. const getWorkerString = function (fn) {
  8054. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  8055. };
  8056. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  8057. const workerCode$1 = transform(getWorkerString(function () {
  8058. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  8059. /**
  8060. * mux.js
  8061. *
  8062. * Copyright (c) Brightcove
  8063. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8064. *
  8065. * A lightweight readable stream implemention that handles event dispatching.
  8066. * Objects that inherit from streams should call init in their constructors.
  8067. */
  8068. var Stream$8 = function () {
  8069. this.init = function () {
  8070. var listeners = {};
  8071. /**
  8072. * Add a listener for a specified event type.
  8073. * @param type {string} the event name
  8074. * @param listener {function} the callback to be invoked when an event of
  8075. * the specified type occurs
  8076. */
  8077. this.on = function (type, listener) {
  8078. if (!listeners[type]) {
  8079. listeners[type] = [];
  8080. }
  8081. listeners[type] = listeners[type].concat(listener);
  8082. };
  8083. /**
  8084. * Remove a listener for a specified event type.
  8085. * @param type {string} the event name
  8086. * @param listener {function} a function previously registered for this
  8087. * type of event through `on`
  8088. */
  8089. this.off = function (type, listener) {
  8090. var index;
  8091. if (!listeners[type]) {
  8092. return false;
  8093. }
  8094. index = listeners[type].indexOf(listener);
  8095. listeners[type] = listeners[type].slice();
  8096. listeners[type].splice(index, 1);
  8097. return index > -1;
  8098. };
  8099. /**
  8100. * Trigger an event of the specified type on this stream. Any additional
  8101. * arguments to this function are passed as parameters to event listeners.
  8102. * @param type {string} the event name
  8103. */
  8104. this.trigger = function (type) {
  8105. var callbacks, i, length, args;
  8106. callbacks = listeners[type];
  8107. if (!callbacks) {
  8108. return;
  8109. } // Slicing the arguments on every invocation of this method
  8110. // can add a significant amount of overhead. Avoid the
  8111. // intermediate object creation for the common case of a
  8112. // single callback argument
  8113. if (arguments.length === 2) {
  8114. length = callbacks.length;
  8115. for (i = 0; i < length; ++i) {
  8116. callbacks[i].call(this, arguments[1]);
  8117. }
  8118. } else {
  8119. args = [];
  8120. i = arguments.length;
  8121. for (i = 1; i < arguments.length; ++i) {
  8122. args.push(arguments[i]);
  8123. }
  8124. length = callbacks.length;
  8125. for (i = 0; i < length; ++i) {
  8126. callbacks[i].apply(this, args);
  8127. }
  8128. }
  8129. };
  8130. /**
  8131. * Destroys the stream and cleans up.
  8132. */
  8133. this.dispose = function () {
  8134. listeners = {};
  8135. };
  8136. };
  8137. };
  8138. /**
  8139. * Forwards all `data` events on this stream to the destination stream. The
  8140. * destination stream should provide a method `push` to receive the data
  8141. * events as they arrive.
  8142. * @param destination {stream} the stream that will receive all `data` events
  8143. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  8144. * when the current stream emits a 'done' event
  8145. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  8146. */
  8147. Stream$8.prototype.pipe = function (destination) {
  8148. this.on('data', function (data) {
  8149. destination.push(data);
  8150. });
  8151. this.on('done', function (flushSource) {
  8152. destination.flush(flushSource);
  8153. });
  8154. this.on('partialdone', function (flushSource) {
  8155. destination.partialFlush(flushSource);
  8156. });
  8157. this.on('endedtimeline', function (flushSource) {
  8158. destination.endTimeline(flushSource);
  8159. });
  8160. this.on('reset', function (flushSource) {
  8161. destination.reset(flushSource);
  8162. });
  8163. return destination;
  8164. }; // Default stream functions that are expected to be overridden to perform
  8165. // actual work. These are provided by the prototype as a sort of no-op
  8166. // implementation so that we don't have to check for their existence in the
  8167. // `pipe` function above.
  8168. Stream$8.prototype.push = function (data) {
  8169. this.trigger('data', data);
  8170. };
  8171. Stream$8.prototype.flush = function (flushSource) {
  8172. this.trigger('done', flushSource);
  8173. };
  8174. Stream$8.prototype.partialFlush = function (flushSource) {
  8175. this.trigger('partialdone', flushSource);
  8176. };
  8177. Stream$8.prototype.endTimeline = function (flushSource) {
  8178. this.trigger('endedtimeline', flushSource);
  8179. };
  8180. Stream$8.prototype.reset = function (flushSource) {
  8181. this.trigger('reset', flushSource);
  8182. };
  8183. var stream = Stream$8;
  8184. var MAX_UINT32$1 = Math.pow(2, 32);
  8185. var getUint64$3 = function (uint8) {
  8186. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  8187. var value;
  8188. if (dv.getBigUint64) {
  8189. value = dv.getBigUint64(0);
  8190. if (value < Number.MAX_SAFE_INTEGER) {
  8191. return Number(value);
  8192. }
  8193. return value;
  8194. }
  8195. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  8196. };
  8197. var numbers = {
  8198. getUint64: getUint64$3,
  8199. MAX_UINT32: MAX_UINT32$1
  8200. };
  8201. /**
  8202. * mux.js
  8203. *
  8204. * Copyright (c) Brightcove
  8205. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8206. *
  8207. * Functions that generate fragmented MP4s suitable for use with Media
  8208. * Source Extensions.
  8209. */
  8210. var MAX_UINT32 = numbers.MAX_UINT32;
  8211. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
  8212. (function () {
  8213. var i;
  8214. types = {
  8215. avc1: [],
  8216. // codingname
  8217. avcC: [],
  8218. btrt: [],
  8219. dinf: [],
  8220. dref: [],
  8221. esds: [],
  8222. ftyp: [],
  8223. hdlr: [],
  8224. mdat: [],
  8225. mdhd: [],
  8226. mdia: [],
  8227. mfhd: [],
  8228. minf: [],
  8229. moof: [],
  8230. moov: [],
  8231. mp4a: [],
  8232. // codingname
  8233. mvex: [],
  8234. mvhd: [],
  8235. pasp: [],
  8236. sdtp: [],
  8237. smhd: [],
  8238. stbl: [],
  8239. stco: [],
  8240. stsc: [],
  8241. stsd: [],
  8242. stsz: [],
  8243. stts: [],
  8244. styp: [],
  8245. tfdt: [],
  8246. tfhd: [],
  8247. traf: [],
  8248. trak: [],
  8249. trun: [],
  8250. trex: [],
  8251. tkhd: [],
  8252. vmhd: []
  8253. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  8254. // don't throw an error
  8255. if (typeof Uint8Array === 'undefined') {
  8256. return;
  8257. }
  8258. for (i in types) {
  8259. if (types.hasOwnProperty(i)) {
  8260. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  8261. }
  8262. }
  8263. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  8264. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  8265. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  8266. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  8267. 0x00, 0x00, 0x00, // flags
  8268. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8269. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8270. 0x00, 0x00, 0x00, 0x00, // reserved
  8271. 0x00, 0x00, 0x00, 0x00, // reserved
  8272. 0x00, 0x00, 0x00, 0x00, // reserved
  8273. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  8274. ]);
  8275. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  8276. 0x00, 0x00, 0x00, // flags
  8277. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8278. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  8279. 0x00, 0x00, 0x00, 0x00, // reserved
  8280. 0x00, 0x00, 0x00, 0x00, // reserved
  8281. 0x00, 0x00, 0x00, 0x00, // reserved
  8282. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  8283. ]);
  8284. HDLR_TYPES = {
  8285. video: VIDEO_HDLR,
  8286. audio: AUDIO_HDLR
  8287. };
  8288. DREF = new Uint8Array([0x00, // version 0
  8289. 0x00, 0x00, 0x00, // flags
  8290. 0x00, 0x00, 0x00, 0x01, // entry_count
  8291. 0x00, 0x00, 0x00, 0x0c, // entry_size
  8292. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  8293. 0x00, // version 0
  8294. 0x00, 0x00, 0x01 // entry_flags
  8295. ]);
  8296. SMHD = new Uint8Array([0x00, // version
  8297. 0x00, 0x00, 0x00, // flags
  8298. 0x00, 0x00, // balance, 0 means centered
  8299. 0x00, 0x00 // reserved
  8300. ]);
  8301. STCO = new Uint8Array([0x00, // version
  8302. 0x00, 0x00, 0x00, // flags
  8303. 0x00, 0x00, 0x00, 0x00 // entry_count
  8304. ]);
  8305. STSC = STCO;
  8306. STSZ = new Uint8Array([0x00, // version
  8307. 0x00, 0x00, 0x00, // flags
  8308. 0x00, 0x00, 0x00, 0x00, // sample_size
  8309. 0x00, 0x00, 0x00, 0x00 // sample_count
  8310. ]);
  8311. STTS = STCO;
  8312. VMHD = new Uint8Array([0x00, // version
  8313. 0x00, 0x00, 0x01, // flags
  8314. 0x00, 0x00, // graphicsmode
  8315. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  8316. ]);
  8317. })();
  8318. box = function (type) {
  8319. var payload = [],
  8320. size = 0,
  8321. i,
  8322. result,
  8323. view;
  8324. for (i = 1; i < arguments.length; i++) {
  8325. payload.push(arguments[i]);
  8326. }
  8327. i = payload.length; // calculate the total size we need to allocate
  8328. while (i--) {
  8329. size += payload[i].byteLength;
  8330. }
  8331. result = new Uint8Array(size + 8);
  8332. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  8333. view.setUint32(0, result.byteLength);
  8334. result.set(type, 4); // copy the payload into the result
  8335. for (i = 0, size = 8; i < payload.length; i++) {
  8336. result.set(payload[i], size);
  8337. size += payload[i].byteLength;
  8338. }
  8339. return result;
  8340. };
  8341. dinf = function () {
  8342. return box(types.dinf, box(types.dref, DREF));
  8343. };
  8344. esds = function (track) {
  8345. return box(types.esds, new Uint8Array([0x00, // version
  8346. 0x00, 0x00, 0x00, // flags
  8347. // ES_Descriptor
  8348. 0x03, // tag, ES_DescrTag
  8349. 0x19, // length
  8350. 0x00, 0x00, // ES_ID
  8351. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  8352. // DecoderConfigDescriptor
  8353. 0x04, // tag, DecoderConfigDescrTag
  8354. 0x11, // length
  8355. 0x40, // object type
  8356. 0x15, // streamType
  8357. 0x00, 0x06, 0x00, // bufferSizeDB
  8358. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  8359. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  8360. // DecoderSpecificInfo
  8361. 0x05, // tag, DecoderSpecificInfoTag
  8362. 0x02, // length
  8363. // ISO/IEC 14496-3, AudioSpecificConfig
  8364. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  8365. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  8366. ]));
  8367. };
  8368. ftyp = function () {
  8369. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  8370. };
  8371. hdlr = function (type) {
  8372. return box(types.hdlr, HDLR_TYPES[type]);
  8373. };
  8374. mdat = function (data) {
  8375. return box(types.mdat, data);
  8376. };
  8377. mdhd = function (track) {
  8378. var result = new Uint8Array([0x00, // version 0
  8379. 0x00, 0x00, 0x00, // flags
  8380. 0x00, 0x00, 0x00, 0x02, // creation_time
  8381. 0x00, 0x00, 0x00, 0x03, // modification_time
  8382. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8383. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  8384. 0x55, 0xc4, // 'und' language (undetermined)
  8385. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  8386. // defined. The sample rate can be parsed out of an ADTS header, for
  8387. // instance.
  8388. if (track.samplerate) {
  8389. result[12] = track.samplerate >>> 24 & 0xFF;
  8390. result[13] = track.samplerate >>> 16 & 0xFF;
  8391. result[14] = track.samplerate >>> 8 & 0xFF;
  8392. result[15] = track.samplerate & 0xFF;
  8393. }
  8394. return box(types.mdhd, result);
  8395. };
  8396. mdia = function (track) {
  8397. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  8398. };
  8399. mfhd = function (sequenceNumber) {
  8400. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  8401. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  8402. ]));
  8403. };
  8404. minf = function (track) {
  8405. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  8406. };
  8407. moof = function (sequenceNumber, tracks) {
  8408. var trackFragments = [],
  8409. i = tracks.length; // build traf boxes for each track fragment
  8410. while (i--) {
  8411. trackFragments[i] = traf(tracks[i]);
  8412. }
  8413. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  8414. };
  8415. /**
  8416. * Returns a movie box.
  8417. * @param tracks {array} the tracks associated with this movie
  8418. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  8419. */
  8420. moov = function (tracks) {
  8421. var i = tracks.length,
  8422. boxes = [];
  8423. while (i--) {
  8424. boxes[i] = trak(tracks[i]);
  8425. }
  8426. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  8427. };
  8428. mvex = function (tracks) {
  8429. var i = tracks.length,
  8430. boxes = [];
  8431. while (i--) {
  8432. boxes[i] = trex(tracks[i]);
  8433. }
  8434. return box.apply(null, [types.mvex].concat(boxes));
  8435. };
  8436. mvhd = function (duration) {
  8437. var bytes = new Uint8Array([0x00, // version 0
  8438. 0x00, 0x00, 0x00, // flags
  8439. 0x00, 0x00, 0x00, 0x01, // creation_time
  8440. 0x00, 0x00, 0x00, 0x02, // modification_time
  8441. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8442. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  8443. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  8444. 0x01, 0x00, // 1.0 volume
  8445. 0x00, 0x00, // reserved
  8446. 0x00, 0x00, 0x00, 0x00, // reserved
  8447. 0x00, 0x00, 0x00, 0x00, // reserved
  8448. 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, // transformation: unity matrix
  8449. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  8450. 0xff, 0xff, 0xff, 0xff // next_track_ID
  8451. ]);
  8452. return box(types.mvhd, bytes);
  8453. };
  8454. sdtp = function (track) {
  8455. var samples = track.samples || [],
  8456. bytes = new Uint8Array(4 + samples.length),
  8457. flags,
  8458. i; // leave the full box header (4 bytes) all zero
  8459. // write the sample table
  8460. for (i = 0; i < samples.length; i++) {
  8461. flags = samples[i].flags;
  8462. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  8463. }
  8464. return box(types.sdtp, bytes);
  8465. };
  8466. stbl = function (track) {
  8467. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  8468. };
  8469. (function () {
  8470. var videoSample, audioSample;
  8471. stsd = function (track) {
  8472. return box(types.stsd, new Uint8Array([0x00, // version 0
  8473. 0x00, 0x00, 0x00, // flags
  8474. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  8475. };
  8476. videoSample = function (track) {
  8477. var sps = track.sps || [],
  8478. pps = track.pps || [],
  8479. sequenceParameterSets = [],
  8480. pictureParameterSets = [],
  8481. i,
  8482. avc1Box; // assemble the SPSs
  8483. for (i = 0; i < sps.length; i++) {
  8484. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  8485. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  8486. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  8487. } // assemble the PPSs
  8488. for (i = 0; i < pps.length; i++) {
  8489. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  8490. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  8491. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  8492. }
  8493. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8494. 0x00, 0x01, // data_reference_index
  8495. 0x00, 0x00, // pre_defined
  8496. 0x00, 0x00, // reserved
  8497. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  8498. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  8499. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  8500. 0x00, 0x48, 0x00, 0x00, // horizresolution
  8501. 0x00, 0x48, 0x00, 0x00, // vertresolution
  8502. 0x00, 0x00, 0x00, 0x00, // reserved
  8503. 0x00, 0x01, // frame_count
  8504. 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  8505. 0x00, 0x18, // depth = 24
  8506. 0x11, 0x11 // pre_defined = -1
  8507. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  8508. track.profileIdc, // AVCProfileIndication
  8509. track.profileCompatibility, // profile_compatibility
  8510. track.levelIdc, // AVCLevelIndication
  8511. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  8512. ].concat([sps.length], // numOfSequenceParameterSets
  8513. sequenceParameterSets, // "SPS"
  8514. [pps.length], // numOfPictureParameterSets
  8515. pictureParameterSets // "PPS"
  8516. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  8517. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  8518. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  8519. ]))];
  8520. if (track.sarRatio) {
  8521. var hSpacing = track.sarRatio[0],
  8522. vSpacing = track.sarRatio[1];
  8523. avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
  8524. }
  8525. return box.apply(null, avc1Box);
  8526. };
  8527. audioSample = function (track) {
  8528. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  8529. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8530. 0x00, 0x01, // data_reference_index
  8531. // AudioSampleEntry, ISO/IEC 14496-12
  8532. 0x00, 0x00, 0x00, 0x00, // reserved
  8533. 0x00, 0x00, 0x00, 0x00, // reserved
  8534. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  8535. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  8536. 0x00, 0x00, // pre_defined
  8537. 0x00, 0x00, // reserved
  8538. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  8539. // MP4AudioSampleEntry, ISO/IEC 14496-14
  8540. ]), esds(track));
  8541. };
  8542. })();
  8543. tkhd = function (track) {
  8544. var result = new Uint8Array([0x00, // version 0
  8545. 0x00, 0x00, 0x07, // flags
  8546. 0x00, 0x00, 0x00, 0x00, // creation_time
  8547. 0x00, 0x00, 0x00, 0x00, // modification_time
  8548. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8549. 0x00, 0x00, 0x00, 0x00, // reserved
  8550. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  8551. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8552. 0x00, 0x00, // layer
  8553. 0x00, 0x00, // alternate_group
  8554. 0x01, 0x00, // non-audio track volume
  8555. 0x00, 0x00, // reserved
  8556. 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, // transformation: unity matrix
  8557. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  8558. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  8559. ]);
  8560. return box(types.tkhd, result);
  8561. };
  8562. /**
  8563. * Generate a track fragment (traf) box. A traf box collects metadata
  8564. * about tracks in a movie fragment (moof) box.
  8565. */
  8566. traf = function (track) {
  8567. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  8568. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  8569. 0x00, 0x00, 0x3a, // flags
  8570. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8571. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  8572. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8573. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8574. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  8575. ]));
  8576. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  8577. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  8578. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  8579. 0x00, 0x00, 0x00, // flags
  8580. // baseMediaDecodeTime
  8581. upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
  8582. // the containing moof to the first payload byte of the associated
  8583. // mdat
  8584. dataOffset = 32 + // tfhd
  8585. 20 + // tfdt
  8586. 8 + // traf header
  8587. 16 + // mfhd
  8588. 8 + // moof header
  8589. 8; // mdat header
  8590. // audio tracks require less metadata
  8591. if (track.type === 'audio') {
  8592. trackFragmentRun = trun$1(track, dataOffset);
  8593. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  8594. } // video tracks should contain an independent and disposable samples
  8595. // box (sdtp)
  8596. // generate one and adjust offsets to match
  8597. sampleDependencyTable = sdtp(track);
  8598. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  8599. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  8600. };
  8601. /**
  8602. * Generate a track box.
  8603. * @param track {object} a track definition
  8604. * @return {Uint8Array} the track box
  8605. */
  8606. trak = function (track) {
  8607. track.duration = track.duration || 0xffffffff;
  8608. return box(types.trak, tkhd(track), mdia(track));
  8609. };
  8610. trex = function (track) {
  8611. var result = new Uint8Array([0x00, // version 0
  8612. 0x00, 0x00, 0x00, // flags
  8613. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8614. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  8615. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8616. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8617. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  8618. ]); // the last two bytes of default_sample_flags is the sample
  8619. // degradation priority, a hint about the importance of this sample
  8620. // relative to others. Lower the degradation priority for all sample
  8621. // types other than video.
  8622. if (track.type !== 'video') {
  8623. result[result.length - 1] = 0x00;
  8624. }
  8625. return box(types.trex, result);
  8626. };
  8627. (function () {
  8628. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  8629. // duration is present for the first sample, it will be present for
  8630. // all subsequent samples.
  8631. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  8632. trunHeader = function (samples, offset) {
  8633. var durationPresent = 0,
  8634. sizePresent = 0,
  8635. flagsPresent = 0,
  8636. compositionTimeOffset = 0; // trun flag constants
  8637. if (samples.length) {
  8638. if (samples[0].duration !== undefined) {
  8639. durationPresent = 0x1;
  8640. }
  8641. if (samples[0].size !== undefined) {
  8642. sizePresent = 0x2;
  8643. }
  8644. if (samples[0].flags !== undefined) {
  8645. flagsPresent = 0x4;
  8646. }
  8647. if (samples[0].compositionTimeOffset !== undefined) {
  8648. compositionTimeOffset = 0x8;
  8649. }
  8650. }
  8651. return [0x00, // version 0
  8652. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  8653. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  8654. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  8655. ];
  8656. };
  8657. videoTrun = function (track, offset) {
  8658. var bytesOffest, bytes, header, samples, sample, i;
  8659. samples = track.samples || [];
  8660. offset += 8 + 12 + 16 * samples.length;
  8661. header = trunHeader(samples, offset);
  8662. bytes = new Uint8Array(header.length + samples.length * 16);
  8663. bytes.set(header);
  8664. bytesOffest = header.length;
  8665. for (i = 0; i < samples.length; i++) {
  8666. sample = samples[i];
  8667. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  8668. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  8669. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  8670. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  8671. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  8672. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  8673. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  8674. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  8675. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  8676. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  8677. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  8678. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  8679. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  8680. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  8681. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  8682. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  8683. }
  8684. return box(types.trun, bytes);
  8685. };
  8686. audioTrun = function (track, offset) {
  8687. var bytes, bytesOffest, header, samples, sample, i;
  8688. samples = track.samples || [];
  8689. offset += 8 + 12 + 8 * samples.length;
  8690. header = trunHeader(samples, offset);
  8691. bytes = new Uint8Array(header.length + samples.length * 8);
  8692. bytes.set(header);
  8693. bytesOffest = header.length;
  8694. for (i = 0; i < samples.length; i++) {
  8695. sample = samples[i];
  8696. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  8697. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  8698. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  8699. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  8700. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  8701. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  8702. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  8703. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  8704. }
  8705. return box(types.trun, bytes);
  8706. };
  8707. trun$1 = function (track, offset) {
  8708. if (track.type === 'audio') {
  8709. return audioTrun(track, offset);
  8710. }
  8711. return videoTrun(track, offset);
  8712. };
  8713. })();
  8714. var mp4Generator = {
  8715. ftyp: ftyp,
  8716. mdat: mdat,
  8717. moof: moof,
  8718. moov: moov,
  8719. initSegment: function (tracks) {
  8720. var fileType = ftyp(),
  8721. movie = moov(tracks),
  8722. result;
  8723. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  8724. result.set(fileType);
  8725. result.set(movie, fileType.byteLength);
  8726. return result;
  8727. }
  8728. };
  8729. /**
  8730. * mux.js
  8731. *
  8732. * Copyright (c) Brightcove
  8733. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8734. */
  8735. // composed of the nal units that make up that frame
  8736. // Also keep track of cummulative data about the frame from the nal units such
  8737. // as the frame duration, starting pts, etc.
  8738. var groupNalsIntoFrames = function (nalUnits) {
  8739. var i,
  8740. currentNal,
  8741. currentFrame = [],
  8742. frames = []; // TODO added for LHLS, make sure this is OK
  8743. frames.byteLength = 0;
  8744. frames.nalCount = 0;
  8745. frames.duration = 0;
  8746. currentFrame.byteLength = 0;
  8747. for (i = 0; i < nalUnits.length; i++) {
  8748. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  8749. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  8750. // Since the very first nal unit is expected to be an AUD
  8751. // only push to the frames array when currentFrame is not empty
  8752. if (currentFrame.length) {
  8753. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  8754. frames.byteLength += currentFrame.byteLength;
  8755. frames.nalCount += currentFrame.length;
  8756. frames.duration += currentFrame.duration;
  8757. frames.push(currentFrame);
  8758. }
  8759. currentFrame = [currentNal];
  8760. currentFrame.byteLength = currentNal.data.byteLength;
  8761. currentFrame.pts = currentNal.pts;
  8762. currentFrame.dts = currentNal.dts;
  8763. } else {
  8764. // Specifically flag key frames for ease of use later
  8765. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  8766. currentFrame.keyFrame = true;
  8767. }
  8768. currentFrame.duration = currentNal.dts - currentFrame.dts;
  8769. currentFrame.byteLength += currentNal.data.byteLength;
  8770. currentFrame.push(currentNal);
  8771. }
  8772. } // For the last frame, use the duration of the previous frame if we
  8773. // have nothing better to go on
  8774. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  8775. currentFrame.duration = frames[frames.length - 1].duration;
  8776. } // Push the final frame
  8777. // TODO added for LHLS, make sure this is OK
  8778. frames.byteLength += currentFrame.byteLength;
  8779. frames.nalCount += currentFrame.length;
  8780. frames.duration += currentFrame.duration;
  8781. frames.push(currentFrame);
  8782. return frames;
  8783. }; // Convert an array of frames into an array of Gop with each Gop being composed
  8784. // of the frames that make up that Gop
  8785. // Also keep track of cummulative data about the Gop from the frames such as the
  8786. // Gop duration, starting pts, etc.
  8787. var groupFramesIntoGops = function (frames) {
  8788. var i,
  8789. currentFrame,
  8790. currentGop = [],
  8791. gops = []; // We must pre-set some of the values on the Gop since we
  8792. // keep running totals of these values
  8793. currentGop.byteLength = 0;
  8794. currentGop.nalCount = 0;
  8795. currentGop.duration = 0;
  8796. currentGop.pts = frames[0].pts;
  8797. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  8798. gops.byteLength = 0;
  8799. gops.nalCount = 0;
  8800. gops.duration = 0;
  8801. gops.pts = frames[0].pts;
  8802. gops.dts = frames[0].dts;
  8803. for (i = 0; i < frames.length; i++) {
  8804. currentFrame = frames[i];
  8805. if (currentFrame.keyFrame) {
  8806. // Since the very first frame is expected to be an keyframe
  8807. // only push to the gops array when currentGop is not empty
  8808. if (currentGop.length) {
  8809. gops.push(currentGop);
  8810. gops.byteLength += currentGop.byteLength;
  8811. gops.nalCount += currentGop.nalCount;
  8812. gops.duration += currentGop.duration;
  8813. }
  8814. currentGop = [currentFrame];
  8815. currentGop.nalCount = currentFrame.length;
  8816. currentGop.byteLength = currentFrame.byteLength;
  8817. currentGop.pts = currentFrame.pts;
  8818. currentGop.dts = currentFrame.dts;
  8819. currentGop.duration = currentFrame.duration;
  8820. } else {
  8821. currentGop.duration += currentFrame.duration;
  8822. currentGop.nalCount += currentFrame.length;
  8823. currentGop.byteLength += currentFrame.byteLength;
  8824. currentGop.push(currentFrame);
  8825. }
  8826. }
  8827. if (gops.length && currentGop.duration <= 0) {
  8828. currentGop.duration = gops[gops.length - 1].duration;
  8829. }
  8830. gops.byteLength += currentGop.byteLength;
  8831. gops.nalCount += currentGop.nalCount;
  8832. gops.duration += currentGop.duration; // push the final Gop
  8833. gops.push(currentGop);
  8834. return gops;
  8835. };
  8836. /*
  8837. * Search for the first keyframe in the GOPs and throw away all frames
  8838. * until that keyframe. Then extend the duration of the pulled keyframe
  8839. * and pull the PTS and DTS of the keyframe so that it covers the time
  8840. * range of the frames that were disposed.
  8841. *
  8842. * @param {Array} gops video GOPs
  8843. * @returns {Array} modified video GOPs
  8844. */
  8845. var extendFirstKeyFrame = function (gops) {
  8846. var currentGop;
  8847. if (!gops[0][0].keyFrame && gops.length > 1) {
  8848. // Remove the first GOP
  8849. currentGop = gops.shift();
  8850. gops.byteLength -= currentGop.byteLength;
  8851. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  8852. // first gop to cover the time period of the
  8853. // frames we just removed
  8854. gops[0][0].dts = currentGop.dts;
  8855. gops[0][0].pts = currentGop.pts;
  8856. gops[0][0].duration += currentGop.duration;
  8857. }
  8858. return gops;
  8859. };
  8860. /**
  8861. * Default sample object
  8862. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  8863. */
  8864. var createDefaultSample = function () {
  8865. return {
  8866. size: 0,
  8867. flags: {
  8868. isLeading: 0,
  8869. dependsOn: 1,
  8870. isDependedOn: 0,
  8871. hasRedundancy: 0,
  8872. degradationPriority: 0,
  8873. isNonSyncSample: 1
  8874. }
  8875. };
  8876. };
  8877. /*
  8878. * Collates information from a video frame into an object for eventual
  8879. * entry into an MP4 sample table.
  8880. *
  8881. * @param {Object} frame the video frame
  8882. * @param {Number} dataOffset the byte offset to position the sample
  8883. * @return {Object} object containing sample table info for a frame
  8884. */
  8885. var sampleForFrame = function (frame, dataOffset) {
  8886. var sample = createDefaultSample();
  8887. sample.dataOffset = dataOffset;
  8888. sample.compositionTimeOffset = frame.pts - frame.dts;
  8889. sample.duration = frame.duration;
  8890. sample.size = 4 * frame.length; // Space for nal unit size
  8891. sample.size += frame.byteLength;
  8892. if (frame.keyFrame) {
  8893. sample.flags.dependsOn = 2;
  8894. sample.flags.isNonSyncSample = 0;
  8895. }
  8896. return sample;
  8897. }; // generate the track's sample table from an array of gops
  8898. var generateSampleTable$1 = function (gops, baseDataOffset) {
  8899. var h,
  8900. i,
  8901. sample,
  8902. currentGop,
  8903. currentFrame,
  8904. dataOffset = baseDataOffset || 0,
  8905. samples = [];
  8906. for (h = 0; h < gops.length; h++) {
  8907. currentGop = gops[h];
  8908. for (i = 0; i < currentGop.length; i++) {
  8909. currentFrame = currentGop[i];
  8910. sample = sampleForFrame(currentFrame, dataOffset);
  8911. dataOffset += sample.size;
  8912. samples.push(sample);
  8913. }
  8914. }
  8915. return samples;
  8916. }; // generate the track's raw mdat data from an array of gops
  8917. var concatenateNalData = function (gops) {
  8918. var h,
  8919. i,
  8920. j,
  8921. currentGop,
  8922. currentFrame,
  8923. currentNal,
  8924. dataOffset = 0,
  8925. nalsByteLength = gops.byteLength,
  8926. numberOfNals = gops.nalCount,
  8927. totalByteLength = nalsByteLength + 4 * numberOfNals,
  8928. data = new Uint8Array(totalByteLength),
  8929. view = new DataView(data.buffer); // For each Gop..
  8930. for (h = 0; h < gops.length; h++) {
  8931. currentGop = gops[h]; // For each Frame..
  8932. for (i = 0; i < currentGop.length; i++) {
  8933. currentFrame = currentGop[i]; // For each NAL..
  8934. for (j = 0; j < currentFrame.length; j++) {
  8935. currentNal = currentFrame[j];
  8936. view.setUint32(dataOffset, currentNal.data.byteLength);
  8937. dataOffset += 4;
  8938. data.set(currentNal.data, dataOffset);
  8939. dataOffset += currentNal.data.byteLength;
  8940. }
  8941. }
  8942. }
  8943. return data;
  8944. }; // generate the track's sample table from a frame
  8945. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  8946. var sample,
  8947. dataOffset = baseDataOffset || 0,
  8948. samples = [];
  8949. sample = sampleForFrame(frame, dataOffset);
  8950. samples.push(sample);
  8951. return samples;
  8952. }; // generate the track's raw mdat data from a frame
  8953. var concatenateNalDataForFrame = function (frame) {
  8954. var i,
  8955. currentNal,
  8956. dataOffset = 0,
  8957. nalsByteLength = frame.byteLength,
  8958. numberOfNals = frame.length,
  8959. totalByteLength = nalsByteLength + 4 * numberOfNals,
  8960. data = new Uint8Array(totalByteLength),
  8961. view = new DataView(data.buffer); // For each NAL..
  8962. for (i = 0; i < frame.length; i++) {
  8963. currentNal = frame[i];
  8964. view.setUint32(dataOffset, currentNal.data.byteLength);
  8965. dataOffset += 4;
  8966. data.set(currentNal.data, dataOffset);
  8967. dataOffset += currentNal.data.byteLength;
  8968. }
  8969. return data;
  8970. };
  8971. var frameUtils$1 = {
  8972. groupNalsIntoFrames: groupNalsIntoFrames,
  8973. groupFramesIntoGops: groupFramesIntoGops,
  8974. extendFirstKeyFrame: extendFirstKeyFrame,
  8975. generateSampleTable: generateSampleTable$1,
  8976. concatenateNalData: concatenateNalData,
  8977. generateSampleTableForFrame: generateSampleTableForFrame,
  8978. concatenateNalDataForFrame: concatenateNalDataForFrame
  8979. };
  8980. /**
  8981. * mux.js
  8982. *
  8983. * Copyright (c) Brightcove
  8984. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8985. */
  8986. var highPrefix = [33, 16, 5, 32, 164, 27];
  8987. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  8988. var zeroFill = function (count) {
  8989. var a = [];
  8990. while (count--) {
  8991. a.push(0);
  8992. }
  8993. return a;
  8994. };
  8995. var makeTable = function (metaTable) {
  8996. return Object.keys(metaTable).reduce(function (obj, key) {
  8997. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  8998. return arr.concat(part);
  8999. }, []));
  9000. return obj;
  9001. }, {});
  9002. };
  9003. var silence;
  9004. var silence_1 = function () {
  9005. if (!silence) {
  9006. // Frames-of-silence to use for filling in missing AAC frames
  9007. var coneOfSilence = {
  9008. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  9009. 88200: [highPrefix, [231], zeroFill(170), [56]],
  9010. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  9011. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  9012. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  9013. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  9014. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  9015. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  9016. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  9017. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  9018. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  9019. };
  9020. silence = makeTable(coneOfSilence);
  9021. }
  9022. return silence;
  9023. };
  9024. /**
  9025. * mux.js
  9026. *
  9027. * Copyright (c) Brightcove
  9028. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9029. */
  9030. var ONE_SECOND_IN_TS$4 = 90000,
  9031. // 90kHz clock
  9032. secondsToVideoTs,
  9033. secondsToAudioTs,
  9034. videoTsToSeconds,
  9035. audioTsToSeconds,
  9036. audioTsToVideoTs,
  9037. videoTsToAudioTs,
  9038. metadataTsToSeconds;
  9039. secondsToVideoTs = function (seconds) {
  9040. return seconds * ONE_SECOND_IN_TS$4;
  9041. };
  9042. secondsToAudioTs = function (seconds, sampleRate) {
  9043. return seconds * sampleRate;
  9044. };
  9045. videoTsToSeconds = function (timestamp) {
  9046. return timestamp / ONE_SECOND_IN_TS$4;
  9047. };
  9048. audioTsToSeconds = function (timestamp, sampleRate) {
  9049. return timestamp / sampleRate;
  9050. };
  9051. audioTsToVideoTs = function (timestamp, sampleRate) {
  9052. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  9053. };
  9054. videoTsToAudioTs = function (timestamp, sampleRate) {
  9055. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  9056. };
  9057. /**
  9058. * Adjust ID3 tag or caption timing information by the timeline pts values
  9059. * (if keepOriginalTimestamps is false) and convert to seconds
  9060. */
  9061. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  9062. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  9063. };
  9064. var clock$2 = {
  9065. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  9066. secondsToVideoTs: secondsToVideoTs,
  9067. secondsToAudioTs: secondsToAudioTs,
  9068. videoTsToSeconds: videoTsToSeconds,
  9069. audioTsToSeconds: audioTsToSeconds,
  9070. audioTsToVideoTs: audioTsToVideoTs,
  9071. videoTsToAudioTs: videoTsToAudioTs,
  9072. metadataTsToSeconds: metadataTsToSeconds
  9073. };
  9074. /**
  9075. * mux.js
  9076. *
  9077. * Copyright (c) Brightcove
  9078. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9079. */
  9080. var coneOfSilence = silence_1;
  9081. var clock$1 = clock$2;
  9082. /**
  9083. * Sum the `byteLength` properties of the data in each AAC frame
  9084. */
  9085. var sumFrameByteLengths = function (array) {
  9086. var i,
  9087. currentObj,
  9088. sum = 0; // sum the byteLength's all each nal unit in the frame
  9089. for (i = 0; i < array.length; i++) {
  9090. currentObj = array[i];
  9091. sum += currentObj.data.byteLength;
  9092. }
  9093. return sum;
  9094. }; // Possibly pad (prefix) the audio track with silence if appending this track
  9095. // would lead to the introduction of a gap in the audio buffer
  9096. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  9097. var baseMediaDecodeTimeTs,
  9098. frameDuration = 0,
  9099. audioGapDuration = 0,
  9100. audioFillFrameCount = 0,
  9101. audioFillDuration = 0,
  9102. silentFrame,
  9103. i,
  9104. firstFrame;
  9105. if (!frames.length) {
  9106. return;
  9107. }
  9108. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  9109. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  9110. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  9111. // insert the shortest possible amount (audio gap or audio to video gap)
  9112. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  9113. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  9114. audioFillDuration = audioFillFrameCount * frameDuration;
  9115. } // don't attempt to fill gaps smaller than a single frame or larger
  9116. // than a half second
  9117. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  9118. return;
  9119. }
  9120. silentFrame = coneOfSilence()[track.samplerate];
  9121. if (!silentFrame) {
  9122. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  9123. // from the content instead
  9124. silentFrame = frames[0].data;
  9125. }
  9126. for (i = 0; i < audioFillFrameCount; i++) {
  9127. firstFrame = frames[0];
  9128. frames.splice(0, 0, {
  9129. data: silentFrame,
  9130. dts: firstFrame.dts - frameDuration,
  9131. pts: firstFrame.pts - frameDuration
  9132. });
  9133. }
  9134. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  9135. return audioFillDuration;
  9136. }; // If the audio segment extends before the earliest allowed dts
  9137. // value, remove AAC frames until starts at or after the earliest
  9138. // allowed DTS so that we don't end up with a negative baseMedia-
  9139. // DecodeTime for the audio track
  9140. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  9141. if (track.minSegmentDts >= earliestAllowedDts) {
  9142. return adtsFrames;
  9143. } // We will need to recalculate the earliest segment Dts
  9144. track.minSegmentDts = Infinity;
  9145. return adtsFrames.filter(function (currentFrame) {
  9146. // If this is an allowed frame, keep it and record it's Dts
  9147. if (currentFrame.dts >= earliestAllowedDts) {
  9148. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  9149. track.minSegmentPts = track.minSegmentDts;
  9150. return true;
  9151. } // Otherwise, discard it
  9152. return false;
  9153. });
  9154. }; // generate the track's raw mdat data from an array of frames
  9155. var generateSampleTable = function (frames) {
  9156. var i,
  9157. currentFrame,
  9158. samples = [];
  9159. for (i = 0; i < frames.length; i++) {
  9160. currentFrame = frames[i];
  9161. samples.push({
  9162. size: currentFrame.data.byteLength,
  9163. duration: 1024 // For AAC audio, all samples contain 1024 samples
  9164. });
  9165. }
  9166. return samples;
  9167. }; // generate the track's sample table from an array of frames
  9168. var concatenateFrameData = function (frames) {
  9169. var i,
  9170. currentFrame,
  9171. dataOffset = 0,
  9172. data = new Uint8Array(sumFrameByteLengths(frames));
  9173. for (i = 0; i < frames.length; i++) {
  9174. currentFrame = frames[i];
  9175. data.set(currentFrame.data, dataOffset);
  9176. dataOffset += currentFrame.data.byteLength;
  9177. }
  9178. return data;
  9179. };
  9180. var audioFrameUtils$1 = {
  9181. prefixWithSilence: prefixWithSilence,
  9182. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  9183. generateSampleTable: generateSampleTable,
  9184. concatenateFrameData: concatenateFrameData
  9185. };
  9186. /**
  9187. * mux.js
  9188. *
  9189. * Copyright (c) Brightcove
  9190. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9191. */
  9192. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  9193. /**
  9194. * Store information about the start and end of the track and the
  9195. * duration for each frame/sample we process in order to calculate
  9196. * the baseMediaDecodeTime
  9197. */
  9198. var collectDtsInfo = function (track, data) {
  9199. if (typeof data.pts === 'number') {
  9200. if (track.timelineStartInfo.pts === undefined) {
  9201. track.timelineStartInfo.pts = data.pts;
  9202. }
  9203. if (track.minSegmentPts === undefined) {
  9204. track.minSegmentPts = data.pts;
  9205. } else {
  9206. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  9207. }
  9208. if (track.maxSegmentPts === undefined) {
  9209. track.maxSegmentPts = data.pts;
  9210. } else {
  9211. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  9212. }
  9213. }
  9214. if (typeof data.dts === 'number') {
  9215. if (track.timelineStartInfo.dts === undefined) {
  9216. track.timelineStartInfo.dts = data.dts;
  9217. }
  9218. if (track.minSegmentDts === undefined) {
  9219. track.minSegmentDts = data.dts;
  9220. } else {
  9221. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  9222. }
  9223. if (track.maxSegmentDts === undefined) {
  9224. track.maxSegmentDts = data.dts;
  9225. } else {
  9226. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  9227. }
  9228. }
  9229. };
  9230. /**
  9231. * Clear values used to calculate the baseMediaDecodeTime between
  9232. * tracks
  9233. */
  9234. var clearDtsInfo = function (track) {
  9235. delete track.minSegmentDts;
  9236. delete track.maxSegmentDts;
  9237. delete track.minSegmentPts;
  9238. delete track.maxSegmentPts;
  9239. };
  9240. /**
  9241. * Calculate the track's baseMediaDecodeTime based on the earliest
  9242. * DTS the transmuxer has ever seen and the minimum DTS for the
  9243. * current track
  9244. * @param track {object} track metadata configuration
  9245. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  9246. * in the source; false to adjust the first segment to start at 0.
  9247. */
  9248. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  9249. var baseMediaDecodeTime,
  9250. scale,
  9251. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  9252. if (!keepOriginalTimestamps) {
  9253. minSegmentDts -= track.timelineStartInfo.dts;
  9254. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  9255. // we want the start of the first segment to be placed
  9256. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  9257. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  9258. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  9259. if (track.type === 'audio') {
  9260. // Audio has a different clock equal to the sampling_rate so we need to
  9261. // scale the PTS values into the clock rate of the track
  9262. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  9263. baseMediaDecodeTime *= scale;
  9264. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  9265. }
  9266. return baseMediaDecodeTime;
  9267. };
  9268. var trackDecodeInfo$1 = {
  9269. clearDtsInfo: clearDtsInfo,
  9270. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  9271. collectDtsInfo: collectDtsInfo
  9272. };
  9273. /**
  9274. * mux.js
  9275. *
  9276. * Copyright (c) Brightcove
  9277. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9278. *
  9279. * Reads in-band caption information from a video elementary
  9280. * stream. Captions must follow the CEA-708 standard for injection
  9281. * into an MPEG-2 transport streams.
  9282. * @see https://en.wikipedia.org/wiki/CEA-708
  9283. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  9284. */
  9285. // payload type field to indicate how they are to be
  9286. // interpreted. CEAS-708 caption content is always transmitted with
  9287. // payload type 0x04.
  9288. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  9289. RBSP_TRAILING_BITS = 128;
  9290. /**
  9291. * Parse a supplemental enhancement information (SEI) NAL unit.
  9292. * Stops parsing once a message of type ITU T T35 has been found.
  9293. *
  9294. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  9295. * @return {object} the parsed SEI payload
  9296. * @see Rec. ITU-T H.264, 7.3.2.3.1
  9297. */
  9298. var parseSei = function (bytes) {
  9299. var i = 0,
  9300. result = {
  9301. payloadType: -1,
  9302. payloadSize: 0
  9303. },
  9304. payloadType = 0,
  9305. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  9306. while (i < bytes.byteLength) {
  9307. // stop once we have hit the end of the sei_rbsp
  9308. if (bytes[i] === RBSP_TRAILING_BITS) {
  9309. break;
  9310. } // Parse payload type
  9311. while (bytes[i] === 0xFF) {
  9312. payloadType += 255;
  9313. i++;
  9314. }
  9315. payloadType += bytes[i++]; // Parse payload size
  9316. while (bytes[i] === 0xFF) {
  9317. payloadSize += 255;
  9318. i++;
  9319. }
  9320. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  9321. // there can only ever be one caption message in a frame's sei
  9322. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  9323. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  9324. if (userIdentifier === 'GA94') {
  9325. result.payloadType = payloadType;
  9326. result.payloadSize = payloadSize;
  9327. result.payload = bytes.subarray(i, i + payloadSize);
  9328. break;
  9329. } else {
  9330. result.payload = void 0;
  9331. }
  9332. } // skip the payload and parse the next message
  9333. i += payloadSize;
  9334. payloadType = 0;
  9335. payloadSize = 0;
  9336. }
  9337. return result;
  9338. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  9339. var parseUserData = function (sei) {
  9340. // itu_t_t35_contry_code must be 181 (United States) for
  9341. // captions
  9342. if (sei.payload[0] !== 181) {
  9343. return null;
  9344. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  9345. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  9346. return null;
  9347. } // the user_identifier should be "GA94" to indicate ATSC1 data
  9348. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  9349. return null;
  9350. } // finally, user_data_type_code should be 0x03 for caption data
  9351. if (sei.payload[7] !== 0x03) {
  9352. return null;
  9353. } // return the user_data_type_structure and strip the trailing
  9354. // marker bits
  9355. return sei.payload.subarray(8, sei.payload.length - 1);
  9356. }; // see CEA-708-D, section 4.4
  9357. var parseCaptionPackets = function (pts, userData) {
  9358. var results = [],
  9359. i,
  9360. count,
  9361. offset,
  9362. data; // if this is just filler, return immediately
  9363. if (!(userData[0] & 0x40)) {
  9364. return results;
  9365. } // parse out the cc_data_1 and cc_data_2 fields
  9366. count = userData[0] & 0x1f;
  9367. for (i = 0; i < count; i++) {
  9368. offset = i * 3;
  9369. data = {
  9370. type: userData[offset + 2] & 0x03,
  9371. pts: pts
  9372. }; // capture cc data when cc_valid is 1
  9373. if (userData[offset + 2] & 0x04) {
  9374. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  9375. results.push(data);
  9376. }
  9377. }
  9378. return results;
  9379. };
  9380. var discardEmulationPreventionBytes$1 = function (data) {
  9381. var length = data.byteLength,
  9382. emulationPreventionBytesPositions = [],
  9383. i = 1,
  9384. newLength,
  9385. newData; // Find all `Emulation Prevention Bytes`
  9386. while (i < length - 2) {
  9387. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  9388. emulationPreventionBytesPositions.push(i + 2);
  9389. i += 2;
  9390. } else {
  9391. i++;
  9392. }
  9393. } // If no Emulation Prevention Bytes were found just return the original
  9394. // array
  9395. if (emulationPreventionBytesPositions.length === 0) {
  9396. return data;
  9397. } // Create a new array to hold the NAL unit data
  9398. newLength = length - emulationPreventionBytesPositions.length;
  9399. newData = new Uint8Array(newLength);
  9400. var sourceIndex = 0;
  9401. for (i = 0; i < newLength; sourceIndex++, i++) {
  9402. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  9403. // Skip this byte
  9404. sourceIndex++; // Remove this position index
  9405. emulationPreventionBytesPositions.shift();
  9406. }
  9407. newData[i] = data[sourceIndex];
  9408. }
  9409. return newData;
  9410. }; // exports
  9411. var captionPacketParser = {
  9412. parseSei: parseSei,
  9413. parseUserData: parseUserData,
  9414. parseCaptionPackets: parseCaptionPackets,
  9415. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  9416. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  9417. };
  9418. /**
  9419. * mux.js
  9420. *
  9421. * Copyright (c) Brightcove
  9422. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9423. *
  9424. * Reads in-band caption information from a video elementary
  9425. * stream. Captions must follow the CEA-708 standard for injection
  9426. * into an MPEG-2 transport streams.
  9427. * @see https://en.wikipedia.org/wiki/CEA-708
  9428. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  9429. */
  9430. // Link To Transport
  9431. // -----------------
  9432. var Stream$7 = stream;
  9433. var cea708Parser = captionPacketParser;
  9434. var CaptionStream$2 = function (options) {
  9435. options = options || {};
  9436. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  9437. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  9438. this.captionPackets_ = [];
  9439. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  9440. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  9441. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  9442. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  9443. ];
  9444. if (this.parse708captions_) {
  9445. this.cc708Stream_ = new Cea708Stream({
  9446. captionServices: options.captionServices
  9447. }); // eslint-disable-line no-use-before-define
  9448. }
  9449. this.reset(); // forward data and done events from CCs to this CaptionStream
  9450. this.ccStreams_.forEach(function (cc) {
  9451. cc.on('data', this.trigger.bind(this, 'data'));
  9452. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  9453. cc.on('done', this.trigger.bind(this, 'done'));
  9454. }, this);
  9455. if (this.parse708captions_) {
  9456. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  9457. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  9458. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  9459. }
  9460. };
  9461. CaptionStream$2.prototype = new Stream$7();
  9462. CaptionStream$2.prototype.push = function (event) {
  9463. var sei, userData, newCaptionPackets; // only examine SEI NALs
  9464. if (event.nalUnitType !== 'sei_rbsp') {
  9465. return;
  9466. } // parse the sei
  9467. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  9468. if (!sei.payload) {
  9469. return;
  9470. } // ignore everything but user_data_registered_itu_t_t35
  9471. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  9472. return;
  9473. } // parse out the user data payload
  9474. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  9475. if (!userData) {
  9476. return;
  9477. } // Sometimes, the same segment # will be downloaded twice. To stop the
  9478. // caption data from being processed twice, we track the latest dts we've
  9479. // received and ignore everything with a dts before that. However, since
  9480. // data for a specific dts can be split across packets on either side of
  9481. // a segment boundary, we need to make sure we *don't* ignore the packets
  9482. // from the *next* segment that have dts === this.latestDts_. By constantly
  9483. // tracking the number of packets received with dts === this.latestDts_, we
  9484. // know how many should be ignored once we start receiving duplicates.
  9485. if (event.dts < this.latestDts_) {
  9486. // We've started getting older data, so set the flag.
  9487. this.ignoreNextEqualDts_ = true;
  9488. return;
  9489. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  9490. this.numSameDts_--;
  9491. if (!this.numSameDts_) {
  9492. // We've received the last duplicate packet, time to start processing again
  9493. this.ignoreNextEqualDts_ = false;
  9494. }
  9495. return;
  9496. } // parse out CC data packets and save them for later
  9497. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  9498. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  9499. if (this.latestDts_ !== event.dts) {
  9500. this.numSameDts_ = 0;
  9501. }
  9502. this.numSameDts_++;
  9503. this.latestDts_ = event.dts;
  9504. };
  9505. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  9506. this.ccStreams_.forEach(function (cc) {
  9507. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  9508. }, this);
  9509. };
  9510. CaptionStream$2.prototype.flushStream = function (flushType) {
  9511. // make sure we actually parsed captions before proceeding
  9512. if (!this.captionPackets_.length) {
  9513. this.flushCCStreams(flushType);
  9514. return;
  9515. } // In Chrome, the Array#sort function is not stable so add a
  9516. // presortIndex that we can use to ensure we get a stable-sort
  9517. this.captionPackets_.forEach(function (elem, idx) {
  9518. elem.presortIndex = idx;
  9519. }); // sort caption byte-pairs based on their PTS values
  9520. this.captionPackets_.sort(function (a, b) {
  9521. if (a.pts === b.pts) {
  9522. return a.presortIndex - b.presortIndex;
  9523. }
  9524. return a.pts - b.pts;
  9525. });
  9526. this.captionPackets_.forEach(function (packet) {
  9527. if (packet.type < 2) {
  9528. // Dispatch packet to the right Cea608Stream
  9529. this.dispatchCea608Packet(packet);
  9530. } else {
  9531. // Dispatch packet to the Cea708Stream
  9532. this.dispatchCea708Packet(packet);
  9533. }
  9534. }, this);
  9535. this.captionPackets_.length = 0;
  9536. this.flushCCStreams(flushType);
  9537. };
  9538. CaptionStream$2.prototype.flush = function () {
  9539. return this.flushStream('flush');
  9540. }; // Only called if handling partial data
  9541. CaptionStream$2.prototype.partialFlush = function () {
  9542. return this.flushStream('partialFlush');
  9543. };
  9544. CaptionStream$2.prototype.reset = function () {
  9545. this.latestDts_ = null;
  9546. this.ignoreNextEqualDts_ = false;
  9547. this.numSameDts_ = 0;
  9548. this.activeCea608Channel_ = [null, null];
  9549. this.ccStreams_.forEach(function (ccStream) {
  9550. ccStream.reset();
  9551. });
  9552. }; // From the CEA-608 spec:
  9553. /*
  9554. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  9555. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  9556. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  9557. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  9558. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  9559. * to switch to captioning or Text.
  9560. */
  9561. // With that in mind, we ignore any data between an XDS control code and a
  9562. // subsequent closed-captioning control code.
  9563. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  9564. // NOTE: packet.type is the CEA608 field
  9565. if (this.setsTextOrXDSActive(packet)) {
  9566. this.activeCea608Channel_[packet.type] = null;
  9567. } else if (this.setsChannel1Active(packet)) {
  9568. this.activeCea608Channel_[packet.type] = 0;
  9569. } else if (this.setsChannel2Active(packet)) {
  9570. this.activeCea608Channel_[packet.type] = 1;
  9571. }
  9572. if (this.activeCea608Channel_[packet.type] === null) {
  9573. // If we haven't received anything to set the active channel, or the
  9574. // packets are Text/XDS data, discard the data; we don't want jumbled
  9575. // captions
  9576. return;
  9577. }
  9578. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  9579. };
  9580. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  9581. return (packet.ccData & 0x7800) === 0x1000;
  9582. };
  9583. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  9584. return (packet.ccData & 0x7800) === 0x1800;
  9585. };
  9586. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  9587. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  9588. };
  9589. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  9590. if (this.parse708captions_) {
  9591. this.cc708Stream_.push(packet);
  9592. }
  9593. }; // ----------------------
  9594. // Session to Application
  9595. // ----------------------
  9596. // This hash maps special and extended character codes to their
  9597. // proper Unicode equivalent. The first one-byte key is just a
  9598. // non-standard character code. The two-byte keys that follow are
  9599. // the extended CEA708 character codes, along with the preceding
  9600. // 0x10 extended character byte to distinguish these codes from
  9601. // non-extended character codes. Every CEA708 character code that
  9602. // is not in this object maps directly to a standard unicode
  9603. // character code.
  9604. // The transparent space and non-breaking transparent space are
  9605. // technically not fully supported since there is no code to
  9606. // make them transparent, so they have normal non-transparent
  9607. // stand-ins.
  9608. // The special closed caption (CC) character isn't a standard
  9609. // unicode character, so a fairly similar unicode character was
  9610. // chosen in it's place.
  9611. var CHARACTER_TRANSLATION_708 = {
  9612. 0x7f: 0x266a,
  9613. // ♪
  9614. 0x1020: 0x20,
  9615. // Transparent Space
  9616. 0x1021: 0xa0,
  9617. // Nob-breaking Transparent Space
  9618. 0x1025: 0x2026,
  9619. // …
  9620. 0x102a: 0x0160,
  9621. // Š
  9622. 0x102c: 0x0152,
  9623. // Œ
  9624. 0x1030: 0x2588,
  9625. // █
  9626. 0x1031: 0x2018,
  9627. // ‘
  9628. 0x1032: 0x2019,
  9629. // ’
  9630. 0x1033: 0x201c,
  9631. // “
  9632. 0x1034: 0x201d,
  9633. // ”
  9634. 0x1035: 0x2022,
  9635. // •
  9636. 0x1039: 0x2122,
  9637. // ™
  9638. 0x103a: 0x0161,
  9639. // š
  9640. 0x103c: 0x0153,
  9641. // œ
  9642. 0x103d: 0x2120,
  9643. // ℠
  9644. 0x103f: 0x0178,
  9645. // Ÿ
  9646. 0x1076: 0x215b,
  9647. // ⅛
  9648. 0x1077: 0x215c,
  9649. // ⅜
  9650. 0x1078: 0x215d,
  9651. // ⅝
  9652. 0x1079: 0x215e,
  9653. // ⅞
  9654. 0x107a: 0x23d0,
  9655. // ⏐
  9656. 0x107b: 0x23a4,
  9657. // ⎤
  9658. 0x107c: 0x23a3,
  9659. // ⎣
  9660. 0x107d: 0x23af,
  9661. // ⎯
  9662. 0x107e: 0x23a6,
  9663. // ⎦
  9664. 0x107f: 0x23a1,
  9665. // ⎡
  9666. 0x10a0: 0x3138 // ㄸ (CC char)
  9667. };
  9668. var get708CharFromCode = function (code) {
  9669. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  9670. if (code & 0x1000 && code === newCode) {
  9671. // Invalid extended code
  9672. return '';
  9673. }
  9674. return String.fromCharCode(newCode);
  9675. };
  9676. var within708TextBlock = function (b) {
  9677. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  9678. };
  9679. var Cea708Window = function (windowNum) {
  9680. this.windowNum = windowNum;
  9681. this.reset();
  9682. };
  9683. Cea708Window.prototype.reset = function () {
  9684. this.clearText();
  9685. this.pendingNewLine = false;
  9686. this.winAttr = {};
  9687. this.penAttr = {};
  9688. this.penLoc = {};
  9689. this.penColor = {}; // These default values are arbitrary,
  9690. // defineWindow will usually override them
  9691. this.visible = 0;
  9692. this.rowLock = 0;
  9693. this.columnLock = 0;
  9694. this.priority = 0;
  9695. this.relativePositioning = 0;
  9696. this.anchorVertical = 0;
  9697. this.anchorHorizontal = 0;
  9698. this.anchorPoint = 0;
  9699. this.rowCount = 1;
  9700. this.virtualRowCount = this.rowCount + 1;
  9701. this.columnCount = 41;
  9702. this.windowStyle = 0;
  9703. this.penStyle = 0;
  9704. };
  9705. Cea708Window.prototype.getText = function () {
  9706. return this.rows.join('\n');
  9707. };
  9708. Cea708Window.prototype.clearText = function () {
  9709. this.rows = [''];
  9710. this.rowIdx = 0;
  9711. };
  9712. Cea708Window.prototype.newLine = function (pts) {
  9713. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  9714. this.beforeRowOverflow(pts);
  9715. }
  9716. if (this.rows.length > 0) {
  9717. this.rows.push('');
  9718. this.rowIdx++;
  9719. } // Show all virtual rows since there's no visible scrolling
  9720. while (this.rows.length > this.virtualRowCount) {
  9721. this.rows.shift();
  9722. this.rowIdx--;
  9723. }
  9724. };
  9725. Cea708Window.prototype.isEmpty = function () {
  9726. if (this.rows.length === 0) {
  9727. return true;
  9728. } else if (this.rows.length === 1) {
  9729. return this.rows[0] === '';
  9730. }
  9731. return false;
  9732. };
  9733. Cea708Window.prototype.addText = function (text) {
  9734. this.rows[this.rowIdx] += text;
  9735. };
  9736. Cea708Window.prototype.backspace = function () {
  9737. if (!this.isEmpty()) {
  9738. var row = this.rows[this.rowIdx];
  9739. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  9740. }
  9741. };
  9742. var Cea708Service = function (serviceNum, encoding, stream) {
  9743. this.serviceNum = serviceNum;
  9744. this.text = '';
  9745. this.currentWindow = new Cea708Window(-1);
  9746. this.windows = [];
  9747. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  9748. if (typeof encoding === 'string') {
  9749. this.createTextDecoder(encoding);
  9750. }
  9751. };
  9752. /**
  9753. * Initialize service windows
  9754. * Must be run before service use
  9755. *
  9756. * @param {Integer} pts PTS value
  9757. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  9758. */
  9759. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  9760. this.startPts = pts;
  9761. for (var win = 0; win < 8; win++) {
  9762. this.windows[win] = new Cea708Window(win);
  9763. if (typeof beforeRowOverflow === 'function') {
  9764. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  9765. }
  9766. }
  9767. };
  9768. /**
  9769. * Set current window of service to be affected by commands
  9770. *
  9771. * @param {Integer} windowNum Window number
  9772. */
  9773. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  9774. this.currentWindow = this.windows[windowNum];
  9775. };
  9776. /**
  9777. * Try to create a TextDecoder if it is natively supported
  9778. */
  9779. Cea708Service.prototype.createTextDecoder = function (encoding) {
  9780. if (typeof TextDecoder === 'undefined') {
  9781. this.stream.trigger('log', {
  9782. level: 'warn',
  9783. message: 'The `encoding` option is unsupported without TextDecoder support'
  9784. });
  9785. } else {
  9786. try {
  9787. this.textDecoder_ = new TextDecoder(encoding);
  9788. } catch (error) {
  9789. this.stream.trigger('log', {
  9790. level: 'warn',
  9791. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  9792. });
  9793. }
  9794. }
  9795. };
  9796. var Cea708Stream = function (options) {
  9797. options = options || {};
  9798. Cea708Stream.prototype.init.call(this);
  9799. var self = this;
  9800. var captionServices = options.captionServices || {};
  9801. var captionServiceEncodings = {};
  9802. var serviceProps; // Get service encodings from captionServices option block
  9803. Object.keys(captionServices).forEach(serviceName => {
  9804. serviceProps = captionServices[serviceName];
  9805. if (/^SERVICE/.test(serviceName)) {
  9806. captionServiceEncodings[serviceName] = serviceProps.encoding;
  9807. }
  9808. });
  9809. this.serviceEncodings = captionServiceEncodings;
  9810. this.current708Packet = null;
  9811. this.services = {};
  9812. this.push = function (packet) {
  9813. if (packet.type === 3) {
  9814. // 708 packet start
  9815. self.new708Packet();
  9816. self.add708Bytes(packet);
  9817. } else {
  9818. if (self.current708Packet === null) {
  9819. // This should only happen at the start of a file if there's no packet start.
  9820. self.new708Packet();
  9821. }
  9822. self.add708Bytes(packet);
  9823. }
  9824. };
  9825. };
  9826. Cea708Stream.prototype = new Stream$7();
  9827. /**
  9828. * Push current 708 packet, create new 708 packet.
  9829. */
  9830. Cea708Stream.prototype.new708Packet = function () {
  9831. if (this.current708Packet !== null) {
  9832. this.push708Packet();
  9833. }
  9834. this.current708Packet = {
  9835. data: [],
  9836. ptsVals: []
  9837. };
  9838. };
  9839. /**
  9840. * Add pts and both bytes from packet into current 708 packet.
  9841. */
  9842. Cea708Stream.prototype.add708Bytes = function (packet) {
  9843. var data = packet.ccData;
  9844. var byte0 = data >>> 8;
  9845. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  9846. // that service blocks will always line up with byte pairs.
  9847. this.current708Packet.ptsVals.push(packet.pts);
  9848. this.current708Packet.data.push(byte0);
  9849. this.current708Packet.data.push(byte1);
  9850. };
  9851. /**
  9852. * Parse completed 708 packet into service blocks and push each service block.
  9853. */
  9854. Cea708Stream.prototype.push708Packet = function () {
  9855. var packet708 = this.current708Packet;
  9856. var packetData = packet708.data;
  9857. var serviceNum = null;
  9858. var blockSize = null;
  9859. var i = 0;
  9860. var b = packetData[i++];
  9861. packet708.seq = b >> 6;
  9862. packet708.sizeCode = b & 0x3f; // 0b00111111;
  9863. for (; i < packetData.length; i++) {
  9864. b = packetData[i++];
  9865. serviceNum = b >> 5;
  9866. blockSize = b & 0x1f; // 0b00011111
  9867. if (serviceNum === 7 && blockSize > 0) {
  9868. // Extended service num
  9869. b = packetData[i++];
  9870. serviceNum = b;
  9871. }
  9872. this.pushServiceBlock(serviceNum, i, blockSize);
  9873. if (blockSize > 0) {
  9874. i += blockSize - 1;
  9875. }
  9876. }
  9877. };
  9878. /**
  9879. * Parse service block, execute commands, read text.
  9880. *
  9881. * Note: While many of these commands serve important purposes,
  9882. * many others just parse out the parameters or attributes, but
  9883. * nothing is done with them because this is not a full and complete
  9884. * implementation of the entire 708 spec.
  9885. *
  9886. * @param {Integer} serviceNum Service number
  9887. * @param {Integer} start Start index of the 708 packet data
  9888. * @param {Integer} size Block size
  9889. */
  9890. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  9891. var b;
  9892. var i = start;
  9893. var packetData = this.current708Packet.data;
  9894. var service = this.services[serviceNum];
  9895. if (!service) {
  9896. service = this.initService(serviceNum, i);
  9897. }
  9898. for (; i < start + size && i < packetData.length; i++) {
  9899. b = packetData[i];
  9900. if (within708TextBlock(b)) {
  9901. i = this.handleText(i, service);
  9902. } else if (b === 0x18) {
  9903. i = this.multiByteCharacter(i, service);
  9904. } else if (b === 0x10) {
  9905. i = this.extendedCommands(i, service);
  9906. } else if (0x80 <= b && b <= 0x87) {
  9907. i = this.setCurrentWindow(i, service);
  9908. } else if (0x98 <= b && b <= 0x9f) {
  9909. i = this.defineWindow(i, service);
  9910. } else if (b === 0x88) {
  9911. i = this.clearWindows(i, service);
  9912. } else if (b === 0x8c) {
  9913. i = this.deleteWindows(i, service);
  9914. } else if (b === 0x89) {
  9915. i = this.displayWindows(i, service);
  9916. } else if (b === 0x8a) {
  9917. i = this.hideWindows(i, service);
  9918. } else if (b === 0x8b) {
  9919. i = this.toggleWindows(i, service);
  9920. } else if (b === 0x97) {
  9921. i = this.setWindowAttributes(i, service);
  9922. } else if (b === 0x90) {
  9923. i = this.setPenAttributes(i, service);
  9924. } else if (b === 0x91) {
  9925. i = this.setPenColor(i, service);
  9926. } else if (b === 0x92) {
  9927. i = this.setPenLocation(i, service);
  9928. } else if (b === 0x8f) {
  9929. service = this.reset(i, service);
  9930. } else if (b === 0x08) {
  9931. // BS: Backspace
  9932. service.currentWindow.backspace();
  9933. } else if (b === 0x0c) {
  9934. // FF: Form feed
  9935. service.currentWindow.clearText();
  9936. } else if (b === 0x0d) {
  9937. // CR: Carriage return
  9938. service.currentWindow.pendingNewLine = true;
  9939. } else if (b === 0x0e) {
  9940. // HCR: Horizontal carriage return
  9941. service.currentWindow.clearText();
  9942. } else if (b === 0x8d) {
  9943. // DLY: Delay, nothing to do
  9944. i++;
  9945. } else ;
  9946. }
  9947. };
  9948. /**
  9949. * Execute an extended command
  9950. *
  9951. * @param {Integer} i Current index in the 708 packet
  9952. * @param {Service} service The service object to be affected
  9953. * @return {Integer} New index after parsing
  9954. */
  9955. Cea708Stream.prototype.extendedCommands = function (i, service) {
  9956. var packetData = this.current708Packet.data;
  9957. var b = packetData[++i];
  9958. if (within708TextBlock(b)) {
  9959. i = this.handleText(i, service, {
  9960. isExtended: true
  9961. });
  9962. }
  9963. return i;
  9964. };
  9965. /**
  9966. * Get PTS value of a given byte index
  9967. *
  9968. * @param {Integer} byteIndex Index of the byte
  9969. * @return {Integer} PTS
  9970. */
  9971. Cea708Stream.prototype.getPts = function (byteIndex) {
  9972. // There's 1 pts value per 2 bytes
  9973. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  9974. };
  9975. /**
  9976. * Initializes a service
  9977. *
  9978. * @param {Integer} serviceNum Service number
  9979. * @return {Service} Initialized service object
  9980. */
  9981. Cea708Stream.prototype.initService = function (serviceNum, i) {
  9982. var serviceName = 'SERVICE' + serviceNum;
  9983. var self = this;
  9984. var serviceName;
  9985. var encoding;
  9986. if (serviceName in this.serviceEncodings) {
  9987. encoding = this.serviceEncodings[serviceName];
  9988. }
  9989. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  9990. this.services[serviceNum].init(this.getPts(i), function (pts) {
  9991. self.flushDisplayed(pts, self.services[serviceNum]);
  9992. });
  9993. return this.services[serviceNum];
  9994. };
  9995. /**
  9996. * Execute text writing to current window
  9997. *
  9998. * @param {Integer} i Current index in the 708 packet
  9999. * @param {Service} service The service object to be affected
  10000. * @return {Integer} New index after parsing
  10001. */
  10002. Cea708Stream.prototype.handleText = function (i, service, options) {
  10003. var isExtended = options && options.isExtended;
  10004. var isMultiByte = options && options.isMultiByte;
  10005. var packetData = this.current708Packet.data;
  10006. var extended = isExtended ? 0x1000 : 0x0000;
  10007. var currentByte = packetData[i];
  10008. var nextByte = packetData[i + 1];
  10009. var win = service.currentWindow;
  10010. var char;
  10011. var charCodeArray; // Use the TextDecoder if one was created for this service
  10012. if (service.textDecoder_ && !isExtended) {
  10013. if (isMultiByte) {
  10014. charCodeArray = [currentByte, nextByte];
  10015. i++;
  10016. } else {
  10017. charCodeArray = [currentByte];
  10018. }
  10019. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  10020. } else {
  10021. char = get708CharFromCode(extended | currentByte);
  10022. }
  10023. if (win.pendingNewLine && !win.isEmpty()) {
  10024. win.newLine(this.getPts(i));
  10025. }
  10026. win.pendingNewLine = false;
  10027. win.addText(char);
  10028. return i;
  10029. };
  10030. /**
  10031. * Handle decoding of multibyte character
  10032. *
  10033. * @param {Integer} i Current index in the 708 packet
  10034. * @param {Service} service The service object to be affected
  10035. * @return {Integer} New index after parsing
  10036. */
  10037. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  10038. var packetData = this.current708Packet.data;
  10039. var firstByte = packetData[i + 1];
  10040. var secondByte = packetData[i + 2];
  10041. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  10042. i = this.handleText(++i, service, {
  10043. isMultiByte: true
  10044. });
  10045. }
  10046. return i;
  10047. };
  10048. /**
  10049. * Parse and execute the CW# command.
  10050. *
  10051. * Set the current window.
  10052. *
  10053. * @param {Integer} i Current index in the 708 packet
  10054. * @param {Service} service The service object to be affected
  10055. * @return {Integer} New index after parsing
  10056. */
  10057. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  10058. var packetData = this.current708Packet.data;
  10059. var b = packetData[i];
  10060. var windowNum = b & 0x07;
  10061. service.setCurrentWindow(windowNum);
  10062. return i;
  10063. };
  10064. /**
  10065. * Parse and execute the DF# command.
  10066. *
  10067. * Define a window and set it as the current window.
  10068. *
  10069. * @param {Integer} i Current index in the 708 packet
  10070. * @param {Service} service The service object to be affected
  10071. * @return {Integer} New index after parsing
  10072. */
  10073. Cea708Stream.prototype.defineWindow = function (i, service) {
  10074. var packetData = this.current708Packet.data;
  10075. var b = packetData[i];
  10076. var windowNum = b & 0x07;
  10077. service.setCurrentWindow(windowNum);
  10078. var win = service.currentWindow;
  10079. b = packetData[++i];
  10080. win.visible = (b & 0x20) >> 5; // v
  10081. win.rowLock = (b & 0x10) >> 4; // rl
  10082. win.columnLock = (b & 0x08) >> 3; // cl
  10083. win.priority = b & 0x07; // p
  10084. b = packetData[++i];
  10085. win.relativePositioning = (b & 0x80) >> 7; // rp
  10086. win.anchorVertical = b & 0x7f; // av
  10087. b = packetData[++i];
  10088. win.anchorHorizontal = b; // ah
  10089. b = packetData[++i];
  10090. win.anchorPoint = (b & 0xf0) >> 4; // ap
  10091. win.rowCount = b & 0x0f; // rc
  10092. b = packetData[++i];
  10093. win.columnCount = b & 0x3f; // cc
  10094. b = packetData[++i];
  10095. win.windowStyle = (b & 0x38) >> 3; // ws
  10096. win.penStyle = b & 0x07; // ps
  10097. // The spec says there are (rowCount+1) "virtual rows"
  10098. win.virtualRowCount = win.rowCount + 1;
  10099. return i;
  10100. };
  10101. /**
  10102. * Parse and execute the SWA command.
  10103. *
  10104. * Set attributes of the current window.
  10105. *
  10106. * @param {Integer} i Current index in the 708 packet
  10107. * @param {Service} service The service object to be affected
  10108. * @return {Integer} New index after parsing
  10109. */
  10110. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  10111. var packetData = this.current708Packet.data;
  10112. var b = packetData[i];
  10113. var winAttr = service.currentWindow.winAttr;
  10114. b = packetData[++i];
  10115. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  10116. winAttr.fillRed = (b & 0x30) >> 4; // fr
  10117. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  10118. winAttr.fillBlue = b & 0x03; // fb
  10119. b = packetData[++i];
  10120. winAttr.borderType = (b & 0xc0) >> 6; // bt
  10121. winAttr.borderRed = (b & 0x30) >> 4; // br
  10122. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  10123. winAttr.borderBlue = b & 0x03; // bb
  10124. b = packetData[++i];
  10125. winAttr.borderType += (b & 0x80) >> 5; // bt
  10126. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  10127. winAttr.printDirection = (b & 0x30) >> 4; // pd
  10128. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  10129. winAttr.justify = b & 0x03; // j
  10130. b = packetData[++i];
  10131. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  10132. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  10133. winAttr.displayEffect = b & 0x03; // de
  10134. return i;
  10135. };
  10136. /**
  10137. * Gather text from all displayed windows and push a caption to output.
  10138. *
  10139. * @param {Integer} i Current index in the 708 packet
  10140. * @param {Service} service The service object to be affected
  10141. */
  10142. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  10143. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  10144. // display text in the correct order, but sample files so far have not shown any issue.
  10145. for (var winId = 0; winId < 8; winId++) {
  10146. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  10147. displayedText.push(service.windows[winId].getText());
  10148. }
  10149. }
  10150. service.endPts = pts;
  10151. service.text = displayedText.join('\n\n');
  10152. this.pushCaption(service);
  10153. service.startPts = pts;
  10154. };
  10155. /**
  10156. * Push a caption to output if the caption contains text.
  10157. *
  10158. * @param {Service} service The service object to be affected
  10159. */
  10160. Cea708Stream.prototype.pushCaption = function (service) {
  10161. if (service.text !== '') {
  10162. this.trigger('data', {
  10163. startPts: service.startPts,
  10164. endPts: service.endPts,
  10165. text: service.text,
  10166. stream: 'cc708_' + service.serviceNum
  10167. });
  10168. service.text = '';
  10169. service.startPts = service.endPts;
  10170. }
  10171. };
  10172. /**
  10173. * Parse and execute the DSW command.
  10174. *
  10175. * Set visible property of windows based on the parsed bitmask.
  10176. *
  10177. * @param {Integer} i Current index in the 708 packet
  10178. * @param {Service} service The service object to be affected
  10179. * @return {Integer} New index after parsing
  10180. */
  10181. Cea708Stream.prototype.displayWindows = function (i, service) {
  10182. var packetData = this.current708Packet.data;
  10183. var b = packetData[++i];
  10184. var pts = this.getPts(i);
  10185. this.flushDisplayed(pts, service);
  10186. for (var winId = 0; winId < 8; winId++) {
  10187. if (b & 0x01 << winId) {
  10188. service.windows[winId].visible = 1;
  10189. }
  10190. }
  10191. return i;
  10192. };
  10193. /**
  10194. * Parse and execute the HDW command.
  10195. *
  10196. * Set visible property of windows based on the parsed bitmask.
  10197. *
  10198. * @param {Integer} i Current index in the 708 packet
  10199. * @param {Service} service The service object to be affected
  10200. * @return {Integer} New index after parsing
  10201. */
  10202. Cea708Stream.prototype.hideWindows = function (i, service) {
  10203. var packetData = this.current708Packet.data;
  10204. var b = packetData[++i];
  10205. var pts = this.getPts(i);
  10206. this.flushDisplayed(pts, service);
  10207. for (var winId = 0; winId < 8; winId++) {
  10208. if (b & 0x01 << winId) {
  10209. service.windows[winId].visible = 0;
  10210. }
  10211. }
  10212. return i;
  10213. };
  10214. /**
  10215. * Parse and execute the TGW command.
  10216. *
  10217. * Set visible property of windows based on the parsed bitmask.
  10218. *
  10219. * @param {Integer} i Current index in the 708 packet
  10220. * @param {Service} service The service object to be affected
  10221. * @return {Integer} New index after parsing
  10222. */
  10223. Cea708Stream.prototype.toggleWindows = function (i, service) {
  10224. var packetData = this.current708Packet.data;
  10225. var b = packetData[++i];
  10226. var pts = this.getPts(i);
  10227. this.flushDisplayed(pts, service);
  10228. for (var winId = 0; winId < 8; winId++) {
  10229. if (b & 0x01 << winId) {
  10230. service.windows[winId].visible ^= 1;
  10231. }
  10232. }
  10233. return i;
  10234. };
  10235. /**
  10236. * Parse and execute the CLW command.
  10237. *
  10238. * Clear text of windows based on the parsed bitmask.
  10239. *
  10240. * @param {Integer} i Current index in the 708 packet
  10241. * @param {Service} service The service object to be affected
  10242. * @return {Integer} New index after parsing
  10243. */
  10244. Cea708Stream.prototype.clearWindows = function (i, service) {
  10245. var packetData = this.current708Packet.data;
  10246. var b = packetData[++i];
  10247. var pts = this.getPts(i);
  10248. this.flushDisplayed(pts, service);
  10249. for (var winId = 0; winId < 8; winId++) {
  10250. if (b & 0x01 << winId) {
  10251. service.windows[winId].clearText();
  10252. }
  10253. }
  10254. return i;
  10255. };
  10256. /**
  10257. * Parse and execute the DLW command.
  10258. *
  10259. * Re-initialize windows based on the parsed bitmask.
  10260. *
  10261. * @param {Integer} i Current index in the 708 packet
  10262. * @param {Service} service The service object to be affected
  10263. * @return {Integer} New index after parsing
  10264. */
  10265. Cea708Stream.prototype.deleteWindows = function (i, service) {
  10266. var packetData = this.current708Packet.data;
  10267. var b = packetData[++i];
  10268. var pts = this.getPts(i);
  10269. this.flushDisplayed(pts, service);
  10270. for (var winId = 0; winId < 8; winId++) {
  10271. if (b & 0x01 << winId) {
  10272. service.windows[winId].reset();
  10273. }
  10274. }
  10275. return i;
  10276. };
  10277. /**
  10278. * Parse and execute the SPA command.
  10279. *
  10280. * Set pen attributes of the current window.
  10281. *
  10282. * @param {Integer} i Current index in the 708 packet
  10283. * @param {Service} service The service object to be affected
  10284. * @return {Integer} New index after parsing
  10285. */
  10286. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  10287. var packetData = this.current708Packet.data;
  10288. var b = packetData[i];
  10289. var penAttr = service.currentWindow.penAttr;
  10290. b = packetData[++i];
  10291. penAttr.textTag = (b & 0xf0) >> 4; // tt
  10292. penAttr.offset = (b & 0x0c) >> 2; // o
  10293. penAttr.penSize = b & 0x03; // s
  10294. b = packetData[++i];
  10295. penAttr.italics = (b & 0x80) >> 7; // i
  10296. penAttr.underline = (b & 0x40) >> 6; // u
  10297. penAttr.edgeType = (b & 0x38) >> 3; // et
  10298. penAttr.fontStyle = b & 0x07; // fs
  10299. return i;
  10300. };
  10301. /**
  10302. * Parse and execute the SPC command.
  10303. *
  10304. * Set pen color of the current window.
  10305. *
  10306. * @param {Integer} i Current index in the 708 packet
  10307. * @param {Service} service The service object to be affected
  10308. * @return {Integer} New index after parsing
  10309. */
  10310. Cea708Stream.prototype.setPenColor = function (i, service) {
  10311. var packetData = this.current708Packet.data;
  10312. var b = packetData[i];
  10313. var penColor = service.currentWindow.penColor;
  10314. b = packetData[++i];
  10315. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  10316. penColor.fgRed = (b & 0x30) >> 4; // fr
  10317. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  10318. penColor.fgBlue = b & 0x03; // fb
  10319. b = packetData[++i];
  10320. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  10321. penColor.bgRed = (b & 0x30) >> 4; // br
  10322. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  10323. penColor.bgBlue = b & 0x03; // bb
  10324. b = packetData[++i];
  10325. penColor.edgeRed = (b & 0x30) >> 4; // er
  10326. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  10327. penColor.edgeBlue = b & 0x03; // eb
  10328. return i;
  10329. };
  10330. /**
  10331. * Parse and execute the SPL command.
  10332. *
  10333. * Set pen location of the current window.
  10334. *
  10335. * @param {Integer} i Current index in the 708 packet
  10336. * @param {Service} service The service object to be affected
  10337. * @return {Integer} New index after parsing
  10338. */
  10339. Cea708Stream.prototype.setPenLocation = function (i, service) {
  10340. var packetData = this.current708Packet.data;
  10341. var b = packetData[i];
  10342. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  10343. service.currentWindow.pendingNewLine = true;
  10344. b = packetData[++i];
  10345. penLoc.row = b & 0x0f; // r
  10346. b = packetData[++i];
  10347. penLoc.column = b & 0x3f; // c
  10348. return i;
  10349. };
  10350. /**
  10351. * Execute the RST command.
  10352. *
  10353. * Reset service to a clean slate. Re-initialize.
  10354. *
  10355. * @param {Integer} i Current index in the 708 packet
  10356. * @param {Service} service The service object to be affected
  10357. * @return {Service} Re-initialized service
  10358. */
  10359. Cea708Stream.prototype.reset = function (i, service) {
  10360. var pts = this.getPts(i);
  10361. this.flushDisplayed(pts, service);
  10362. return this.initService(service.serviceNum, i);
  10363. }; // This hash maps non-ASCII, special, and extended character codes to their
  10364. // proper Unicode equivalent. The first keys that are only a single byte
  10365. // are the non-standard ASCII characters, which simply map the CEA608 byte
  10366. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  10367. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  10368. // can be performed regardless of the field and data channel on which the
  10369. // character code was received.
  10370. var CHARACTER_TRANSLATION = {
  10371. 0x2a: 0xe1,
  10372. // á
  10373. 0x5c: 0xe9,
  10374. // é
  10375. 0x5e: 0xed,
  10376. // í
  10377. 0x5f: 0xf3,
  10378. // ó
  10379. 0x60: 0xfa,
  10380. // ú
  10381. 0x7b: 0xe7,
  10382. // ç
  10383. 0x7c: 0xf7,
  10384. // ÷
  10385. 0x7d: 0xd1,
  10386. // Ñ
  10387. 0x7e: 0xf1,
  10388. // ñ
  10389. 0x7f: 0x2588,
  10390. // █
  10391. 0x0130: 0xae,
  10392. // ®
  10393. 0x0131: 0xb0,
  10394. // °
  10395. 0x0132: 0xbd,
  10396. // ½
  10397. 0x0133: 0xbf,
  10398. // ¿
  10399. 0x0134: 0x2122,
  10400. // ™
  10401. 0x0135: 0xa2,
  10402. // ¢
  10403. 0x0136: 0xa3,
  10404. // £
  10405. 0x0137: 0x266a,
  10406. // ♪
  10407. 0x0138: 0xe0,
  10408. // à
  10409. 0x0139: 0xa0,
  10410. //
  10411. 0x013a: 0xe8,
  10412. // è
  10413. 0x013b: 0xe2,
  10414. // â
  10415. 0x013c: 0xea,
  10416. // ê
  10417. 0x013d: 0xee,
  10418. // î
  10419. 0x013e: 0xf4,
  10420. // ô
  10421. 0x013f: 0xfb,
  10422. // û
  10423. 0x0220: 0xc1,
  10424. // Á
  10425. 0x0221: 0xc9,
  10426. // É
  10427. 0x0222: 0xd3,
  10428. // Ó
  10429. 0x0223: 0xda,
  10430. // Ú
  10431. 0x0224: 0xdc,
  10432. // Ü
  10433. 0x0225: 0xfc,
  10434. // ü
  10435. 0x0226: 0x2018,
  10436. // ‘
  10437. 0x0227: 0xa1,
  10438. // ¡
  10439. 0x0228: 0x2a,
  10440. // *
  10441. 0x0229: 0x27,
  10442. // '
  10443. 0x022a: 0x2014,
  10444. // —
  10445. 0x022b: 0xa9,
  10446. // ©
  10447. 0x022c: 0x2120,
  10448. // ℠
  10449. 0x022d: 0x2022,
  10450. // •
  10451. 0x022e: 0x201c,
  10452. // “
  10453. 0x022f: 0x201d,
  10454. // ”
  10455. 0x0230: 0xc0,
  10456. // À
  10457. 0x0231: 0xc2,
  10458. // Â
  10459. 0x0232: 0xc7,
  10460. // Ç
  10461. 0x0233: 0xc8,
  10462. // È
  10463. 0x0234: 0xca,
  10464. // Ê
  10465. 0x0235: 0xcb,
  10466. // Ë
  10467. 0x0236: 0xeb,
  10468. // ë
  10469. 0x0237: 0xce,
  10470. // Î
  10471. 0x0238: 0xcf,
  10472. // Ï
  10473. 0x0239: 0xef,
  10474. // ï
  10475. 0x023a: 0xd4,
  10476. // Ô
  10477. 0x023b: 0xd9,
  10478. // Ù
  10479. 0x023c: 0xf9,
  10480. // ù
  10481. 0x023d: 0xdb,
  10482. // Û
  10483. 0x023e: 0xab,
  10484. // «
  10485. 0x023f: 0xbb,
  10486. // »
  10487. 0x0320: 0xc3,
  10488. // Ã
  10489. 0x0321: 0xe3,
  10490. // ã
  10491. 0x0322: 0xcd,
  10492. // Í
  10493. 0x0323: 0xcc,
  10494. // Ì
  10495. 0x0324: 0xec,
  10496. // ì
  10497. 0x0325: 0xd2,
  10498. // Ò
  10499. 0x0326: 0xf2,
  10500. // ò
  10501. 0x0327: 0xd5,
  10502. // Õ
  10503. 0x0328: 0xf5,
  10504. // õ
  10505. 0x0329: 0x7b,
  10506. // {
  10507. 0x032a: 0x7d,
  10508. // }
  10509. 0x032b: 0x5c,
  10510. // \
  10511. 0x032c: 0x5e,
  10512. // ^
  10513. 0x032d: 0x5f,
  10514. // _
  10515. 0x032e: 0x7c,
  10516. // |
  10517. 0x032f: 0x7e,
  10518. // ~
  10519. 0x0330: 0xc4,
  10520. // Ä
  10521. 0x0331: 0xe4,
  10522. // ä
  10523. 0x0332: 0xd6,
  10524. // Ö
  10525. 0x0333: 0xf6,
  10526. // ö
  10527. 0x0334: 0xdf,
  10528. // ß
  10529. 0x0335: 0xa5,
  10530. // ¥
  10531. 0x0336: 0xa4,
  10532. // ¤
  10533. 0x0337: 0x2502,
  10534. // │
  10535. 0x0338: 0xc5,
  10536. // Å
  10537. 0x0339: 0xe5,
  10538. // å
  10539. 0x033a: 0xd8,
  10540. // Ø
  10541. 0x033b: 0xf8,
  10542. // ø
  10543. 0x033c: 0x250c,
  10544. // ┌
  10545. 0x033d: 0x2510,
  10546. // ┐
  10547. 0x033e: 0x2514,
  10548. // └
  10549. 0x033f: 0x2518 // ┘
  10550. };
  10551. var getCharFromCode = function (code) {
  10552. if (code === null) {
  10553. return '';
  10554. }
  10555. code = CHARACTER_TRANSLATION[code] || code;
  10556. return String.fromCharCode(code);
  10557. }; // the index of the last row in a CEA-608 display buffer
  10558. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  10559. // getting it through bit logic.
  10560. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
  10561. // cells. The "bottom" row is the last element in the outer array.
  10562. var createDisplayBuffer = function () {
  10563. var result = [],
  10564. i = BOTTOM_ROW + 1;
  10565. while (i--) {
  10566. result.push('');
  10567. }
  10568. return result;
  10569. };
  10570. var Cea608Stream = function (field, dataChannel) {
  10571. Cea608Stream.prototype.init.call(this);
  10572. this.field_ = field || 0;
  10573. this.dataChannel_ = dataChannel || 0;
  10574. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  10575. this.setConstants();
  10576. this.reset();
  10577. this.push = function (packet) {
  10578. var data, swap, char0, char1, text; // remove the parity bits
  10579. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  10580. if (data === this.lastControlCode_) {
  10581. this.lastControlCode_ = null;
  10582. return;
  10583. } // Store control codes
  10584. if ((data & 0xf000) === 0x1000) {
  10585. this.lastControlCode_ = data;
  10586. } else if (data !== this.PADDING_) {
  10587. this.lastControlCode_ = null;
  10588. }
  10589. char0 = data >>> 8;
  10590. char1 = data & 0xff;
  10591. if (data === this.PADDING_) {
  10592. return;
  10593. } else if (data === this.RESUME_CAPTION_LOADING_) {
  10594. this.mode_ = 'popOn';
  10595. } else if (data === this.END_OF_CAPTION_) {
  10596. // If an EOC is received while in paint-on mode, the displayed caption
  10597. // text should be swapped to non-displayed memory as if it was a pop-on
  10598. // caption. Because of that, we should explicitly switch back to pop-on
  10599. // mode
  10600. this.mode_ = 'popOn';
  10601. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  10602. this.flushDisplayed(packet.pts); // flip memory
  10603. swap = this.displayed_;
  10604. this.displayed_ = this.nonDisplayed_;
  10605. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  10606. this.startPts_ = packet.pts;
  10607. } else if (data === this.ROLL_UP_2_ROWS_) {
  10608. this.rollUpRows_ = 2;
  10609. this.setRollUp(packet.pts);
  10610. } else if (data === this.ROLL_UP_3_ROWS_) {
  10611. this.rollUpRows_ = 3;
  10612. this.setRollUp(packet.pts);
  10613. } else if (data === this.ROLL_UP_4_ROWS_) {
  10614. this.rollUpRows_ = 4;
  10615. this.setRollUp(packet.pts);
  10616. } else if (data === this.CARRIAGE_RETURN_) {
  10617. this.clearFormatting(packet.pts);
  10618. this.flushDisplayed(packet.pts);
  10619. this.shiftRowsUp_();
  10620. this.startPts_ = packet.pts;
  10621. } else if (data === this.BACKSPACE_) {
  10622. if (this.mode_ === 'popOn') {
  10623. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  10624. } else {
  10625. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  10626. }
  10627. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  10628. this.flushDisplayed(packet.pts);
  10629. this.displayed_ = createDisplayBuffer();
  10630. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  10631. this.nonDisplayed_ = createDisplayBuffer();
  10632. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  10633. if (this.mode_ !== 'paintOn') {
  10634. // NOTE: This should be removed when proper caption positioning is
  10635. // implemented
  10636. this.flushDisplayed(packet.pts);
  10637. this.displayed_ = createDisplayBuffer();
  10638. }
  10639. this.mode_ = 'paintOn';
  10640. this.startPts_ = packet.pts; // Append special characters to caption text
  10641. } else if (this.isSpecialCharacter(char0, char1)) {
  10642. // Bitmask char0 so that we can apply character transformations
  10643. // regardless of field and data channel.
  10644. // Then byte-shift to the left and OR with char1 so we can pass the
  10645. // entire character code to `getCharFromCode`.
  10646. char0 = (char0 & 0x03) << 8;
  10647. text = getCharFromCode(char0 | char1);
  10648. this[this.mode_](packet.pts, text);
  10649. this.column_++; // Append extended characters to caption text
  10650. } else if (this.isExtCharacter(char0, char1)) {
  10651. // Extended characters always follow their "non-extended" equivalents.
  10652. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  10653. // decoders are supposed to drop the "è", while compliant decoders
  10654. // backspace the "e" and insert "è".
  10655. // Delete the previous character
  10656. if (this.mode_ === 'popOn') {
  10657. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  10658. } else {
  10659. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  10660. } // Bitmask char0 so that we can apply character transformations
  10661. // regardless of field and data channel.
  10662. // Then byte-shift to the left and OR with char1 so we can pass the
  10663. // entire character code to `getCharFromCode`.
  10664. char0 = (char0 & 0x03) << 8;
  10665. text = getCharFromCode(char0 | char1);
  10666. this[this.mode_](packet.pts, text);
  10667. this.column_++; // Process mid-row codes
  10668. } else if (this.isMidRowCode(char0, char1)) {
  10669. // Attributes are not additive, so clear all formatting
  10670. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  10671. // should be replaced with spaces, so add one now
  10672. this[this.mode_](packet.pts, ' ');
  10673. this.column_++;
  10674. if ((char1 & 0xe) === 0xe) {
  10675. this.addFormatting(packet.pts, ['i']);
  10676. }
  10677. if ((char1 & 0x1) === 0x1) {
  10678. this.addFormatting(packet.pts, ['u']);
  10679. } // Detect offset control codes and adjust cursor
  10680. } else if (this.isOffsetControlCode(char0, char1)) {
  10681. // Cursor position is set by indent PAC (see below) in 4-column
  10682. // increments, with an additional offset code of 1-3 to reach any
  10683. // of the 32 columns specified by CEA-608. So all we need to do
  10684. // here is increment the column cursor by the given offset.
  10685. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  10686. } else if (this.isPAC(char0, char1)) {
  10687. // There's no logic for PAC -> row mapping, so we have to just
  10688. // find the row code in an array and use its index :(
  10689. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  10690. if (this.mode_ === 'rollUp') {
  10691. // This implies that the base row is incorrectly set.
  10692. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  10693. // of roll-up rows set.
  10694. if (row - this.rollUpRows_ + 1 < 0) {
  10695. row = this.rollUpRows_ - 1;
  10696. }
  10697. this.setRollUp(packet.pts, row);
  10698. }
  10699. if (row !== this.row_) {
  10700. // formatting is only persistent for current row
  10701. this.clearFormatting(packet.pts);
  10702. this.row_ = row;
  10703. } // All PACs can apply underline, so detect and apply
  10704. // (All odd-numbered second bytes set underline)
  10705. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  10706. this.addFormatting(packet.pts, ['u']);
  10707. }
  10708. if ((data & 0x10) === 0x10) {
  10709. // We've got an indent level code. Each successive even number
  10710. // increments the column cursor by 4, so we can get the desired
  10711. // column position by bit-shifting to the right (to get n/2)
  10712. // and multiplying by 4.
  10713. this.column_ = ((data & 0xe) >> 1) * 4;
  10714. }
  10715. if (this.isColorPAC(char1)) {
  10716. // it's a color code, though we only support white, which
  10717. // can be either normal or italicized. white italics can be
  10718. // either 0x4e or 0x6e depending on the row, so we just
  10719. // bitwise-and with 0xe to see if italics should be turned on
  10720. if ((char1 & 0xe) === 0xe) {
  10721. this.addFormatting(packet.pts, ['i']);
  10722. }
  10723. } // We have a normal character in char0, and possibly one in char1
  10724. } else if (this.isNormalChar(char0)) {
  10725. if (char1 === 0x00) {
  10726. char1 = null;
  10727. }
  10728. text = getCharFromCode(char0);
  10729. text += getCharFromCode(char1);
  10730. this[this.mode_](packet.pts, text);
  10731. this.column_ += text.length;
  10732. } // finish data processing
  10733. };
  10734. };
  10735. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  10736. // display buffer
  10737. Cea608Stream.prototype.flushDisplayed = function (pts) {
  10738. var content = this.displayed_ // remove spaces from the start and end of the string
  10739. .map(function (row, index) {
  10740. try {
  10741. return row.trim();
  10742. } catch (e) {
  10743. // Ordinarily, this shouldn't happen. However, caption
  10744. // parsing errors should not throw exceptions and
  10745. // break playback.
  10746. this.trigger('log', {
  10747. level: 'warn',
  10748. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  10749. });
  10750. return '';
  10751. }
  10752. }, this) // combine all text rows to display in one cue
  10753. .join('\n') // and remove blank rows from the start and end, but not the middle
  10754. .replace(/^\n+|\n+$/g, '');
  10755. if (content.length) {
  10756. this.trigger('data', {
  10757. startPts: this.startPts_,
  10758. endPts: pts,
  10759. text: content,
  10760. stream: this.name_
  10761. });
  10762. }
  10763. };
  10764. /**
  10765. * Zero out the data, used for startup and on seek
  10766. */
  10767. Cea608Stream.prototype.reset = function () {
  10768. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  10769. // actually display captions. If a caption is shifted to a row
  10770. // with a lower index than this, it is cleared from the display
  10771. // buffer
  10772. this.topRow_ = 0;
  10773. this.startPts_ = 0;
  10774. this.displayed_ = createDisplayBuffer();
  10775. this.nonDisplayed_ = createDisplayBuffer();
  10776. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  10777. this.column_ = 0;
  10778. this.row_ = BOTTOM_ROW;
  10779. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  10780. this.formatting_ = [];
  10781. };
  10782. /**
  10783. * Sets up control code and related constants for this instance
  10784. */
  10785. Cea608Stream.prototype.setConstants = function () {
  10786. // The following attributes have these uses:
  10787. // ext_ : char0 for mid-row codes, and the base for extended
  10788. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  10789. // extended codes)
  10790. // control_: char0 for control codes, except byte-shifted to the
  10791. // left so that we can do this.control_ | CONTROL_CODE
  10792. // offset_: char0 for tab offset codes
  10793. //
  10794. // It's also worth noting that control codes, and _only_ control codes,
  10795. // differ between field 1 and field2. Field 2 control codes are always
  10796. // their field 1 value plus 1. That's why there's the "| field" on the
  10797. // control value.
  10798. if (this.dataChannel_ === 0) {
  10799. this.BASE_ = 0x10;
  10800. this.EXT_ = 0x11;
  10801. this.CONTROL_ = (0x14 | this.field_) << 8;
  10802. this.OFFSET_ = 0x17;
  10803. } else if (this.dataChannel_ === 1) {
  10804. this.BASE_ = 0x18;
  10805. this.EXT_ = 0x19;
  10806. this.CONTROL_ = (0x1c | this.field_) << 8;
  10807. this.OFFSET_ = 0x1f;
  10808. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  10809. // list is not exhaustive. For a more comprehensive listing and semantics see
  10810. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  10811. // Padding
  10812. this.PADDING_ = 0x0000; // Pop-on Mode
  10813. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  10814. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  10815. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  10816. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  10817. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  10818. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  10819. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  10820. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  10821. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  10822. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  10823. };
  10824. /**
  10825. * Detects if the 2-byte packet data is a special character
  10826. *
  10827. * Special characters have a second byte in the range 0x30 to 0x3f,
  10828. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  10829. * data channel 2).
  10830. *
  10831. * @param {Integer} char0 The first byte
  10832. * @param {Integer} char1 The second byte
  10833. * @return {Boolean} Whether the 2 bytes are an special character
  10834. */
  10835. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  10836. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  10837. };
  10838. /**
  10839. * Detects if the 2-byte packet data is an extended character
  10840. *
  10841. * Extended characters have a second byte in the range 0x20 to 0x3f,
  10842. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  10843. * 0x1a or 0x1b (for data channel 2).
  10844. *
  10845. * @param {Integer} char0 The first byte
  10846. * @param {Integer} char1 The second byte
  10847. * @return {Boolean} Whether the 2 bytes are an extended character
  10848. */
  10849. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  10850. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  10851. };
  10852. /**
  10853. * Detects if the 2-byte packet is a mid-row code
  10854. *
  10855. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  10856. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  10857. * channel 2).
  10858. *
  10859. * @param {Integer} char0 The first byte
  10860. * @param {Integer} char1 The second byte
  10861. * @return {Boolean} Whether the 2 bytes are a mid-row code
  10862. */
  10863. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  10864. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  10865. };
  10866. /**
  10867. * Detects if the 2-byte packet is an offset control code
  10868. *
  10869. * Offset control codes have a second byte in the range 0x21 to 0x23,
  10870. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  10871. * data channel 2).
  10872. *
  10873. * @param {Integer} char0 The first byte
  10874. * @param {Integer} char1 The second byte
  10875. * @return {Boolean} Whether the 2 bytes are an offset control code
  10876. */
  10877. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  10878. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  10879. };
  10880. /**
  10881. * Detects if the 2-byte packet is a Preamble Address Code
  10882. *
  10883. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  10884. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  10885. * range 0x40 to 0x7f.
  10886. *
  10887. * @param {Integer} char0 The first byte
  10888. * @param {Integer} char1 The second byte
  10889. * @return {Boolean} Whether the 2 bytes are a PAC
  10890. */
  10891. Cea608Stream.prototype.isPAC = function (char0, char1) {
  10892. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  10893. };
  10894. /**
  10895. * Detects if a packet's second byte is in the range of a PAC color code
  10896. *
  10897. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  10898. * 0x60 to 0x6f.
  10899. *
  10900. * @param {Integer} char1 The second byte
  10901. * @return {Boolean} Whether the byte is a color PAC
  10902. */
  10903. Cea608Stream.prototype.isColorPAC = function (char1) {
  10904. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  10905. };
  10906. /**
  10907. * Detects if a single byte is in the range of a normal character
  10908. *
  10909. * Normal text bytes are in the range 0x20 to 0x7f.
  10910. *
  10911. * @param {Integer} char The byte
  10912. * @return {Boolean} Whether the byte is a normal character
  10913. */
  10914. Cea608Stream.prototype.isNormalChar = function (char) {
  10915. return char >= 0x20 && char <= 0x7f;
  10916. };
  10917. /**
  10918. * Configures roll-up
  10919. *
  10920. * @param {Integer} pts Current PTS
  10921. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  10922. * a new position
  10923. */
  10924. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  10925. // Reset the base row to the bottom row when switching modes
  10926. if (this.mode_ !== 'rollUp') {
  10927. this.row_ = BOTTOM_ROW;
  10928. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  10929. this.flushDisplayed(pts);
  10930. this.nonDisplayed_ = createDisplayBuffer();
  10931. this.displayed_ = createDisplayBuffer();
  10932. }
  10933. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  10934. // move currently displayed captions (up or down) to the new base row
  10935. for (var i = 0; i < this.rollUpRows_; i++) {
  10936. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  10937. this.displayed_[this.row_ - i] = '';
  10938. }
  10939. }
  10940. if (newBaseRow === undefined) {
  10941. newBaseRow = this.row_;
  10942. }
  10943. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  10944. }; // Adds the opening HTML tag for the passed character to the caption text,
  10945. // and keeps track of it for later closing
  10946. Cea608Stream.prototype.addFormatting = function (pts, format) {
  10947. this.formatting_ = this.formatting_.concat(format);
  10948. var text = format.reduce(function (text, format) {
  10949. return text + '<' + format + '>';
  10950. }, '');
  10951. this[this.mode_](pts, text);
  10952. }; // Adds HTML closing tags for current formatting to caption text and
  10953. // clears remembered formatting
  10954. Cea608Stream.prototype.clearFormatting = function (pts) {
  10955. if (!this.formatting_.length) {
  10956. return;
  10957. }
  10958. var text = this.formatting_.reverse().reduce(function (text, format) {
  10959. return text + '</' + format + '>';
  10960. }, '');
  10961. this.formatting_ = [];
  10962. this[this.mode_](pts, text);
  10963. }; // Mode Implementations
  10964. Cea608Stream.prototype.popOn = function (pts, text) {
  10965. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  10966. baseRow += text;
  10967. this.nonDisplayed_[this.row_] = baseRow;
  10968. };
  10969. Cea608Stream.prototype.rollUp = function (pts, text) {
  10970. var baseRow = this.displayed_[this.row_];
  10971. baseRow += text;
  10972. this.displayed_[this.row_] = baseRow;
  10973. };
  10974. Cea608Stream.prototype.shiftRowsUp_ = function () {
  10975. var i; // clear out inactive rows
  10976. for (i = 0; i < this.topRow_; i++) {
  10977. this.displayed_[i] = '';
  10978. }
  10979. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  10980. this.displayed_[i] = '';
  10981. } // shift displayed rows up
  10982. for (i = this.topRow_; i < this.row_; i++) {
  10983. this.displayed_[i] = this.displayed_[i + 1];
  10984. } // clear out the bottom row
  10985. this.displayed_[this.row_] = '';
  10986. };
  10987. Cea608Stream.prototype.paintOn = function (pts, text) {
  10988. var baseRow = this.displayed_[this.row_];
  10989. baseRow += text;
  10990. this.displayed_[this.row_] = baseRow;
  10991. }; // exports
  10992. var captionStream = {
  10993. CaptionStream: CaptionStream$2,
  10994. Cea608Stream: Cea608Stream,
  10995. Cea708Stream: Cea708Stream
  10996. };
  10997. /**
  10998. * mux.js
  10999. *
  11000. * Copyright (c) Brightcove
  11001. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11002. */
  11003. var streamTypes = {
  11004. H264_STREAM_TYPE: 0x1B,
  11005. ADTS_STREAM_TYPE: 0x0F,
  11006. METADATA_STREAM_TYPE: 0x15
  11007. };
  11008. /**
  11009. * mux.js
  11010. *
  11011. * Copyright (c) Brightcove
  11012. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11013. *
  11014. * Accepts program elementary stream (PES) data events and corrects
  11015. * decode and presentation time stamps to account for a rollover
  11016. * of the 33 bit value.
  11017. */
  11018. var Stream$6 = stream;
  11019. var MAX_TS = 8589934592;
  11020. var RO_THRESH = 4294967296;
  11021. var TYPE_SHARED = 'shared';
  11022. var handleRollover$1 = function (value, reference) {
  11023. var direction = 1;
  11024. if (value > reference) {
  11025. // If the current timestamp value is greater than our reference timestamp and we detect a
  11026. // timestamp rollover, this means the roll over is happening in the opposite direction.
  11027. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  11028. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  11029. // rollover point. In loading this segment, the timestamp values will be very large,
  11030. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  11031. // the time stamp to be `value - 2^33`.
  11032. direction = -1;
  11033. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  11034. // cause an incorrect adjustment.
  11035. while (Math.abs(reference - value) > RO_THRESH) {
  11036. value += direction * MAX_TS;
  11037. }
  11038. return value;
  11039. };
  11040. var TimestampRolloverStream$1 = function (type) {
  11041. var lastDTS, referenceDTS;
  11042. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  11043. // video and audio. We could use `undefined` here, but having a string
  11044. // makes debugging a little clearer.
  11045. this.type_ = type || TYPE_SHARED;
  11046. this.push = function (data) {
  11047. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  11048. // streams will only accept data that matches their type.
  11049. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  11050. return;
  11051. }
  11052. if (referenceDTS === undefined) {
  11053. referenceDTS = data.dts;
  11054. }
  11055. data.dts = handleRollover$1(data.dts, referenceDTS);
  11056. data.pts = handleRollover$1(data.pts, referenceDTS);
  11057. lastDTS = data.dts;
  11058. this.trigger('data', data);
  11059. };
  11060. this.flush = function () {
  11061. referenceDTS = lastDTS;
  11062. this.trigger('done');
  11063. };
  11064. this.endTimeline = function () {
  11065. this.flush();
  11066. this.trigger('endedtimeline');
  11067. };
  11068. this.discontinuity = function () {
  11069. referenceDTS = void 0;
  11070. lastDTS = void 0;
  11071. };
  11072. this.reset = function () {
  11073. this.discontinuity();
  11074. this.trigger('reset');
  11075. };
  11076. };
  11077. TimestampRolloverStream$1.prototype = new Stream$6();
  11078. var timestampRolloverStream = {
  11079. TimestampRolloverStream: TimestampRolloverStream$1,
  11080. handleRollover: handleRollover$1
  11081. }; // Once IE11 support is dropped, this function should be removed.
  11082. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  11083. if (!typedArray) {
  11084. return -1;
  11085. }
  11086. var currentIndex = fromIndex;
  11087. for (; currentIndex < typedArray.length; currentIndex++) {
  11088. if (typedArray[currentIndex] === element) {
  11089. return currentIndex;
  11090. }
  11091. }
  11092. return -1;
  11093. };
  11094. var typedArray = {
  11095. typedArrayIndexOf: typedArrayIndexOf$1
  11096. };
  11097. /**
  11098. * mux.js
  11099. *
  11100. * Copyright (c) Brightcove
  11101. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11102. *
  11103. * Tools for parsing ID3 frame data
  11104. * @see http://id3.org/id3v2.3.0
  11105. */
  11106. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  11107. // Frames that allow different types of text encoding contain a text
  11108. // encoding description byte [ID3v2.4.0 section 4.]
  11109. textEncodingDescriptionByte = {
  11110. Iso88591: 0x00,
  11111. // ISO-8859-1, terminated with \0.
  11112. Utf16: 0x01,
  11113. // UTF-16 encoded Unicode BOM, terminated with \0\0
  11114. Utf16be: 0x02,
  11115. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  11116. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  11117. },
  11118. // return a percent-encoded representation of the specified byte range
  11119. // @see http://en.wikipedia.org/wiki/Percent-encoding
  11120. percentEncode$1 = function (bytes, start, end) {
  11121. var i,
  11122. result = '';
  11123. for (i = start; i < end; i++) {
  11124. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  11125. }
  11126. return result;
  11127. },
  11128. // return the string representation of the specified byte range,
  11129. // interpreted as UTf-8.
  11130. parseUtf8 = function (bytes, start, end) {
  11131. return decodeURIComponent(percentEncode$1(bytes, start, end));
  11132. },
  11133. // return the string representation of the specified byte range,
  11134. // interpreted as ISO-8859-1.
  11135. parseIso88591$1 = function (bytes, start, end) {
  11136. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  11137. },
  11138. parseSyncSafeInteger$1 = function (data) {
  11139. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  11140. },
  11141. frameParsers = {
  11142. 'APIC': function (frame) {
  11143. var i = 1,
  11144. mimeTypeEndIndex,
  11145. descriptionEndIndex,
  11146. LINK_MIME_TYPE = '-->';
  11147. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11148. // ignore frames with unrecognized character encodings
  11149. return;
  11150. } // parsing fields [ID3v2.4.0 section 4.14.]
  11151. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11152. if (mimeTypeEndIndex < 0) {
  11153. // malformed frame
  11154. return;
  11155. } // parsing Mime type field (terminated with \0)
  11156. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  11157. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  11158. frame.pictureType = frame.data[i];
  11159. i++;
  11160. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11161. if (descriptionEndIndex < 0) {
  11162. // malformed frame
  11163. return;
  11164. } // parsing Description field (terminated with \0)
  11165. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  11166. i = descriptionEndIndex + 1;
  11167. if (frame.mimeType === LINK_MIME_TYPE) {
  11168. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  11169. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  11170. } else {
  11171. // parsing Picture Data field as binary data
  11172. frame.pictureData = frame.data.subarray(i, frame.data.length);
  11173. }
  11174. },
  11175. 'T*': function (frame) {
  11176. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11177. // ignore frames with unrecognized character encodings
  11178. return;
  11179. } // parse text field, do not include null terminator in the frame value
  11180. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  11181. frame.value = parseUtf8(frame.data, 1, frame.data.length).replace(/\0*$/, ''); // text information frames supports multiple strings, stored as a terminator separated list [ID3v2.4.0 section 4.2.]
  11182. frame.values = frame.value.split('\0');
  11183. },
  11184. 'TXXX': function (frame) {
  11185. var descriptionEndIndex;
  11186. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11187. // ignore frames with unrecognized character encodings
  11188. return;
  11189. }
  11190. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  11191. if (descriptionEndIndex === -1) {
  11192. return;
  11193. } // parse the text fields
  11194. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  11195. // frames that allow different types of encoding contain terminated text
  11196. // [ID3v2.4.0 section 4.]
  11197. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  11198. frame.data = frame.value;
  11199. },
  11200. 'W*': function (frame) {
  11201. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  11202. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  11203. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  11204. },
  11205. 'WXXX': function (frame) {
  11206. var descriptionEndIndex;
  11207. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11208. // ignore frames with unrecognized character encodings
  11209. return;
  11210. }
  11211. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  11212. if (descriptionEndIndex === -1) {
  11213. return;
  11214. } // parse the description and URL fields
  11215. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  11216. // if the value is followed by a string termination all the following information
  11217. // should be ignored [ID3v2.4.0 section 4.3]
  11218. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  11219. },
  11220. 'PRIV': function (frame) {
  11221. var i;
  11222. for (i = 0; i < frame.data.length; i++) {
  11223. if (frame.data[i] === 0) {
  11224. // parse the description and URL fields
  11225. frame.owner = parseIso88591$1(frame.data, 0, i);
  11226. break;
  11227. }
  11228. }
  11229. frame.privateData = frame.data.subarray(i + 1);
  11230. frame.data = frame.privateData;
  11231. }
  11232. };
  11233. var parseId3Frames$1 = function (data) {
  11234. var frameSize,
  11235. frameHeader,
  11236. frameStart = 10,
  11237. tagSize = 0,
  11238. frames = []; // If we don't have enough data for a header, 10 bytes,
  11239. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  11240. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  11241. return;
  11242. } // the frame size is transmitted as a 28-bit integer in the
  11243. // last four bytes of the ID3 header.
  11244. // The most significant bit of each byte is dropped and the
  11245. // results concatenated to recover the actual value.
  11246. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  11247. // convenient for our comparisons to include it
  11248. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  11249. var hasExtendedHeader = data[5] & 0x40;
  11250. if (hasExtendedHeader) {
  11251. // advance the frame start past the extended header
  11252. frameStart += 4; // header size field
  11253. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  11254. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  11255. } // parse one or more ID3 frames
  11256. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  11257. do {
  11258. // determine the number of bytes in this frame
  11259. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  11260. if (frameSize < 1) {
  11261. break;
  11262. }
  11263. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  11264. var frame = {
  11265. id: frameHeader,
  11266. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  11267. };
  11268. frame.key = frame.id; // parse frame values
  11269. if (frameParsers[frame.id]) {
  11270. // use frame specific parser
  11271. frameParsers[frame.id](frame);
  11272. } else if (frame.id[0] === 'T') {
  11273. // use text frame generic parser
  11274. frameParsers['T*'](frame);
  11275. } else if (frame.id[0] === 'W') {
  11276. // use URL link frame generic parser
  11277. frameParsers['W*'](frame);
  11278. }
  11279. frames.push(frame);
  11280. frameStart += 10; // advance past the frame header
  11281. frameStart += frameSize; // advance past the frame body
  11282. } while (frameStart < tagSize);
  11283. return frames;
  11284. };
  11285. var parseId3 = {
  11286. parseId3Frames: parseId3Frames$1,
  11287. parseSyncSafeInteger: parseSyncSafeInteger$1,
  11288. frameParsers: frameParsers
  11289. };
  11290. /**
  11291. * mux.js
  11292. *
  11293. * Copyright (c) Brightcove
  11294. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11295. *
  11296. * Accepts program elementary stream (PES) data events and parses out
  11297. * ID3 metadata from them, if present.
  11298. * @see http://id3.org/id3v2.3.0
  11299. */
  11300. var Stream$5 = stream,
  11301. StreamTypes$3 = streamTypes,
  11302. id3 = parseId3,
  11303. MetadataStream;
  11304. MetadataStream = function (options) {
  11305. var settings = {
  11306. // the bytes of the program-level descriptor field in MP2T
  11307. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  11308. // program element descriptors"
  11309. descriptor: options && options.descriptor
  11310. },
  11311. // the total size in bytes of the ID3 tag being parsed
  11312. tagSize = 0,
  11313. // tag data that is not complete enough to be parsed
  11314. buffer = [],
  11315. // the total number of bytes currently in the buffer
  11316. bufferSize = 0,
  11317. i;
  11318. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  11319. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  11320. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  11321. if (settings.descriptor) {
  11322. for (i = 0; i < settings.descriptor.length; i++) {
  11323. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  11324. }
  11325. }
  11326. this.push = function (chunk) {
  11327. var tag, frameStart, frameSize, frame, i, frameHeader;
  11328. if (chunk.type !== 'timed-metadata') {
  11329. return;
  11330. } // if data_alignment_indicator is set in the PES header,
  11331. // we must have the start of a new ID3 tag. Assume anything
  11332. // remaining in the buffer was malformed and throw it out
  11333. if (chunk.dataAlignmentIndicator) {
  11334. bufferSize = 0;
  11335. buffer.length = 0;
  11336. } // ignore events that don't look like ID3 data
  11337. if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
  11338. this.trigger('log', {
  11339. level: 'warn',
  11340. message: 'Skipping unrecognized metadata packet'
  11341. });
  11342. return;
  11343. } // add this chunk to the data we've collected so far
  11344. buffer.push(chunk);
  11345. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  11346. if (buffer.length === 1) {
  11347. // the frame size is transmitted as a 28-bit integer in the
  11348. // last four bytes of the ID3 header.
  11349. // The most significant bit of each byte is dropped and the
  11350. // results concatenated to recover the actual value.
  11351. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  11352. // convenient for our comparisons to include it
  11353. tagSize += 10;
  11354. } // if the entire frame has not arrived, wait for more data
  11355. if (bufferSize < tagSize) {
  11356. return;
  11357. } // collect the entire frame so it can be parsed
  11358. tag = {
  11359. data: new Uint8Array(tagSize),
  11360. frames: [],
  11361. pts: buffer[0].pts,
  11362. dts: buffer[0].dts
  11363. };
  11364. for (i = 0; i < tagSize;) {
  11365. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  11366. i += buffer[0].data.byteLength;
  11367. bufferSize -= buffer[0].data.byteLength;
  11368. buffer.shift();
  11369. } // find the start of the first frame and the end of the tag
  11370. frameStart = 10;
  11371. if (tag.data[5] & 0x40) {
  11372. // advance the frame start past the extended header
  11373. frameStart += 4; // header size field
  11374. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  11375. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  11376. } // parse one or more ID3 frames
  11377. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  11378. do {
  11379. // determine the number of bytes in this frame
  11380. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  11381. if (frameSize < 1) {
  11382. this.trigger('log', {
  11383. level: 'warn',
  11384. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  11385. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  11386. // to be sent along.
  11387. break;
  11388. }
  11389. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  11390. frame = {
  11391. id: frameHeader,
  11392. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  11393. };
  11394. frame.key = frame.id; // parse frame values
  11395. if (id3.frameParsers[frame.id]) {
  11396. // use frame specific parser
  11397. id3.frameParsers[frame.id](frame);
  11398. } else if (frame.id[0] === 'T') {
  11399. // use text frame generic parser
  11400. id3.frameParsers['T*'](frame);
  11401. } else if (frame.id[0] === 'W') {
  11402. // use URL link frame generic parser
  11403. id3.frameParsers['W*'](frame);
  11404. } // handle the special PRIV frame used to indicate the start
  11405. // time for raw AAC data
  11406. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  11407. var d = frame.data,
  11408. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  11409. size *= 4;
  11410. size += d[7] & 0x03;
  11411. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  11412. // on the value of this frame
  11413. // we couldn't have known the appropriate pts and dts before
  11414. // parsing this ID3 tag so set those values now
  11415. if (tag.pts === undefined && tag.dts === undefined) {
  11416. tag.pts = frame.timeStamp;
  11417. tag.dts = frame.timeStamp;
  11418. }
  11419. this.trigger('timestamp', frame);
  11420. }
  11421. tag.frames.push(frame);
  11422. frameStart += 10; // advance past the frame header
  11423. frameStart += frameSize; // advance past the frame body
  11424. } while (frameStart < tagSize);
  11425. this.trigger('data', tag);
  11426. };
  11427. };
  11428. MetadataStream.prototype = new Stream$5();
  11429. var metadataStream = MetadataStream;
  11430. /**
  11431. * mux.js
  11432. *
  11433. * Copyright (c) Brightcove
  11434. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11435. *
  11436. * A stream-based mp2t to mp4 converter. This utility can be used to
  11437. * deliver mp4s to a SourceBuffer on platforms that support native
  11438. * Media Source Extensions.
  11439. */
  11440. var Stream$4 = stream,
  11441. CaptionStream$1 = captionStream,
  11442. StreamTypes$2 = streamTypes,
  11443. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  11444. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  11445. var MP2T_PACKET_LENGTH$1 = 188,
  11446. // bytes
  11447. SYNC_BYTE$1 = 0x47;
  11448. /**
  11449. * Splits an incoming stream of binary data into MPEG-2 Transport
  11450. * Stream packets.
  11451. */
  11452. TransportPacketStream = function () {
  11453. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  11454. bytesInBuffer = 0;
  11455. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  11456. /**
  11457. * Split a stream of data into M2TS packets
  11458. **/
  11459. this.push = function (bytes) {
  11460. var startIndex = 0,
  11461. endIndex = MP2T_PACKET_LENGTH$1,
  11462. everything; // If there are bytes remaining from the last segment, prepend them to the
  11463. // bytes that were pushed in
  11464. if (bytesInBuffer) {
  11465. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  11466. everything.set(buffer.subarray(0, bytesInBuffer));
  11467. everything.set(bytes, bytesInBuffer);
  11468. bytesInBuffer = 0;
  11469. } else {
  11470. everything = bytes;
  11471. } // While we have enough data for a packet
  11472. while (endIndex < everything.byteLength) {
  11473. // Look for a pair of start and end sync bytes in the data..
  11474. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  11475. // We found a packet so emit it and jump one whole packet forward in
  11476. // the stream
  11477. this.trigger('data', everything.subarray(startIndex, endIndex));
  11478. startIndex += MP2T_PACKET_LENGTH$1;
  11479. endIndex += MP2T_PACKET_LENGTH$1;
  11480. continue;
  11481. } // If we get here, we have somehow become de-synchronized and we need to step
  11482. // forward one byte at a time until we find a pair of sync bytes that denote
  11483. // a packet
  11484. startIndex++;
  11485. endIndex++;
  11486. } // If there was some data left over at the end of the segment that couldn't
  11487. // possibly be a whole packet, keep it because it might be the start of a packet
  11488. // that continues in the next segment
  11489. if (startIndex < everything.byteLength) {
  11490. buffer.set(everything.subarray(startIndex), 0);
  11491. bytesInBuffer = everything.byteLength - startIndex;
  11492. }
  11493. };
  11494. /**
  11495. * Passes identified M2TS packets to the TransportParseStream to be parsed
  11496. **/
  11497. this.flush = function () {
  11498. // If the buffer contains a whole packet when we are being flushed, emit it
  11499. // and empty the buffer. Otherwise hold onto the data because it may be
  11500. // important for decoding the next segment
  11501. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  11502. this.trigger('data', buffer);
  11503. bytesInBuffer = 0;
  11504. }
  11505. this.trigger('done');
  11506. };
  11507. this.endTimeline = function () {
  11508. this.flush();
  11509. this.trigger('endedtimeline');
  11510. };
  11511. this.reset = function () {
  11512. bytesInBuffer = 0;
  11513. this.trigger('reset');
  11514. };
  11515. };
  11516. TransportPacketStream.prototype = new Stream$4();
  11517. /**
  11518. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  11519. * forms of the individual transport stream packets.
  11520. */
  11521. TransportParseStream = function () {
  11522. var parsePsi, parsePat, parsePmt, self;
  11523. TransportParseStream.prototype.init.call(this);
  11524. self = this;
  11525. this.packetsWaitingForPmt = [];
  11526. this.programMapTable = undefined;
  11527. parsePsi = function (payload, psi) {
  11528. var offset = 0; // PSI packets may be split into multiple sections and those
  11529. // sections may be split into multiple packets. If a PSI
  11530. // section starts in this packet, the payload_unit_start_indicator
  11531. // will be true and the first byte of the payload will indicate
  11532. // the offset from the current position to the start of the
  11533. // section.
  11534. if (psi.payloadUnitStartIndicator) {
  11535. offset += payload[offset] + 1;
  11536. }
  11537. if (psi.type === 'pat') {
  11538. parsePat(payload.subarray(offset), psi);
  11539. } else {
  11540. parsePmt(payload.subarray(offset), psi);
  11541. }
  11542. };
  11543. parsePat = function (payload, pat) {
  11544. pat.section_number = payload[7]; // eslint-disable-line camelcase
  11545. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  11546. // skip the PSI header and parse the first PMT entry
  11547. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  11548. pat.pmtPid = self.pmtPid;
  11549. };
  11550. /**
  11551. * Parse out the relevant fields of a Program Map Table (PMT).
  11552. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  11553. * packet. The first byte in this array should be the table_id
  11554. * field.
  11555. * @param pmt {object} the object that should be decorated with
  11556. * fields parsed from the PMT.
  11557. */
  11558. parsePmt = function (payload, pmt) {
  11559. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  11560. // take effect. We don't believe this should ever be the case
  11561. // for HLS but we'll ignore "forward" PMT declarations if we see
  11562. // them. Future PMT declarations have the current_next_indicator
  11563. // set to zero.
  11564. if (!(payload[5] & 0x01)) {
  11565. return;
  11566. } // overwrite any existing program map table
  11567. self.programMapTable = {
  11568. video: null,
  11569. audio: null,
  11570. 'timed-metadata': {}
  11571. }; // the mapping table ends at the end of the current section
  11572. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  11573. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  11574. // long the program info descriptors are
  11575. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  11576. offset = 12 + programInfoLength;
  11577. while (offset < tableEnd) {
  11578. var streamType = payload[offset];
  11579. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  11580. // TODO: should this be done for metadata too? for now maintain behavior of
  11581. // multiple metadata streams
  11582. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  11583. self.programMapTable.video = pid;
  11584. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  11585. self.programMapTable.audio = pid;
  11586. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  11587. // map pid to stream type for metadata streams
  11588. self.programMapTable['timed-metadata'][pid] = streamType;
  11589. } // move to the next table entry
  11590. // skip past the elementary stream descriptors, if present
  11591. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  11592. } // record the map on the packet as well
  11593. pmt.programMapTable = self.programMapTable;
  11594. };
  11595. /**
  11596. * Deliver a new MP2T packet to the next stream in the pipeline.
  11597. */
  11598. this.push = function (packet) {
  11599. var result = {},
  11600. offset = 4;
  11601. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  11602. result.pid = packet[1] & 0x1f;
  11603. result.pid <<= 8;
  11604. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  11605. // fifth byte of the TS packet header. The adaptation field is
  11606. // used to add stuffing to PES packets that don't fill a complete
  11607. // TS packet, and to specify some forms of timing and control data
  11608. // that we do not currently use.
  11609. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  11610. offset += packet[offset] + 1;
  11611. } // parse the rest of the packet based on the type
  11612. if (result.pid === 0) {
  11613. result.type = 'pat';
  11614. parsePsi(packet.subarray(offset), result);
  11615. this.trigger('data', result);
  11616. } else if (result.pid === this.pmtPid) {
  11617. result.type = 'pmt';
  11618. parsePsi(packet.subarray(offset), result);
  11619. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  11620. while (this.packetsWaitingForPmt.length) {
  11621. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  11622. }
  11623. } else if (this.programMapTable === undefined) {
  11624. // When we have not seen a PMT yet, defer further processing of
  11625. // PES packets until one has been parsed
  11626. this.packetsWaitingForPmt.push([packet, offset, result]);
  11627. } else {
  11628. this.processPes_(packet, offset, result);
  11629. }
  11630. };
  11631. this.processPes_ = function (packet, offset, result) {
  11632. // set the appropriate stream type
  11633. if (result.pid === this.programMapTable.video) {
  11634. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  11635. } else if (result.pid === this.programMapTable.audio) {
  11636. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  11637. } else {
  11638. // if not video or audio, it is timed-metadata or unknown
  11639. // if unknown, streamType will be undefined
  11640. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  11641. }
  11642. result.type = 'pes';
  11643. result.data = packet.subarray(offset);
  11644. this.trigger('data', result);
  11645. };
  11646. };
  11647. TransportParseStream.prototype = new Stream$4();
  11648. TransportParseStream.STREAM_TYPES = {
  11649. h264: 0x1b,
  11650. adts: 0x0f
  11651. };
  11652. /**
  11653. * Reconsistutes program elementary stream (PES) packets from parsed
  11654. * transport stream packets. That is, if you pipe an
  11655. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  11656. * events will be events which capture the bytes for individual PES
  11657. * packets plus relevant metadata that has been extracted from the
  11658. * container.
  11659. */
  11660. ElementaryStream = function () {
  11661. var self = this,
  11662. segmentHadPmt = false,
  11663. // PES packet fragments
  11664. video = {
  11665. data: [],
  11666. size: 0
  11667. },
  11668. audio = {
  11669. data: [],
  11670. size: 0
  11671. },
  11672. timedMetadata = {
  11673. data: [],
  11674. size: 0
  11675. },
  11676. programMapTable,
  11677. parsePes = function (payload, pes) {
  11678. var ptsDtsFlags;
  11679. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  11680. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  11681. // that are frame data that is continuing from the previous fragment. This
  11682. // is to check that the pes data is the start of a new pes payload
  11683. if (startPrefix !== 1) {
  11684. return;
  11685. } // get the packet length, this will be 0 for video
  11686. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  11687. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  11688. // and a DTS value. Determine what combination of values is
  11689. // available to work with.
  11690. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  11691. // performs all bitwise operations on 32-bit integers but javascript
  11692. // supports a much greater range (52-bits) of integer using standard
  11693. // mathematical operations.
  11694. // We construct a 31-bit value using bitwise operators over the 31
  11695. // most significant bits and then multiply by 4 (equal to a left-shift
  11696. // of 2) before we add the final 2 least significant bits of the
  11697. // timestamp (equal to an OR.)
  11698. if (ptsDtsFlags & 0xC0) {
  11699. // the PTS and DTS are not written out directly. For information
  11700. // on how they are encoded, see
  11701. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  11702. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  11703. pes.pts *= 4; // Left shift by 2
  11704. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  11705. pes.dts = pes.pts;
  11706. if (ptsDtsFlags & 0x40) {
  11707. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  11708. pes.dts *= 4; // Left shift by 2
  11709. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  11710. }
  11711. } // the data section starts immediately after the PES header.
  11712. // pes_header_data_length specifies the number of header bytes
  11713. // that follow the last byte of the field.
  11714. pes.data = payload.subarray(9 + payload[8]);
  11715. },
  11716. /**
  11717. * Pass completely parsed PES packets to the next stream in the pipeline
  11718. **/
  11719. flushStream = function (stream, type, forceFlush) {
  11720. var packetData = new Uint8Array(stream.size),
  11721. event = {
  11722. type: type
  11723. },
  11724. i = 0,
  11725. offset = 0,
  11726. packetFlushable = false,
  11727. fragment; // do nothing if there is not enough buffered data for a complete
  11728. // PES header
  11729. if (!stream.data.length || stream.size < 9) {
  11730. return;
  11731. }
  11732. event.trackId = stream.data[0].pid; // reassemble the packet
  11733. for (i = 0; i < stream.data.length; i++) {
  11734. fragment = stream.data[i];
  11735. packetData.set(fragment.data, offset);
  11736. offset += fragment.data.byteLength;
  11737. } // parse assembled packet's PES header
  11738. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  11739. // check that there is enough stream data to fill the packet
  11740. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  11741. if (forceFlush || packetFlushable) {
  11742. stream.size = 0;
  11743. stream.data.length = 0;
  11744. } // only emit packets that are complete. this is to avoid assembling
  11745. // incomplete PES packets due to poor segmentation
  11746. if (packetFlushable) {
  11747. self.trigger('data', event);
  11748. }
  11749. };
  11750. ElementaryStream.prototype.init.call(this);
  11751. /**
  11752. * Identifies M2TS packet types and parses PES packets using metadata
  11753. * parsed from the PMT
  11754. **/
  11755. this.push = function (data) {
  11756. ({
  11757. pat: function () {// we have to wait for the PMT to arrive as well before we
  11758. // have any meaningful metadata
  11759. },
  11760. pes: function () {
  11761. var stream, streamType;
  11762. switch (data.streamType) {
  11763. case StreamTypes$2.H264_STREAM_TYPE:
  11764. stream = video;
  11765. streamType = 'video';
  11766. break;
  11767. case StreamTypes$2.ADTS_STREAM_TYPE:
  11768. stream = audio;
  11769. streamType = 'audio';
  11770. break;
  11771. case StreamTypes$2.METADATA_STREAM_TYPE:
  11772. stream = timedMetadata;
  11773. streamType = 'timed-metadata';
  11774. break;
  11775. default:
  11776. // ignore unknown stream types
  11777. return;
  11778. } // if a new packet is starting, we can flush the completed
  11779. // packet
  11780. if (data.payloadUnitStartIndicator) {
  11781. flushStream(stream, streamType, true);
  11782. } // buffer this fragment until we are sure we've received the
  11783. // complete payload
  11784. stream.data.push(data);
  11785. stream.size += data.data.byteLength;
  11786. },
  11787. pmt: function () {
  11788. var event = {
  11789. type: 'metadata',
  11790. tracks: []
  11791. };
  11792. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  11793. if (programMapTable.video !== null) {
  11794. event.tracks.push({
  11795. timelineStartInfo: {
  11796. baseMediaDecodeTime: 0
  11797. },
  11798. id: +programMapTable.video,
  11799. codec: 'avc',
  11800. type: 'video'
  11801. });
  11802. }
  11803. if (programMapTable.audio !== null) {
  11804. event.tracks.push({
  11805. timelineStartInfo: {
  11806. baseMediaDecodeTime: 0
  11807. },
  11808. id: +programMapTable.audio,
  11809. codec: 'adts',
  11810. type: 'audio'
  11811. });
  11812. }
  11813. segmentHadPmt = true;
  11814. self.trigger('data', event);
  11815. }
  11816. })[data.type]();
  11817. };
  11818. this.reset = function () {
  11819. video.size = 0;
  11820. video.data.length = 0;
  11821. audio.size = 0;
  11822. audio.data.length = 0;
  11823. this.trigger('reset');
  11824. };
  11825. /**
  11826. * Flush any remaining input. Video PES packets may be of variable
  11827. * length. Normally, the start of a new video packet can trigger the
  11828. * finalization of the previous packet. That is not possible if no
  11829. * more video is forthcoming, however. In that case, some other
  11830. * mechanism (like the end of the file) has to be employed. When it is
  11831. * clear that no additional data is forthcoming, calling this method
  11832. * will flush the buffered packets.
  11833. */
  11834. this.flushStreams_ = function () {
  11835. // !!THIS ORDER IS IMPORTANT!!
  11836. // video first then audio
  11837. flushStream(video, 'video');
  11838. flushStream(audio, 'audio');
  11839. flushStream(timedMetadata, 'timed-metadata');
  11840. };
  11841. this.flush = function () {
  11842. // if on flush we haven't had a pmt emitted
  11843. // and we have a pmt to emit. emit the pmt
  11844. // so that we trigger a trackinfo downstream.
  11845. if (!segmentHadPmt && programMapTable) {
  11846. var pmt = {
  11847. type: 'metadata',
  11848. tracks: []
  11849. }; // translate audio and video streams to tracks
  11850. if (programMapTable.video !== null) {
  11851. pmt.tracks.push({
  11852. timelineStartInfo: {
  11853. baseMediaDecodeTime: 0
  11854. },
  11855. id: +programMapTable.video,
  11856. codec: 'avc',
  11857. type: 'video'
  11858. });
  11859. }
  11860. if (programMapTable.audio !== null) {
  11861. pmt.tracks.push({
  11862. timelineStartInfo: {
  11863. baseMediaDecodeTime: 0
  11864. },
  11865. id: +programMapTable.audio,
  11866. codec: 'adts',
  11867. type: 'audio'
  11868. });
  11869. }
  11870. self.trigger('data', pmt);
  11871. }
  11872. segmentHadPmt = false;
  11873. this.flushStreams_();
  11874. this.trigger('done');
  11875. };
  11876. };
  11877. ElementaryStream.prototype = new Stream$4();
  11878. var m2ts$1 = {
  11879. PAT_PID: 0x0000,
  11880. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  11881. TransportPacketStream: TransportPacketStream,
  11882. TransportParseStream: TransportParseStream,
  11883. ElementaryStream: ElementaryStream,
  11884. TimestampRolloverStream: TimestampRolloverStream,
  11885. CaptionStream: CaptionStream$1.CaptionStream,
  11886. Cea608Stream: CaptionStream$1.Cea608Stream,
  11887. Cea708Stream: CaptionStream$1.Cea708Stream,
  11888. MetadataStream: metadataStream
  11889. };
  11890. for (var type in StreamTypes$2) {
  11891. if (StreamTypes$2.hasOwnProperty(type)) {
  11892. m2ts$1[type] = StreamTypes$2[type];
  11893. }
  11894. }
  11895. var m2ts_1 = m2ts$1;
  11896. /**
  11897. * mux.js
  11898. *
  11899. * Copyright (c) Brightcove
  11900. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11901. */
  11902. var Stream$3 = stream;
  11903. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  11904. var AdtsStream$1;
  11905. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  11906. /*
  11907. * Accepts a ElementaryStream and emits data events with parsed
  11908. * AAC Audio Frames of the individual packets. Input audio in ADTS
  11909. * format is unpacked and re-emitted as AAC frames.
  11910. *
  11911. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  11912. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  11913. */
  11914. AdtsStream$1 = function (handlePartialSegments) {
  11915. var buffer,
  11916. frameNum = 0;
  11917. AdtsStream$1.prototype.init.call(this);
  11918. this.skipWarn_ = function (start, end) {
  11919. this.trigger('log', {
  11920. level: 'warn',
  11921. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  11922. });
  11923. };
  11924. this.push = function (packet) {
  11925. var i = 0,
  11926. frameLength,
  11927. protectionSkipBytes,
  11928. oldBuffer,
  11929. sampleCount,
  11930. adtsFrameDuration;
  11931. if (!handlePartialSegments) {
  11932. frameNum = 0;
  11933. }
  11934. if (packet.type !== 'audio') {
  11935. // ignore non-audio data
  11936. return;
  11937. } // Prepend any data in the buffer to the input data so that we can parse
  11938. // aac frames the cross a PES packet boundary
  11939. if (buffer && buffer.length) {
  11940. oldBuffer = buffer;
  11941. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  11942. buffer.set(oldBuffer);
  11943. buffer.set(packet.data, oldBuffer.byteLength);
  11944. } else {
  11945. buffer = packet.data;
  11946. } // unpack any ADTS frames which have been fully received
  11947. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  11948. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  11949. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  11950. while (i + 7 < buffer.length) {
  11951. // Look for the start of an ADTS header..
  11952. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  11953. if (typeof skip !== 'number') {
  11954. skip = i;
  11955. } // If a valid header was not found, jump one forward and attempt to
  11956. // find a valid ADTS header starting at the next byte
  11957. i++;
  11958. continue;
  11959. }
  11960. if (typeof skip === 'number') {
  11961. this.skipWarn_(skip, i);
  11962. skip = null;
  11963. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  11964. // end of the ADTS header
  11965. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  11966. // end of the sync sequence
  11967. // NOTE: frame length includes the size of the header
  11968. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  11969. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  11970. adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2]; // If we don't have enough data to actually finish this ADTS frame,
  11971. // then we have to wait for more data
  11972. if (buffer.byteLength - i < frameLength) {
  11973. break;
  11974. } // Otherwise, deliver the complete AAC frame
  11975. this.trigger('data', {
  11976. pts: packet.pts + frameNum * adtsFrameDuration,
  11977. dts: packet.dts + frameNum * adtsFrameDuration,
  11978. sampleCount: sampleCount,
  11979. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  11980. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  11981. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  11982. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  11983. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  11984. samplesize: 16,
  11985. // data is the frame without it's header
  11986. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  11987. });
  11988. frameNum++;
  11989. i += frameLength;
  11990. }
  11991. if (typeof skip === 'number') {
  11992. this.skipWarn_(skip, i);
  11993. skip = null;
  11994. } // remove processed bytes from the buffer.
  11995. buffer = buffer.subarray(i);
  11996. };
  11997. this.flush = function () {
  11998. frameNum = 0;
  11999. this.trigger('done');
  12000. };
  12001. this.reset = function () {
  12002. buffer = void 0;
  12003. this.trigger('reset');
  12004. };
  12005. this.endTimeline = function () {
  12006. buffer = void 0;
  12007. this.trigger('endedtimeline');
  12008. };
  12009. };
  12010. AdtsStream$1.prototype = new Stream$3();
  12011. var adts = AdtsStream$1;
  12012. /**
  12013. * mux.js
  12014. *
  12015. * Copyright (c) Brightcove
  12016. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12017. */
  12018. var ExpGolomb$1;
  12019. /**
  12020. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  12021. * scheme used by h264.
  12022. */
  12023. ExpGolomb$1 = function (workingData) {
  12024. var // the number of bytes left to examine in workingData
  12025. workingBytesAvailable = workingData.byteLength,
  12026. // the current word being examined
  12027. workingWord = 0,
  12028. // :uint
  12029. // the number of bits left to examine in the current word
  12030. workingBitsAvailable = 0; // :uint;
  12031. // ():uint
  12032. this.length = function () {
  12033. return 8 * workingBytesAvailable;
  12034. }; // ():uint
  12035. this.bitsAvailable = function () {
  12036. return 8 * workingBytesAvailable + workingBitsAvailable;
  12037. }; // ():void
  12038. this.loadWord = function () {
  12039. var position = workingData.byteLength - workingBytesAvailable,
  12040. workingBytes = new Uint8Array(4),
  12041. availableBytes = Math.min(4, workingBytesAvailable);
  12042. if (availableBytes === 0) {
  12043. throw new Error('no bytes available');
  12044. }
  12045. workingBytes.set(workingData.subarray(position, position + availableBytes));
  12046. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  12047. workingBitsAvailable = availableBytes * 8;
  12048. workingBytesAvailable -= availableBytes;
  12049. }; // (count:int):void
  12050. this.skipBits = function (count) {
  12051. var skipBytes; // :int
  12052. if (workingBitsAvailable > count) {
  12053. workingWord <<= count;
  12054. workingBitsAvailable -= count;
  12055. } else {
  12056. count -= workingBitsAvailable;
  12057. skipBytes = Math.floor(count / 8);
  12058. count -= skipBytes * 8;
  12059. workingBytesAvailable -= skipBytes;
  12060. this.loadWord();
  12061. workingWord <<= count;
  12062. workingBitsAvailable -= count;
  12063. }
  12064. }; // (size:int):uint
  12065. this.readBits = function (size) {
  12066. var bits = Math.min(workingBitsAvailable, size),
  12067. // :uint
  12068. valu = workingWord >>> 32 - bits; // :uint
  12069. // if size > 31, handle error
  12070. workingBitsAvailable -= bits;
  12071. if (workingBitsAvailable > 0) {
  12072. workingWord <<= bits;
  12073. } else if (workingBytesAvailable > 0) {
  12074. this.loadWord();
  12075. }
  12076. bits = size - bits;
  12077. if (bits > 0) {
  12078. return valu << bits | this.readBits(bits);
  12079. }
  12080. return valu;
  12081. }; // ():uint
  12082. this.skipLeadingZeros = function () {
  12083. var leadingZeroCount; // :uint
  12084. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  12085. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  12086. // the first bit of working word is 1
  12087. workingWord <<= leadingZeroCount;
  12088. workingBitsAvailable -= leadingZeroCount;
  12089. return leadingZeroCount;
  12090. }
  12091. } // we exhausted workingWord and still have not found a 1
  12092. this.loadWord();
  12093. return leadingZeroCount + this.skipLeadingZeros();
  12094. }; // ():void
  12095. this.skipUnsignedExpGolomb = function () {
  12096. this.skipBits(1 + this.skipLeadingZeros());
  12097. }; // ():void
  12098. this.skipExpGolomb = function () {
  12099. this.skipBits(1 + this.skipLeadingZeros());
  12100. }; // ():uint
  12101. this.readUnsignedExpGolomb = function () {
  12102. var clz = this.skipLeadingZeros(); // :uint
  12103. return this.readBits(clz + 1) - 1;
  12104. }; // ():int
  12105. this.readExpGolomb = function () {
  12106. var valu = this.readUnsignedExpGolomb(); // :int
  12107. if (0x01 & valu) {
  12108. // the number is odd if the low order bit is set
  12109. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  12110. }
  12111. return -1 * (valu >>> 1); // divide by two then make it negative
  12112. }; // Some convenience functions
  12113. // :Boolean
  12114. this.readBoolean = function () {
  12115. return this.readBits(1) === 1;
  12116. }; // ():int
  12117. this.readUnsignedByte = function () {
  12118. return this.readBits(8);
  12119. };
  12120. this.loadWord();
  12121. };
  12122. var expGolomb = ExpGolomb$1;
  12123. /**
  12124. * mux.js
  12125. *
  12126. * Copyright (c) Brightcove
  12127. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12128. */
  12129. var Stream$2 = stream;
  12130. var ExpGolomb = expGolomb;
  12131. var H264Stream$1, NalByteStream;
  12132. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  12133. /**
  12134. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  12135. */
  12136. NalByteStream = function () {
  12137. var syncPoint = 0,
  12138. i,
  12139. buffer;
  12140. NalByteStream.prototype.init.call(this);
  12141. /*
  12142. * Scans a byte stream and triggers a data event with the NAL units found.
  12143. * @param {Object} data Event received from H264Stream
  12144. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  12145. *
  12146. * @see H264Stream.push
  12147. */
  12148. this.push = function (data) {
  12149. var swapBuffer;
  12150. if (!buffer) {
  12151. buffer = data.data;
  12152. } else {
  12153. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  12154. swapBuffer.set(buffer);
  12155. swapBuffer.set(data.data, buffer.byteLength);
  12156. buffer = swapBuffer;
  12157. }
  12158. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  12159. // scan for NAL unit boundaries
  12160. // a match looks like this:
  12161. // 0 0 1 .. NAL .. 0 0 1
  12162. // ^ sync point ^ i
  12163. // or this:
  12164. // 0 0 1 .. NAL .. 0 0 0
  12165. // ^ sync point ^ i
  12166. // advance the sync point to a NAL start, if necessary
  12167. for (; syncPoint < len - 3; syncPoint++) {
  12168. if (buffer[syncPoint + 2] === 1) {
  12169. // the sync point is properly aligned
  12170. i = syncPoint + 5;
  12171. break;
  12172. }
  12173. }
  12174. while (i < len) {
  12175. // look at the current byte to determine if we've hit the end of
  12176. // a NAL unit boundary
  12177. switch (buffer[i]) {
  12178. case 0:
  12179. // skip past non-sync sequences
  12180. if (buffer[i - 1] !== 0) {
  12181. i += 2;
  12182. break;
  12183. } else if (buffer[i - 2] !== 0) {
  12184. i++;
  12185. break;
  12186. } // deliver the NAL unit if it isn't empty
  12187. if (syncPoint + 3 !== i - 2) {
  12188. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  12189. } // drop trailing zeroes
  12190. do {
  12191. i++;
  12192. } while (buffer[i] !== 1 && i < len);
  12193. syncPoint = i - 2;
  12194. i += 3;
  12195. break;
  12196. case 1:
  12197. // skip past non-sync sequences
  12198. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  12199. i += 3;
  12200. break;
  12201. } // deliver the NAL unit
  12202. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  12203. syncPoint = i - 2;
  12204. i += 3;
  12205. break;
  12206. default:
  12207. // the current byte isn't a one or zero, so it cannot be part
  12208. // of a sync sequence
  12209. i += 3;
  12210. break;
  12211. }
  12212. } // filter out the NAL units that were delivered
  12213. buffer = buffer.subarray(syncPoint);
  12214. i -= syncPoint;
  12215. syncPoint = 0;
  12216. };
  12217. this.reset = function () {
  12218. buffer = null;
  12219. syncPoint = 0;
  12220. this.trigger('reset');
  12221. };
  12222. this.flush = function () {
  12223. // deliver the last buffered NAL unit
  12224. if (buffer && buffer.byteLength > 3) {
  12225. this.trigger('data', buffer.subarray(syncPoint + 3));
  12226. } // reset the stream state
  12227. buffer = null;
  12228. syncPoint = 0;
  12229. this.trigger('done');
  12230. };
  12231. this.endTimeline = function () {
  12232. this.flush();
  12233. this.trigger('endedtimeline');
  12234. };
  12235. };
  12236. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  12237. // see Recommendation ITU-T H.264 (4/2013),
  12238. // 7.3.2.1.1 Sequence parameter set data syntax
  12239. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  12240. 100: true,
  12241. 110: true,
  12242. 122: true,
  12243. 244: true,
  12244. 44: true,
  12245. 83: true,
  12246. 86: true,
  12247. 118: true,
  12248. 128: true,
  12249. // TODO: the three profiles below don't
  12250. // appear to have sps data in the specificiation anymore?
  12251. 138: true,
  12252. 139: true,
  12253. 134: true
  12254. };
  12255. /**
  12256. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  12257. * events.
  12258. */
  12259. H264Stream$1 = function () {
  12260. var nalByteStream = new NalByteStream(),
  12261. self,
  12262. trackId,
  12263. currentPts,
  12264. currentDts,
  12265. discardEmulationPreventionBytes,
  12266. readSequenceParameterSet,
  12267. skipScalingList;
  12268. H264Stream$1.prototype.init.call(this);
  12269. self = this;
  12270. /*
  12271. * Pushes a packet from a stream onto the NalByteStream
  12272. *
  12273. * @param {Object} packet - A packet received from a stream
  12274. * @param {Uint8Array} packet.data - The raw bytes of the packet
  12275. * @param {Number} packet.dts - Decode timestamp of the packet
  12276. * @param {Number} packet.pts - Presentation timestamp of the packet
  12277. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  12278. * @param {('video'|'audio')} packet.type - The type of packet
  12279. *
  12280. */
  12281. this.push = function (packet) {
  12282. if (packet.type !== 'video') {
  12283. return;
  12284. }
  12285. trackId = packet.trackId;
  12286. currentPts = packet.pts;
  12287. currentDts = packet.dts;
  12288. nalByteStream.push(packet);
  12289. };
  12290. /*
  12291. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  12292. * for the NALUs to the next stream component.
  12293. * Also, preprocess caption and sequence parameter NALUs.
  12294. *
  12295. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  12296. * @see NalByteStream.push
  12297. */
  12298. nalByteStream.on('data', function (data) {
  12299. var event = {
  12300. trackId: trackId,
  12301. pts: currentPts,
  12302. dts: currentDts,
  12303. data: data,
  12304. nalUnitTypeCode: data[0] & 0x1f
  12305. };
  12306. switch (event.nalUnitTypeCode) {
  12307. case 0x05:
  12308. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  12309. break;
  12310. case 0x06:
  12311. event.nalUnitType = 'sei_rbsp';
  12312. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  12313. break;
  12314. case 0x07:
  12315. event.nalUnitType = 'seq_parameter_set_rbsp';
  12316. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  12317. event.config = readSequenceParameterSet(event.escapedRBSP);
  12318. break;
  12319. case 0x08:
  12320. event.nalUnitType = 'pic_parameter_set_rbsp';
  12321. break;
  12322. case 0x09:
  12323. event.nalUnitType = 'access_unit_delimiter_rbsp';
  12324. break;
  12325. } // This triggers data on the H264Stream
  12326. self.trigger('data', event);
  12327. });
  12328. nalByteStream.on('done', function () {
  12329. self.trigger('done');
  12330. });
  12331. nalByteStream.on('partialdone', function () {
  12332. self.trigger('partialdone');
  12333. });
  12334. nalByteStream.on('reset', function () {
  12335. self.trigger('reset');
  12336. });
  12337. nalByteStream.on('endedtimeline', function () {
  12338. self.trigger('endedtimeline');
  12339. });
  12340. this.flush = function () {
  12341. nalByteStream.flush();
  12342. };
  12343. this.partialFlush = function () {
  12344. nalByteStream.partialFlush();
  12345. };
  12346. this.reset = function () {
  12347. nalByteStream.reset();
  12348. };
  12349. this.endTimeline = function () {
  12350. nalByteStream.endTimeline();
  12351. };
  12352. /**
  12353. * Advance the ExpGolomb decoder past a scaling list. The scaling
  12354. * list is optionally transmitted as part of a sequence parameter
  12355. * set and is not relevant to transmuxing.
  12356. * @param count {number} the number of entries in this scaling list
  12357. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  12358. * start of a scaling list
  12359. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  12360. */
  12361. skipScalingList = function (count, expGolombDecoder) {
  12362. var lastScale = 8,
  12363. nextScale = 8,
  12364. j,
  12365. deltaScale;
  12366. for (j = 0; j < count; j++) {
  12367. if (nextScale !== 0) {
  12368. deltaScale = expGolombDecoder.readExpGolomb();
  12369. nextScale = (lastScale + deltaScale + 256) % 256;
  12370. }
  12371. lastScale = nextScale === 0 ? lastScale : nextScale;
  12372. }
  12373. };
  12374. /**
  12375. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  12376. * Sequence Payload"
  12377. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  12378. * unit
  12379. * @return {Uint8Array} the RBSP without any Emulation
  12380. * Prevention Bytes
  12381. */
  12382. discardEmulationPreventionBytes = function (data) {
  12383. var length = data.byteLength,
  12384. emulationPreventionBytesPositions = [],
  12385. i = 1,
  12386. newLength,
  12387. newData; // Find all `Emulation Prevention Bytes`
  12388. while (i < length - 2) {
  12389. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  12390. emulationPreventionBytesPositions.push(i + 2);
  12391. i += 2;
  12392. } else {
  12393. i++;
  12394. }
  12395. } // If no Emulation Prevention Bytes were found just return the original
  12396. // array
  12397. if (emulationPreventionBytesPositions.length === 0) {
  12398. return data;
  12399. } // Create a new array to hold the NAL unit data
  12400. newLength = length - emulationPreventionBytesPositions.length;
  12401. newData = new Uint8Array(newLength);
  12402. var sourceIndex = 0;
  12403. for (i = 0; i < newLength; sourceIndex++, i++) {
  12404. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  12405. // Skip this byte
  12406. sourceIndex++; // Remove this position index
  12407. emulationPreventionBytesPositions.shift();
  12408. }
  12409. newData[i] = data[sourceIndex];
  12410. }
  12411. return newData;
  12412. };
  12413. /**
  12414. * Read a sequence parameter set and return some interesting video
  12415. * properties. A sequence parameter set is the H264 metadata that
  12416. * describes the properties of upcoming video frames.
  12417. * @param data {Uint8Array} the bytes of a sequence parameter set
  12418. * @return {object} an object with configuration parsed from the
  12419. * sequence parameter set, including the dimensions of the
  12420. * associated video frames.
  12421. */
  12422. readSequenceParameterSet = function (data) {
  12423. var frameCropLeftOffset = 0,
  12424. frameCropRightOffset = 0,
  12425. frameCropTopOffset = 0,
  12426. frameCropBottomOffset = 0,
  12427. expGolombDecoder,
  12428. profileIdc,
  12429. levelIdc,
  12430. profileCompatibility,
  12431. chromaFormatIdc,
  12432. picOrderCntType,
  12433. numRefFramesInPicOrderCntCycle,
  12434. picWidthInMbsMinus1,
  12435. picHeightInMapUnitsMinus1,
  12436. frameMbsOnlyFlag,
  12437. scalingListCount,
  12438. sarRatio = [1, 1],
  12439. aspectRatioIdc,
  12440. i;
  12441. expGolombDecoder = new ExpGolomb(data);
  12442. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  12443. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  12444. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  12445. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  12446. // some profiles have more optional data we don't need
  12447. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  12448. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  12449. if (chromaFormatIdc === 3) {
  12450. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  12451. }
  12452. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  12453. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  12454. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  12455. if (expGolombDecoder.readBoolean()) {
  12456. // seq_scaling_matrix_present_flag
  12457. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  12458. for (i = 0; i < scalingListCount; i++) {
  12459. if (expGolombDecoder.readBoolean()) {
  12460. // seq_scaling_list_present_flag[ i ]
  12461. if (i < 6) {
  12462. skipScalingList(16, expGolombDecoder);
  12463. } else {
  12464. skipScalingList(64, expGolombDecoder);
  12465. }
  12466. }
  12467. }
  12468. }
  12469. }
  12470. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  12471. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  12472. if (picOrderCntType === 0) {
  12473. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  12474. } else if (picOrderCntType === 1) {
  12475. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  12476. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  12477. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  12478. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  12479. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  12480. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  12481. }
  12482. }
  12483. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  12484. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  12485. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  12486. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  12487. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  12488. if (frameMbsOnlyFlag === 0) {
  12489. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  12490. }
  12491. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  12492. if (expGolombDecoder.readBoolean()) {
  12493. // frame_cropping_flag
  12494. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  12495. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  12496. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  12497. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  12498. }
  12499. if (expGolombDecoder.readBoolean()) {
  12500. // vui_parameters_present_flag
  12501. if (expGolombDecoder.readBoolean()) {
  12502. // aspect_ratio_info_present_flag
  12503. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  12504. switch (aspectRatioIdc) {
  12505. case 1:
  12506. sarRatio = [1, 1];
  12507. break;
  12508. case 2:
  12509. sarRatio = [12, 11];
  12510. break;
  12511. case 3:
  12512. sarRatio = [10, 11];
  12513. break;
  12514. case 4:
  12515. sarRatio = [16, 11];
  12516. break;
  12517. case 5:
  12518. sarRatio = [40, 33];
  12519. break;
  12520. case 6:
  12521. sarRatio = [24, 11];
  12522. break;
  12523. case 7:
  12524. sarRatio = [20, 11];
  12525. break;
  12526. case 8:
  12527. sarRatio = [32, 11];
  12528. break;
  12529. case 9:
  12530. sarRatio = [80, 33];
  12531. break;
  12532. case 10:
  12533. sarRatio = [18, 11];
  12534. break;
  12535. case 11:
  12536. sarRatio = [15, 11];
  12537. break;
  12538. case 12:
  12539. sarRatio = [64, 33];
  12540. break;
  12541. case 13:
  12542. sarRatio = [160, 99];
  12543. break;
  12544. case 14:
  12545. sarRatio = [4, 3];
  12546. break;
  12547. case 15:
  12548. sarRatio = [3, 2];
  12549. break;
  12550. case 16:
  12551. sarRatio = [2, 1];
  12552. break;
  12553. case 255:
  12554. {
  12555. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  12556. break;
  12557. }
  12558. }
  12559. if (sarRatio) {
  12560. sarRatio[0] / sarRatio[1];
  12561. }
  12562. }
  12563. }
  12564. return {
  12565. profileIdc: profileIdc,
  12566. levelIdc: levelIdc,
  12567. profileCompatibility: profileCompatibility,
  12568. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  12569. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  12570. // sar is sample aspect ratio
  12571. sarRatio: sarRatio
  12572. };
  12573. };
  12574. };
  12575. H264Stream$1.prototype = new Stream$2();
  12576. var h264 = {
  12577. H264Stream: H264Stream$1,
  12578. NalByteStream: NalByteStream
  12579. };
  12580. /**
  12581. * mux.js
  12582. *
  12583. * Copyright (c) Brightcove
  12584. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12585. *
  12586. * Utilities to detect basic properties and metadata about Aac data.
  12587. */
  12588. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  12589. var parseId3TagSize = function (header, byteIndex) {
  12590. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  12591. flags = header[byteIndex + 5],
  12592. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  12593. returnSize = returnSize >= 0 ? returnSize : 0;
  12594. if (footerPresent) {
  12595. return returnSize + 20;
  12596. }
  12597. return returnSize + 10;
  12598. };
  12599. var getId3Offset = function (data, offset) {
  12600. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  12601. return offset;
  12602. }
  12603. offset += parseId3TagSize(data, offset);
  12604. return getId3Offset(data, offset);
  12605. }; // TODO: use vhs-utils
  12606. var isLikelyAacData$1 = function (data) {
  12607. var offset = getId3Offset(data, 0);
  12608. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  12609. // is not mp3 data but aac data.
  12610. (data[offset + 1] & 0x16) === 0x10;
  12611. };
  12612. var parseSyncSafeInteger = function (data) {
  12613. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  12614. }; // return a percent-encoded representation of the specified byte range
  12615. // @see http://en.wikipedia.org/wiki/Percent-encoding
  12616. var percentEncode = function (bytes, start, end) {
  12617. var i,
  12618. result = '';
  12619. for (i = start; i < end; i++) {
  12620. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  12621. }
  12622. return result;
  12623. }; // return the string representation of the specified byte range,
  12624. // interpreted as ISO-8859-1.
  12625. var parseIso88591 = function (bytes, start, end) {
  12626. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  12627. };
  12628. var parseAdtsSize = function (header, byteIndex) {
  12629. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  12630. middle = header[byteIndex + 4] << 3,
  12631. highTwo = header[byteIndex + 3] & 0x3 << 11;
  12632. return highTwo | middle | lowThree;
  12633. };
  12634. var parseType$4 = function (header, byteIndex) {
  12635. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  12636. return 'timed-metadata';
  12637. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  12638. return 'audio';
  12639. }
  12640. return null;
  12641. };
  12642. var parseSampleRate = function (packet) {
  12643. var i = 0;
  12644. while (i + 5 < packet.length) {
  12645. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  12646. // If a valid header was not found, jump one forward and attempt to
  12647. // find a valid ADTS header starting at the next byte
  12648. i++;
  12649. continue;
  12650. }
  12651. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  12652. }
  12653. return null;
  12654. };
  12655. var parseAacTimestamp = function (packet) {
  12656. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  12657. frameStart = 10;
  12658. if (packet[5] & 0x40) {
  12659. // advance the frame start past the extended header
  12660. frameStart += 4; // header size field
  12661. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  12662. } // parse one or more ID3 frames
  12663. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  12664. do {
  12665. // determine the number of bytes in this frame
  12666. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  12667. if (frameSize < 1) {
  12668. return null;
  12669. }
  12670. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  12671. if (frameHeader === 'PRIV') {
  12672. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  12673. for (var i = 0; i < frame.byteLength; i++) {
  12674. if (frame[i] === 0) {
  12675. var owner = parseIso88591(frame, 0, i);
  12676. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  12677. var d = frame.subarray(i + 1);
  12678. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  12679. size *= 4;
  12680. size += d[7] & 0x03;
  12681. return size;
  12682. }
  12683. break;
  12684. }
  12685. }
  12686. }
  12687. frameStart += 10; // advance past the frame header
  12688. frameStart += frameSize; // advance past the frame body
  12689. } while (frameStart < packet.byteLength);
  12690. return null;
  12691. };
  12692. var utils = {
  12693. isLikelyAacData: isLikelyAacData$1,
  12694. parseId3TagSize: parseId3TagSize,
  12695. parseAdtsSize: parseAdtsSize,
  12696. parseType: parseType$4,
  12697. parseSampleRate: parseSampleRate,
  12698. parseAacTimestamp: parseAacTimestamp
  12699. };
  12700. /**
  12701. * mux.js
  12702. *
  12703. * Copyright (c) Brightcove
  12704. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12705. *
  12706. * A stream-based aac to mp4 converter. This utility can be used to
  12707. * deliver mp4s to a SourceBuffer on platforms that support native
  12708. * Media Source Extensions.
  12709. */
  12710. var Stream$1 = stream;
  12711. var aacUtils = utils; // Constants
  12712. var AacStream$1;
  12713. /**
  12714. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  12715. */
  12716. AacStream$1 = function () {
  12717. var everything = new Uint8Array(),
  12718. timeStamp = 0;
  12719. AacStream$1.prototype.init.call(this);
  12720. this.setTimestamp = function (timestamp) {
  12721. timeStamp = timestamp;
  12722. };
  12723. this.push = function (bytes) {
  12724. var frameSize = 0,
  12725. byteIndex = 0,
  12726. bytesLeft,
  12727. chunk,
  12728. packet,
  12729. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  12730. // bytes that were pushed in
  12731. if (everything.length) {
  12732. tempLength = everything.length;
  12733. everything = new Uint8Array(bytes.byteLength + tempLength);
  12734. everything.set(everything.subarray(0, tempLength));
  12735. everything.set(bytes, tempLength);
  12736. } else {
  12737. everything = bytes;
  12738. }
  12739. while (everything.length - byteIndex >= 3) {
  12740. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  12741. // Exit early because we don't have enough to parse
  12742. // the ID3 tag header
  12743. if (everything.length - byteIndex < 10) {
  12744. break;
  12745. } // check framesize
  12746. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  12747. // to emit a full packet
  12748. // Add to byteIndex to support multiple ID3 tags in sequence
  12749. if (byteIndex + frameSize > everything.length) {
  12750. break;
  12751. }
  12752. chunk = {
  12753. type: 'timed-metadata',
  12754. data: everything.subarray(byteIndex, byteIndex + frameSize)
  12755. };
  12756. this.trigger('data', chunk);
  12757. byteIndex += frameSize;
  12758. continue;
  12759. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  12760. // Exit early because we don't have enough to parse
  12761. // the ADTS frame header
  12762. if (everything.length - byteIndex < 7) {
  12763. break;
  12764. }
  12765. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  12766. // to emit a full packet
  12767. if (byteIndex + frameSize > everything.length) {
  12768. break;
  12769. }
  12770. packet = {
  12771. type: 'audio',
  12772. data: everything.subarray(byteIndex, byteIndex + frameSize),
  12773. pts: timeStamp,
  12774. dts: timeStamp
  12775. };
  12776. this.trigger('data', packet);
  12777. byteIndex += frameSize;
  12778. continue;
  12779. }
  12780. byteIndex++;
  12781. }
  12782. bytesLeft = everything.length - byteIndex;
  12783. if (bytesLeft > 0) {
  12784. everything = everything.subarray(byteIndex);
  12785. } else {
  12786. everything = new Uint8Array();
  12787. }
  12788. };
  12789. this.reset = function () {
  12790. everything = new Uint8Array();
  12791. this.trigger('reset');
  12792. };
  12793. this.endTimeline = function () {
  12794. everything = new Uint8Array();
  12795. this.trigger('endedtimeline');
  12796. };
  12797. };
  12798. AacStream$1.prototype = new Stream$1();
  12799. var aac = AacStream$1;
  12800. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  12801. var audioProperties = AUDIO_PROPERTIES$1;
  12802. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  12803. var videoProperties = VIDEO_PROPERTIES$1;
  12804. /**
  12805. * mux.js
  12806. *
  12807. * Copyright (c) Brightcove
  12808. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12809. *
  12810. * A stream-based mp2t to mp4 converter. This utility can be used to
  12811. * deliver mp4s to a SourceBuffer on platforms that support native
  12812. * Media Source Extensions.
  12813. */
  12814. var Stream = stream;
  12815. var mp4 = mp4Generator;
  12816. var frameUtils = frameUtils$1;
  12817. var audioFrameUtils = audioFrameUtils$1;
  12818. var trackDecodeInfo = trackDecodeInfo$1;
  12819. var m2ts = m2ts_1;
  12820. var clock = clock$2;
  12821. var AdtsStream = adts;
  12822. var H264Stream = h264.H264Stream;
  12823. var AacStream = aac;
  12824. var isLikelyAacData = utils.isLikelyAacData;
  12825. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  12826. var AUDIO_PROPERTIES = audioProperties;
  12827. var VIDEO_PROPERTIES = videoProperties; // object types
  12828. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  12829. var retriggerForStream = function (key, event) {
  12830. event.stream = key;
  12831. this.trigger('log', event);
  12832. };
  12833. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  12834. var keys = Object.keys(pipeline);
  12835. for (var i = 0; i < keys.length; i++) {
  12836. var key = keys[i]; // skip non-stream keys and headOfPipeline
  12837. // which is just a duplicate
  12838. if (key === 'headOfPipeline' || !pipeline[key].on) {
  12839. continue;
  12840. }
  12841. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  12842. }
  12843. };
  12844. /**
  12845. * Compare two arrays (even typed) for same-ness
  12846. */
  12847. var arrayEquals = function (a, b) {
  12848. var i;
  12849. if (a.length !== b.length) {
  12850. return false;
  12851. } // compare the value of each element in the array
  12852. for (i = 0; i < a.length; i++) {
  12853. if (a[i] !== b[i]) {
  12854. return false;
  12855. }
  12856. }
  12857. return true;
  12858. };
  12859. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  12860. var ptsOffsetFromDts = startPts - startDts,
  12861. decodeDuration = endDts - startDts,
  12862. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  12863. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  12864. // In order to provide relevant values for the player times, base timing info on the
  12865. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  12866. return {
  12867. start: {
  12868. dts: baseMediaDecodeTime,
  12869. pts: baseMediaDecodeTime + ptsOffsetFromDts
  12870. },
  12871. end: {
  12872. dts: baseMediaDecodeTime + decodeDuration,
  12873. pts: baseMediaDecodeTime + presentationDuration
  12874. },
  12875. prependedContentDuration: prependedContentDuration,
  12876. baseMediaDecodeTime: baseMediaDecodeTime
  12877. };
  12878. };
  12879. /**
  12880. * Constructs a single-track, ISO BMFF media segment from AAC data
  12881. * events. The output of this stream can be fed to a SourceBuffer
  12882. * configured with a suitable initialization segment.
  12883. * @param track {object} track metadata configuration
  12884. * @param options {object} transmuxer options object
  12885. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  12886. * in the source; false to adjust the first segment to start at 0.
  12887. */
  12888. AudioSegmentStream = function (track, options) {
  12889. var adtsFrames = [],
  12890. sequenceNumber,
  12891. earliestAllowedDts = 0,
  12892. audioAppendStartTs = 0,
  12893. videoBaseMediaDecodeTime = Infinity;
  12894. options = options || {};
  12895. sequenceNumber = options.firstSequenceNumber || 0;
  12896. AudioSegmentStream.prototype.init.call(this);
  12897. this.push = function (data) {
  12898. trackDecodeInfo.collectDtsInfo(track, data);
  12899. if (track) {
  12900. AUDIO_PROPERTIES.forEach(function (prop) {
  12901. track[prop] = data[prop];
  12902. });
  12903. } // buffer audio data until end() is called
  12904. adtsFrames.push(data);
  12905. };
  12906. this.setEarliestDts = function (earliestDts) {
  12907. earliestAllowedDts = earliestDts;
  12908. };
  12909. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  12910. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  12911. };
  12912. this.setAudioAppendStart = function (timestamp) {
  12913. audioAppendStartTs = timestamp;
  12914. };
  12915. this.flush = function () {
  12916. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  12917. if (adtsFrames.length === 0) {
  12918. this.trigger('done', 'AudioSegmentStream');
  12919. return;
  12920. }
  12921. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  12922. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  12923. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  12924. // samples (that is, adts frames) in the audio data
  12925. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  12926. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  12927. adtsFrames = [];
  12928. moof = mp4.moof(sequenceNumber, [track]);
  12929. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  12930. sequenceNumber++;
  12931. boxes.set(moof);
  12932. boxes.set(mdat, moof.byteLength);
  12933. trackDecodeInfo.clearDtsInfo(track);
  12934. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  12935. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  12936. // valid use-case where an init segment/data should be triggered without associated
  12937. // frames. Leaving for now, but should be looked into.
  12938. if (frames.length) {
  12939. segmentDuration = frames.length * frameDuration;
  12940. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  12941. // frame info is in video clock cycles. Convert to match expectation of
  12942. // listeners (that all timestamps will be based on video clock cycles).
  12943. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  12944. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  12945. this.trigger('timingInfo', {
  12946. start: frames[0].pts,
  12947. end: frames[0].pts + segmentDuration
  12948. });
  12949. }
  12950. this.trigger('data', {
  12951. track: track,
  12952. boxes: boxes
  12953. });
  12954. this.trigger('done', 'AudioSegmentStream');
  12955. };
  12956. this.reset = function () {
  12957. trackDecodeInfo.clearDtsInfo(track);
  12958. adtsFrames = [];
  12959. this.trigger('reset');
  12960. };
  12961. };
  12962. AudioSegmentStream.prototype = new Stream();
  12963. /**
  12964. * Constructs a single-track, ISO BMFF media segment from H264 data
  12965. * events. The output of this stream can be fed to a SourceBuffer
  12966. * configured with a suitable initialization segment.
  12967. * @param track {object} track metadata configuration
  12968. * @param options {object} transmuxer options object
  12969. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  12970. * gopsToAlignWith list when attempting to align gop pts
  12971. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  12972. * in the source; false to adjust the first segment to start at 0.
  12973. */
  12974. VideoSegmentStream = function (track, options) {
  12975. var sequenceNumber,
  12976. nalUnits = [],
  12977. gopsToAlignWith = [],
  12978. config,
  12979. pps;
  12980. options = options || {};
  12981. sequenceNumber = options.firstSequenceNumber || 0;
  12982. VideoSegmentStream.prototype.init.call(this);
  12983. delete track.minPTS;
  12984. this.gopCache_ = [];
  12985. /**
  12986. * Constructs a ISO BMFF segment given H264 nalUnits
  12987. * @param {Object} nalUnit A data event representing a nalUnit
  12988. * @param {String} nalUnit.nalUnitType
  12989. * @param {Object} nalUnit.config Properties for a mp4 track
  12990. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  12991. * @see lib/codecs/h264.js
  12992. **/
  12993. this.push = function (nalUnit) {
  12994. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  12995. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  12996. config = nalUnit.config;
  12997. track.sps = [nalUnit.data];
  12998. VIDEO_PROPERTIES.forEach(function (prop) {
  12999. track[prop] = config[prop];
  13000. }, this);
  13001. }
  13002. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  13003. pps = nalUnit.data;
  13004. track.pps = [nalUnit.data];
  13005. } // buffer video until flush() is called
  13006. nalUnits.push(nalUnit);
  13007. };
  13008. /**
  13009. * Pass constructed ISO BMFF track and boxes on to the
  13010. * next stream in the pipeline
  13011. **/
  13012. this.flush = function () {
  13013. var frames,
  13014. gopForFusion,
  13015. gops,
  13016. moof,
  13017. mdat,
  13018. boxes,
  13019. prependedContentDuration = 0,
  13020. firstGop,
  13021. lastGop; // Throw away nalUnits at the start of the byte stream until
  13022. // we find the first AUD
  13023. while (nalUnits.length) {
  13024. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  13025. break;
  13026. }
  13027. nalUnits.shift();
  13028. } // Return early if no video data has been observed
  13029. if (nalUnits.length === 0) {
  13030. this.resetStream_();
  13031. this.trigger('done', 'VideoSegmentStream');
  13032. return;
  13033. } // Organize the raw nal-units into arrays that represent
  13034. // higher-level constructs such as frames and gops
  13035. // (group-of-pictures)
  13036. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  13037. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  13038. // a problem since MSE (on Chrome) requires a leading keyframe.
  13039. //
  13040. // We have two approaches to repairing this situation:
  13041. // 1) GOP-FUSION:
  13042. // This is where we keep track of the GOPS (group-of-pictures)
  13043. // from previous fragments and attempt to find one that we can
  13044. // prepend to the current fragment in order to create a valid
  13045. // fragment.
  13046. // 2) KEYFRAME-PULLING:
  13047. // Here we search for the first keyframe in the fragment and
  13048. // throw away all the frames between the start of the fragment
  13049. // and that keyframe. We then extend the duration and pull the
  13050. // PTS of the keyframe forward so that it covers the time range
  13051. // of the frames that were disposed of.
  13052. //
  13053. // #1 is far prefereable over #2 which can cause "stuttering" but
  13054. // requires more things to be just right.
  13055. if (!gops[0][0].keyFrame) {
  13056. // Search for a gop for fusion from our gopCache
  13057. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  13058. if (gopForFusion) {
  13059. // in order to provide more accurate timing information about the segment, save
  13060. // the number of seconds prepended to the original segment due to GOP fusion
  13061. prependedContentDuration = gopForFusion.duration;
  13062. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  13063. // new gop at the beginning
  13064. gops.byteLength += gopForFusion.byteLength;
  13065. gops.nalCount += gopForFusion.nalCount;
  13066. gops.pts = gopForFusion.pts;
  13067. gops.dts = gopForFusion.dts;
  13068. gops.duration += gopForFusion.duration;
  13069. } else {
  13070. // If we didn't find a candidate gop fall back to keyframe-pulling
  13071. gops = frameUtils.extendFirstKeyFrame(gops);
  13072. }
  13073. } // Trim gops to align with gopsToAlignWith
  13074. if (gopsToAlignWith.length) {
  13075. var alignedGops;
  13076. if (options.alignGopsAtEnd) {
  13077. alignedGops = this.alignGopsAtEnd_(gops);
  13078. } else {
  13079. alignedGops = this.alignGopsAtStart_(gops);
  13080. }
  13081. if (!alignedGops) {
  13082. // save all the nals in the last GOP into the gop cache
  13083. this.gopCache_.unshift({
  13084. gop: gops.pop(),
  13085. pps: track.pps,
  13086. sps: track.sps
  13087. }); // Keep a maximum of 6 GOPs in the cache
  13088. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13089. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  13090. this.resetStream_();
  13091. this.trigger('done', 'VideoSegmentStream');
  13092. return;
  13093. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  13094. // when recalculated before sending off to CoalesceStream
  13095. trackDecodeInfo.clearDtsInfo(track);
  13096. gops = alignedGops;
  13097. }
  13098. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  13099. // samples (that is, frames) in the video data
  13100. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  13101. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  13102. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  13103. this.trigger('processedGopsInfo', gops.map(function (gop) {
  13104. return {
  13105. pts: gop.pts,
  13106. dts: gop.dts,
  13107. byteLength: gop.byteLength
  13108. };
  13109. }));
  13110. firstGop = gops[0];
  13111. lastGop = gops[gops.length - 1];
  13112. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  13113. this.trigger('timingInfo', {
  13114. start: gops[0].pts,
  13115. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  13116. }); // save all the nals in the last GOP into the gop cache
  13117. this.gopCache_.unshift({
  13118. gop: gops.pop(),
  13119. pps: track.pps,
  13120. sps: track.sps
  13121. }); // Keep a maximum of 6 GOPs in the cache
  13122. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13123. nalUnits = [];
  13124. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  13125. this.trigger('timelineStartInfo', track.timelineStartInfo);
  13126. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  13127. // throwing away hundreds of media segment fragments
  13128. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  13129. sequenceNumber++;
  13130. boxes.set(moof);
  13131. boxes.set(mdat, moof.byteLength);
  13132. this.trigger('data', {
  13133. track: track,
  13134. boxes: boxes
  13135. });
  13136. this.resetStream_(); // Continue with the flush process now
  13137. this.trigger('done', 'VideoSegmentStream');
  13138. };
  13139. this.reset = function () {
  13140. this.resetStream_();
  13141. nalUnits = [];
  13142. this.gopCache_.length = 0;
  13143. gopsToAlignWith.length = 0;
  13144. this.trigger('reset');
  13145. };
  13146. this.resetStream_ = function () {
  13147. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  13148. // for instance, when we are rendition switching
  13149. config = undefined;
  13150. pps = undefined;
  13151. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  13152. // return it or return null if no good candidate was found
  13153. this.getGopForFusion_ = function (nalUnit) {
  13154. var halfSecond = 45000,
  13155. // Half-a-second in a 90khz clock
  13156. allowableOverlap = 10000,
  13157. // About 3 frames @ 30fps
  13158. nearestDistance = Infinity,
  13159. dtsDistance,
  13160. nearestGopObj,
  13161. currentGop,
  13162. currentGopObj,
  13163. i; // Search for the GOP nearest to the beginning of this nal unit
  13164. for (i = 0; i < this.gopCache_.length; i++) {
  13165. currentGopObj = this.gopCache_[i];
  13166. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  13167. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  13168. continue;
  13169. } // Reject Gops that would require a negative baseMediaDecodeTime
  13170. if (currentGop.dts < track.timelineStartInfo.dts) {
  13171. continue;
  13172. } // The distance between the end of the gop and the start of the nalUnit
  13173. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  13174. // a half-second of the nal unit
  13175. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  13176. // Always use the closest GOP we found if there is more than
  13177. // one candidate
  13178. if (!nearestGopObj || nearestDistance > dtsDistance) {
  13179. nearestGopObj = currentGopObj;
  13180. nearestDistance = dtsDistance;
  13181. }
  13182. }
  13183. }
  13184. if (nearestGopObj) {
  13185. return nearestGopObj.gop;
  13186. }
  13187. return null;
  13188. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  13189. // of gopsToAlignWith starting from the START of the list
  13190. this.alignGopsAtStart_ = function (gops) {
  13191. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  13192. byteLength = gops.byteLength;
  13193. nalCount = gops.nalCount;
  13194. duration = gops.duration;
  13195. alignIndex = gopIndex = 0;
  13196. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  13197. align = gopsToAlignWith[alignIndex];
  13198. gop = gops[gopIndex];
  13199. if (align.pts === gop.pts) {
  13200. break;
  13201. }
  13202. if (gop.pts > align.pts) {
  13203. // this current gop starts after the current gop we want to align on, so increment
  13204. // align index
  13205. alignIndex++;
  13206. continue;
  13207. } // current gop starts before the current gop we want to align on. so increment gop
  13208. // index
  13209. gopIndex++;
  13210. byteLength -= gop.byteLength;
  13211. nalCount -= gop.nalCount;
  13212. duration -= gop.duration;
  13213. }
  13214. if (gopIndex === 0) {
  13215. // no gops to trim
  13216. return gops;
  13217. }
  13218. if (gopIndex === gops.length) {
  13219. // all gops trimmed, skip appending all gops
  13220. return null;
  13221. }
  13222. alignedGops = gops.slice(gopIndex);
  13223. alignedGops.byteLength = byteLength;
  13224. alignedGops.duration = duration;
  13225. alignedGops.nalCount = nalCount;
  13226. alignedGops.pts = alignedGops[0].pts;
  13227. alignedGops.dts = alignedGops[0].dts;
  13228. return alignedGops;
  13229. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  13230. // of gopsToAlignWith starting from the END of the list
  13231. this.alignGopsAtEnd_ = function (gops) {
  13232. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  13233. alignIndex = gopsToAlignWith.length - 1;
  13234. gopIndex = gops.length - 1;
  13235. alignEndIndex = null;
  13236. matchFound = false;
  13237. while (alignIndex >= 0 && gopIndex >= 0) {
  13238. align = gopsToAlignWith[alignIndex];
  13239. gop = gops[gopIndex];
  13240. if (align.pts === gop.pts) {
  13241. matchFound = true;
  13242. break;
  13243. }
  13244. if (align.pts > gop.pts) {
  13245. alignIndex--;
  13246. continue;
  13247. }
  13248. if (alignIndex === gopsToAlignWith.length - 1) {
  13249. // gop.pts is greater than the last alignment candidate. If no match is found
  13250. // by the end of this loop, we still want to append gops that come after this
  13251. // point
  13252. alignEndIndex = gopIndex;
  13253. }
  13254. gopIndex--;
  13255. }
  13256. if (!matchFound && alignEndIndex === null) {
  13257. return null;
  13258. }
  13259. var trimIndex;
  13260. if (matchFound) {
  13261. trimIndex = gopIndex;
  13262. } else {
  13263. trimIndex = alignEndIndex;
  13264. }
  13265. if (trimIndex === 0) {
  13266. return gops;
  13267. }
  13268. var alignedGops = gops.slice(trimIndex);
  13269. var metadata = alignedGops.reduce(function (total, gop) {
  13270. total.byteLength += gop.byteLength;
  13271. total.duration += gop.duration;
  13272. total.nalCount += gop.nalCount;
  13273. return total;
  13274. }, {
  13275. byteLength: 0,
  13276. duration: 0,
  13277. nalCount: 0
  13278. });
  13279. alignedGops.byteLength = metadata.byteLength;
  13280. alignedGops.duration = metadata.duration;
  13281. alignedGops.nalCount = metadata.nalCount;
  13282. alignedGops.pts = alignedGops[0].pts;
  13283. alignedGops.dts = alignedGops[0].dts;
  13284. return alignedGops;
  13285. };
  13286. this.alignGopsWith = function (newGopsToAlignWith) {
  13287. gopsToAlignWith = newGopsToAlignWith;
  13288. };
  13289. };
  13290. VideoSegmentStream.prototype = new Stream();
  13291. /**
  13292. * A Stream that can combine multiple streams (ie. audio & video)
  13293. * into a single output segment for MSE. Also supports audio-only
  13294. * and video-only streams.
  13295. * @param options {object} transmuxer options object
  13296. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  13297. * in the source; false to adjust the first segment to start at media timeline start.
  13298. */
  13299. CoalesceStream = function (options, metadataStream) {
  13300. // Number of Tracks per output segment
  13301. // If greater than 1, we combine multiple
  13302. // tracks into a single segment
  13303. this.numberOfTracks = 0;
  13304. this.metadataStream = metadataStream;
  13305. options = options || {};
  13306. if (typeof options.remux !== 'undefined') {
  13307. this.remuxTracks = !!options.remux;
  13308. } else {
  13309. this.remuxTracks = true;
  13310. }
  13311. if (typeof options.keepOriginalTimestamps === 'boolean') {
  13312. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  13313. } else {
  13314. this.keepOriginalTimestamps = false;
  13315. }
  13316. this.pendingTracks = [];
  13317. this.videoTrack = null;
  13318. this.pendingBoxes = [];
  13319. this.pendingCaptions = [];
  13320. this.pendingMetadata = [];
  13321. this.pendingBytes = 0;
  13322. this.emittedTracks = 0;
  13323. CoalesceStream.prototype.init.call(this); // Take output from multiple
  13324. this.push = function (output) {
  13325. // buffer incoming captions until the associated video segment
  13326. // finishes
  13327. if (output.text) {
  13328. return this.pendingCaptions.push(output);
  13329. } // buffer incoming id3 tags until the final flush
  13330. if (output.frames) {
  13331. return this.pendingMetadata.push(output);
  13332. } // Add this track to the list of pending tracks and store
  13333. // important information required for the construction of
  13334. // the final segment
  13335. this.pendingTracks.push(output.track);
  13336. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  13337. // We unshift audio and push video because
  13338. // as of Chrome 75 when switching from
  13339. // one init segment to another if the video
  13340. // mdat does not appear after the audio mdat
  13341. // only audio will play for the duration of our transmux.
  13342. if (output.track.type === 'video') {
  13343. this.videoTrack = output.track;
  13344. this.pendingBoxes.push(output.boxes);
  13345. }
  13346. if (output.track.type === 'audio') {
  13347. this.audioTrack = output.track;
  13348. this.pendingBoxes.unshift(output.boxes);
  13349. }
  13350. };
  13351. };
  13352. CoalesceStream.prototype = new Stream();
  13353. CoalesceStream.prototype.flush = function (flushSource) {
  13354. var offset = 0,
  13355. event = {
  13356. captions: [],
  13357. captionStreams: {},
  13358. metadata: [],
  13359. info: {}
  13360. },
  13361. caption,
  13362. id3,
  13363. initSegment,
  13364. timelineStartPts = 0,
  13365. i;
  13366. if (this.pendingTracks.length < this.numberOfTracks) {
  13367. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  13368. // Return because we haven't received a flush from a data-generating
  13369. // portion of the segment (meaning that we have only recieved meta-data
  13370. // or captions.)
  13371. return;
  13372. } else if (this.remuxTracks) {
  13373. // Return until we have enough tracks from the pipeline to remux (if we
  13374. // are remuxing audio and video into a single MP4)
  13375. return;
  13376. } else if (this.pendingTracks.length === 0) {
  13377. // In the case where we receive a flush without any data having been
  13378. // received we consider it an emitted track for the purposes of coalescing
  13379. // `done` events.
  13380. // We do this for the case where there is an audio and video track in the
  13381. // segment but no audio data. (seen in several playlists with alternate
  13382. // audio tracks and no audio present in the main TS segments.)
  13383. this.emittedTracks++;
  13384. if (this.emittedTracks >= this.numberOfTracks) {
  13385. this.trigger('done');
  13386. this.emittedTracks = 0;
  13387. }
  13388. return;
  13389. }
  13390. }
  13391. if (this.videoTrack) {
  13392. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  13393. VIDEO_PROPERTIES.forEach(function (prop) {
  13394. event.info[prop] = this.videoTrack[prop];
  13395. }, this);
  13396. } else if (this.audioTrack) {
  13397. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  13398. AUDIO_PROPERTIES.forEach(function (prop) {
  13399. event.info[prop] = this.audioTrack[prop];
  13400. }, this);
  13401. }
  13402. if (this.videoTrack || this.audioTrack) {
  13403. if (this.pendingTracks.length === 1) {
  13404. event.type = this.pendingTracks[0].type;
  13405. } else {
  13406. event.type = 'combined';
  13407. }
  13408. this.emittedTracks += this.pendingTracks.length;
  13409. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  13410. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  13411. // and track definitions
  13412. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  13413. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  13414. for (i = 0; i < this.pendingBoxes.length; i++) {
  13415. event.data.set(this.pendingBoxes[i], offset);
  13416. offset += this.pendingBoxes[i].byteLength;
  13417. } // Translate caption PTS times into second offsets to match the
  13418. // video timeline for the segment, and add track info
  13419. for (i = 0; i < this.pendingCaptions.length; i++) {
  13420. caption = this.pendingCaptions[i];
  13421. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  13422. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  13423. event.captionStreams[caption.stream] = true;
  13424. event.captions.push(caption);
  13425. } // Translate ID3 frame PTS times into second offsets to match the
  13426. // video timeline for the segment
  13427. for (i = 0; i < this.pendingMetadata.length; i++) {
  13428. id3 = this.pendingMetadata[i];
  13429. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  13430. event.metadata.push(id3);
  13431. } // We add this to every single emitted segment even though we only need
  13432. // it for the first
  13433. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  13434. this.pendingTracks.length = 0;
  13435. this.videoTrack = null;
  13436. this.pendingBoxes.length = 0;
  13437. this.pendingCaptions.length = 0;
  13438. this.pendingBytes = 0;
  13439. this.pendingMetadata.length = 0; // Emit the built segment
  13440. // We include captions and ID3 tags for backwards compatibility,
  13441. // ideally we should send only video and audio in the data event
  13442. this.trigger('data', event); // Emit each caption to the outside world
  13443. // Ideally, this would happen immediately on parsing captions,
  13444. // but we need to ensure that video data is sent back first
  13445. // so that caption timing can be adjusted to match video timing
  13446. for (i = 0; i < event.captions.length; i++) {
  13447. caption = event.captions[i];
  13448. this.trigger('caption', caption);
  13449. } // Emit each id3 tag to the outside world
  13450. // Ideally, this would happen immediately on parsing the tag,
  13451. // but we need to ensure that video data is sent back first
  13452. // so that ID3 frame timing can be adjusted to match video timing
  13453. for (i = 0; i < event.metadata.length; i++) {
  13454. id3 = event.metadata[i];
  13455. this.trigger('id3Frame', id3);
  13456. }
  13457. } // Only emit `done` if all tracks have been flushed and emitted
  13458. if (this.emittedTracks >= this.numberOfTracks) {
  13459. this.trigger('done');
  13460. this.emittedTracks = 0;
  13461. }
  13462. };
  13463. CoalesceStream.prototype.setRemux = function (val) {
  13464. this.remuxTracks = val;
  13465. };
  13466. /**
  13467. * A Stream that expects MP2T binary data as input and produces
  13468. * corresponding media segments, suitable for use with Media Source
  13469. * Extension (MSE) implementations that support the ISO BMFF byte
  13470. * stream format, like Chrome.
  13471. */
  13472. Transmuxer = function (options) {
  13473. var self = this,
  13474. hasFlushed = true,
  13475. videoTrack,
  13476. audioTrack;
  13477. Transmuxer.prototype.init.call(this);
  13478. options = options || {};
  13479. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  13480. this.transmuxPipeline_ = {};
  13481. this.setupAacPipeline = function () {
  13482. var pipeline = {};
  13483. this.transmuxPipeline_ = pipeline;
  13484. pipeline.type = 'aac';
  13485. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  13486. pipeline.aacStream = new AacStream();
  13487. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  13488. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  13489. pipeline.adtsStream = new AdtsStream();
  13490. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  13491. pipeline.headOfPipeline = pipeline.aacStream;
  13492. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  13493. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  13494. pipeline.metadataStream.on('timestamp', function (frame) {
  13495. pipeline.aacStream.setTimestamp(frame.timeStamp);
  13496. });
  13497. pipeline.aacStream.on('data', function (data) {
  13498. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  13499. return;
  13500. }
  13501. audioTrack = audioTrack || {
  13502. timelineStartInfo: {
  13503. baseMediaDecodeTime: self.baseMediaDecodeTime
  13504. },
  13505. codec: 'adts',
  13506. type: 'audio'
  13507. }; // hook up the audio segment stream to the first track with aac data
  13508. pipeline.coalesceStream.numberOfTracks++;
  13509. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  13510. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  13511. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  13512. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  13513. self.trigger('trackinfo', {
  13514. hasAudio: !!audioTrack,
  13515. hasVideo: !!videoTrack
  13516. });
  13517. }); // Re-emit any data coming from the coalesce stream to the outside world
  13518. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  13519. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  13520. addPipelineLogRetriggers(this, pipeline);
  13521. };
  13522. this.setupTsPipeline = function () {
  13523. var pipeline = {};
  13524. this.transmuxPipeline_ = pipeline;
  13525. pipeline.type = 'ts';
  13526. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  13527. pipeline.packetStream = new m2ts.TransportPacketStream();
  13528. pipeline.parseStream = new m2ts.TransportParseStream();
  13529. pipeline.elementaryStream = new m2ts.ElementaryStream();
  13530. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  13531. pipeline.adtsStream = new AdtsStream();
  13532. pipeline.h264Stream = new H264Stream();
  13533. pipeline.captionStream = new m2ts.CaptionStream(options);
  13534. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  13535. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  13536. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  13537. // demux the streams
  13538. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  13539. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  13540. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  13541. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  13542. pipeline.elementaryStream.on('data', function (data) {
  13543. var i;
  13544. if (data.type === 'metadata') {
  13545. i = data.tracks.length; // scan the tracks listed in the metadata
  13546. while (i--) {
  13547. if (!videoTrack && data.tracks[i].type === 'video') {
  13548. videoTrack = data.tracks[i];
  13549. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  13550. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  13551. audioTrack = data.tracks[i];
  13552. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  13553. }
  13554. } // hook up the video segment stream to the first track with h264 data
  13555. if (videoTrack && !pipeline.videoSegmentStream) {
  13556. pipeline.coalesceStream.numberOfTracks++;
  13557. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  13558. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  13559. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  13560. // When video emits timelineStartInfo data after a flush, we forward that
  13561. // info to the AudioSegmentStream, if it exists, because video timeline
  13562. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  13563. // because this is a particularly subtle form of timestamp alteration.
  13564. if (audioTrack && !options.keepOriginalTimestamps) {
  13565. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  13566. // very earliest DTS we have seen in video because Chrome will
  13567. // interpret any video track with a baseMediaDecodeTime that is
  13568. // non-zero as a gap.
  13569. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  13570. }
  13571. });
  13572. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  13573. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  13574. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  13575. if (audioTrack) {
  13576. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  13577. }
  13578. });
  13579. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  13580. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  13581. }
  13582. if (audioTrack && !pipeline.audioSegmentStream) {
  13583. // hook up the audio segment stream to the first track with aac data
  13584. pipeline.coalesceStream.numberOfTracks++;
  13585. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  13586. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  13587. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  13588. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  13589. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  13590. } // emit pmt info
  13591. self.trigger('trackinfo', {
  13592. hasAudio: !!audioTrack,
  13593. hasVideo: !!videoTrack
  13594. });
  13595. }
  13596. }); // Re-emit any data coming from the coalesce stream to the outside world
  13597. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  13598. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  13599. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  13600. self.trigger('id3Frame', id3Frame);
  13601. });
  13602. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  13603. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  13604. addPipelineLogRetriggers(this, pipeline);
  13605. }; // hook up the segment streams once track metadata is delivered
  13606. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  13607. var pipeline = this.transmuxPipeline_;
  13608. if (!options.keepOriginalTimestamps) {
  13609. this.baseMediaDecodeTime = baseMediaDecodeTime;
  13610. }
  13611. if (audioTrack) {
  13612. audioTrack.timelineStartInfo.dts = undefined;
  13613. audioTrack.timelineStartInfo.pts = undefined;
  13614. trackDecodeInfo.clearDtsInfo(audioTrack);
  13615. if (pipeline.audioTimestampRolloverStream) {
  13616. pipeline.audioTimestampRolloverStream.discontinuity();
  13617. }
  13618. }
  13619. if (videoTrack) {
  13620. if (pipeline.videoSegmentStream) {
  13621. pipeline.videoSegmentStream.gopCache_ = [];
  13622. }
  13623. videoTrack.timelineStartInfo.dts = undefined;
  13624. videoTrack.timelineStartInfo.pts = undefined;
  13625. trackDecodeInfo.clearDtsInfo(videoTrack);
  13626. pipeline.captionStream.reset();
  13627. }
  13628. if (pipeline.timestampRolloverStream) {
  13629. pipeline.timestampRolloverStream.discontinuity();
  13630. }
  13631. };
  13632. this.setAudioAppendStart = function (timestamp) {
  13633. if (audioTrack) {
  13634. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  13635. }
  13636. };
  13637. this.setRemux = function (val) {
  13638. var pipeline = this.transmuxPipeline_;
  13639. options.remux = val;
  13640. if (pipeline && pipeline.coalesceStream) {
  13641. pipeline.coalesceStream.setRemux(val);
  13642. }
  13643. };
  13644. this.alignGopsWith = function (gopsToAlignWith) {
  13645. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  13646. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  13647. }
  13648. };
  13649. this.getLogTrigger_ = function (key) {
  13650. var self = this;
  13651. return function (event) {
  13652. event.stream = key;
  13653. self.trigger('log', event);
  13654. };
  13655. }; // feed incoming data to the front of the parsing pipeline
  13656. this.push = function (data) {
  13657. if (hasFlushed) {
  13658. var isAac = isLikelyAacData(data);
  13659. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  13660. this.setupAacPipeline();
  13661. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  13662. this.setupTsPipeline();
  13663. }
  13664. hasFlushed = false;
  13665. }
  13666. this.transmuxPipeline_.headOfPipeline.push(data);
  13667. }; // flush any buffered data
  13668. this.flush = function () {
  13669. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  13670. this.transmuxPipeline_.headOfPipeline.flush();
  13671. };
  13672. this.endTimeline = function () {
  13673. this.transmuxPipeline_.headOfPipeline.endTimeline();
  13674. };
  13675. this.reset = function () {
  13676. if (this.transmuxPipeline_.headOfPipeline) {
  13677. this.transmuxPipeline_.headOfPipeline.reset();
  13678. }
  13679. }; // Caption data has to be reset when seeking outside buffered range
  13680. this.resetCaptions = function () {
  13681. if (this.transmuxPipeline_.captionStream) {
  13682. this.transmuxPipeline_.captionStream.reset();
  13683. }
  13684. };
  13685. };
  13686. Transmuxer.prototype = new Stream();
  13687. var transmuxer = {
  13688. Transmuxer: Transmuxer,
  13689. VideoSegmentStream: VideoSegmentStream,
  13690. AudioSegmentStream: AudioSegmentStream,
  13691. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  13692. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  13693. // exported for testing
  13694. generateSegmentTimingInfo: generateSegmentTimingInfo
  13695. };
  13696. /**
  13697. * mux.js
  13698. *
  13699. * Copyright (c) Brightcove
  13700. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13701. */
  13702. var toUnsigned$3 = function (value) {
  13703. return value >>> 0;
  13704. };
  13705. var toHexString$1 = function (value) {
  13706. return ('00' + value.toString(16)).slice(-2);
  13707. };
  13708. var bin = {
  13709. toUnsigned: toUnsigned$3,
  13710. toHexString: toHexString$1
  13711. };
  13712. var parseType$3 = function (buffer) {
  13713. var result = '';
  13714. result += String.fromCharCode(buffer[0]);
  13715. result += String.fromCharCode(buffer[1]);
  13716. result += String.fromCharCode(buffer[2]);
  13717. result += String.fromCharCode(buffer[3]);
  13718. return result;
  13719. };
  13720. var parseType_1 = parseType$3;
  13721. var toUnsigned$2 = bin.toUnsigned;
  13722. var parseType$2 = parseType_1;
  13723. var findBox$2 = function (data, path) {
  13724. var results = [],
  13725. i,
  13726. size,
  13727. type,
  13728. end,
  13729. subresults;
  13730. if (!path.length) {
  13731. // short-circuit the search for empty paths
  13732. return null;
  13733. }
  13734. for (i = 0; i < data.byteLength;) {
  13735. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  13736. type = parseType$2(data.subarray(i + 4, i + 8));
  13737. end = size > 1 ? i + size : data.byteLength;
  13738. if (type === path[0]) {
  13739. if (path.length === 1) {
  13740. // this is the end of the path and we've found the box we were
  13741. // looking for
  13742. results.push(data.subarray(i + 8, end));
  13743. } else {
  13744. // recursively search for the next box along the path
  13745. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  13746. if (subresults.length) {
  13747. results = results.concat(subresults);
  13748. }
  13749. }
  13750. }
  13751. i = end;
  13752. } // we've finished searching all of data
  13753. return results;
  13754. };
  13755. var findBox_1 = findBox$2;
  13756. var toUnsigned$1 = bin.toUnsigned;
  13757. var getUint64$2 = numbers.getUint64;
  13758. var tfdt = function (data) {
  13759. var result = {
  13760. version: data[0],
  13761. flags: new Uint8Array(data.subarray(1, 4))
  13762. };
  13763. if (result.version === 1) {
  13764. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  13765. } else {
  13766. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  13767. }
  13768. return result;
  13769. };
  13770. var parseTfdt$2 = tfdt;
  13771. var parseSampleFlags$1 = function (flags) {
  13772. return {
  13773. isLeading: (flags[0] & 0x0c) >>> 2,
  13774. dependsOn: flags[0] & 0x03,
  13775. isDependedOn: (flags[1] & 0xc0) >>> 6,
  13776. hasRedundancy: (flags[1] & 0x30) >>> 4,
  13777. paddingValue: (flags[1] & 0x0e) >>> 1,
  13778. isNonSyncSample: flags[1] & 0x01,
  13779. degradationPriority: flags[2] << 8 | flags[3]
  13780. };
  13781. };
  13782. var parseSampleFlags_1 = parseSampleFlags$1;
  13783. var parseSampleFlags = parseSampleFlags_1;
  13784. var trun = function (data) {
  13785. var result = {
  13786. version: data[0],
  13787. flags: new Uint8Array(data.subarray(1, 4)),
  13788. samples: []
  13789. },
  13790. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  13791. // Flag interpretation
  13792. dataOffsetPresent = result.flags[2] & 0x01,
  13793. // compare with 2nd byte of 0x1
  13794. firstSampleFlagsPresent = result.flags[2] & 0x04,
  13795. // compare with 2nd byte of 0x4
  13796. sampleDurationPresent = result.flags[1] & 0x01,
  13797. // compare with 2nd byte of 0x100
  13798. sampleSizePresent = result.flags[1] & 0x02,
  13799. // compare with 2nd byte of 0x200
  13800. sampleFlagsPresent = result.flags[1] & 0x04,
  13801. // compare with 2nd byte of 0x400
  13802. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  13803. // compare with 2nd byte of 0x800
  13804. sampleCount = view.getUint32(4),
  13805. offset = 8,
  13806. sample;
  13807. if (dataOffsetPresent) {
  13808. // 32 bit signed integer
  13809. result.dataOffset = view.getInt32(offset);
  13810. offset += 4;
  13811. } // Overrides the flags for the first sample only. The order of
  13812. // optional values will be: duration, size, compositionTimeOffset
  13813. if (firstSampleFlagsPresent && sampleCount) {
  13814. sample = {
  13815. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  13816. };
  13817. offset += 4;
  13818. if (sampleDurationPresent) {
  13819. sample.duration = view.getUint32(offset);
  13820. offset += 4;
  13821. }
  13822. if (sampleSizePresent) {
  13823. sample.size = view.getUint32(offset);
  13824. offset += 4;
  13825. }
  13826. if (sampleCompositionTimeOffsetPresent) {
  13827. if (result.version === 1) {
  13828. sample.compositionTimeOffset = view.getInt32(offset);
  13829. } else {
  13830. sample.compositionTimeOffset = view.getUint32(offset);
  13831. }
  13832. offset += 4;
  13833. }
  13834. result.samples.push(sample);
  13835. sampleCount--;
  13836. }
  13837. while (sampleCount--) {
  13838. sample = {};
  13839. if (sampleDurationPresent) {
  13840. sample.duration = view.getUint32(offset);
  13841. offset += 4;
  13842. }
  13843. if (sampleSizePresent) {
  13844. sample.size = view.getUint32(offset);
  13845. offset += 4;
  13846. }
  13847. if (sampleFlagsPresent) {
  13848. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  13849. offset += 4;
  13850. }
  13851. if (sampleCompositionTimeOffsetPresent) {
  13852. if (result.version === 1) {
  13853. sample.compositionTimeOffset = view.getInt32(offset);
  13854. } else {
  13855. sample.compositionTimeOffset = view.getUint32(offset);
  13856. }
  13857. offset += 4;
  13858. }
  13859. result.samples.push(sample);
  13860. }
  13861. return result;
  13862. };
  13863. var parseTrun$2 = trun;
  13864. var tfhd = function (data) {
  13865. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  13866. result = {
  13867. version: data[0],
  13868. flags: new Uint8Array(data.subarray(1, 4)),
  13869. trackId: view.getUint32(4)
  13870. },
  13871. baseDataOffsetPresent = result.flags[2] & 0x01,
  13872. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  13873. defaultSampleDurationPresent = result.flags[2] & 0x08,
  13874. defaultSampleSizePresent = result.flags[2] & 0x10,
  13875. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  13876. durationIsEmpty = result.flags[0] & 0x010000,
  13877. defaultBaseIsMoof = result.flags[0] & 0x020000,
  13878. i;
  13879. i = 8;
  13880. if (baseDataOffsetPresent) {
  13881. i += 4; // truncate top 4 bytes
  13882. // FIXME: should we read the full 64 bits?
  13883. result.baseDataOffset = view.getUint32(12);
  13884. i += 4;
  13885. }
  13886. if (sampleDescriptionIndexPresent) {
  13887. result.sampleDescriptionIndex = view.getUint32(i);
  13888. i += 4;
  13889. }
  13890. if (defaultSampleDurationPresent) {
  13891. result.defaultSampleDuration = view.getUint32(i);
  13892. i += 4;
  13893. }
  13894. if (defaultSampleSizePresent) {
  13895. result.defaultSampleSize = view.getUint32(i);
  13896. i += 4;
  13897. }
  13898. if (defaultSampleFlagsPresent) {
  13899. result.defaultSampleFlags = view.getUint32(i);
  13900. }
  13901. if (durationIsEmpty) {
  13902. result.durationIsEmpty = true;
  13903. }
  13904. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  13905. result.baseDataOffsetIsMoof = true;
  13906. }
  13907. return result;
  13908. };
  13909. var parseTfhd$2 = tfhd;
  13910. var win;
  13911. if (typeof window !== "undefined") {
  13912. win = window;
  13913. } else if (typeof commonjsGlobal !== "undefined") {
  13914. win = commonjsGlobal;
  13915. } else if (typeof self !== "undefined") {
  13916. win = self;
  13917. } else {
  13918. win = {};
  13919. }
  13920. var window_1 = win;
  13921. /**
  13922. * mux.js
  13923. *
  13924. * Copyright (c) Brightcove
  13925. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13926. *
  13927. * Reads in-band CEA-708 captions out of FMP4 segments.
  13928. * @see https://en.wikipedia.org/wiki/CEA-708
  13929. */
  13930. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  13931. var CaptionStream = captionStream.CaptionStream;
  13932. var findBox$1 = findBox_1;
  13933. var parseTfdt$1 = parseTfdt$2;
  13934. var parseTrun$1 = parseTrun$2;
  13935. var parseTfhd$1 = parseTfhd$2;
  13936. var window$2 = window_1;
  13937. /**
  13938. * Maps an offset in the mdat to a sample based on the the size of the samples.
  13939. * Assumes that `parseSamples` has been called first.
  13940. *
  13941. * @param {Number} offset - The offset into the mdat
  13942. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  13943. * @return {?Object} The matching sample, or null if no match was found.
  13944. *
  13945. * @see ISO-BMFF-12/2015, Section 8.8.8
  13946. **/
  13947. var mapToSample = function (offset, samples) {
  13948. var approximateOffset = offset;
  13949. for (var i = 0; i < samples.length; i++) {
  13950. var sample = samples[i];
  13951. if (approximateOffset < sample.size) {
  13952. return sample;
  13953. }
  13954. approximateOffset -= sample.size;
  13955. }
  13956. return null;
  13957. };
  13958. /**
  13959. * Finds SEI nal units contained in a Media Data Box.
  13960. * Assumes that `parseSamples` has been called first.
  13961. *
  13962. * @param {Uint8Array} avcStream - The bytes of the mdat
  13963. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  13964. * @param {Number} trackId - The trackId of this video track
  13965. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  13966. * The contents of the seiNal should match what is expected by
  13967. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  13968. *
  13969. * @see ISO-BMFF-12/2015, Section 8.1.1
  13970. * @see Rec. ITU-T H.264, 7.3.2.3.1
  13971. **/
  13972. var findSeiNals = function (avcStream, samples, trackId) {
  13973. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  13974. result = {
  13975. logs: [],
  13976. seiNals: []
  13977. },
  13978. seiNal,
  13979. i,
  13980. length,
  13981. lastMatchedSample;
  13982. for (i = 0; i + 4 < avcStream.length; i += length) {
  13983. length = avcView.getUint32(i);
  13984. i += 4; // Bail if this doesn't appear to be an H264 stream
  13985. if (length <= 0) {
  13986. continue;
  13987. }
  13988. switch (avcStream[i] & 0x1F) {
  13989. case 0x06:
  13990. var data = avcStream.subarray(i + 1, i + 1 + length);
  13991. var matchingSample = mapToSample(i, samples);
  13992. seiNal = {
  13993. nalUnitType: 'sei_rbsp',
  13994. size: length,
  13995. data: data,
  13996. escapedRBSP: discardEmulationPreventionBytes(data),
  13997. trackId: trackId
  13998. };
  13999. if (matchingSample) {
  14000. seiNal.pts = matchingSample.pts;
  14001. seiNal.dts = matchingSample.dts;
  14002. lastMatchedSample = matchingSample;
  14003. } else if (lastMatchedSample) {
  14004. // If a matching sample cannot be found, use the last
  14005. // sample's values as they should be as close as possible
  14006. seiNal.pts = lastMatchedSample.pts;
  14007. seiNal.dts = lastMatchedSample.dts;
  14008. } else {
  14009. result.logs.push({
  14010. level: 'warn',
  14011. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  14012. });
  14013. break;
  14014. }
  14015. result.seiNals.push(seiNal);
  14016. break;
  14017. }
  14018. }
  14019. return result;
  14020. };
  14021. /**
  14022. * Parses sample information out of Track Run Boxes and calculates
  14023. * the absolute presentation and decode timestamps of each sample.
  14024. *
  14025. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  14026. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  14027. @see ISO-BMFF-12/2015, Section 8.8.12
  14028. * @param {Object} tfhd - The parsed Track Fragment Header
  14029. * @see inspect.parseTfhd
  14030. * @return {Object[]} the parsed samples
  14031. *
  14032. * @see ISO-BMFF-12/2015, Section 8.8.8
  14033. **/
  14034. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  14035. var currentDts = baseMediaDecodeTime;
  14036. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  14037. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  14038. var trackId = tfhd.trackId;
  14039. var allSamples = [];
  14040. truns.forEach(function (trun) {
  14041. // Note: We currently do not parse the sample table as well
  14042. // as the trun. It's possible some sources will require this.
  14043. // moov > trak > mdia > minf > stbl
  14044. var trackRun = parseTrun$1(trun);
  14045. var samples = trackRun.samples;
  14046. samples.forEach(function (sample) {
  14047. if (sample.duration === undefined) {
  14048. sample.duration = defaultSampleDuration;
  14049. }
  14050. if (sample.size === undefined) {
  14051. sample.size = defaultSampleSize;
  14052. }
  14053. sample.trackId = trackId;
  14054. sample.dts = currentDts;
  14055. if (sample.compositionTimeOffset === undefined) {
  14056. sample.compositionTimeOffset = 0;
  14057. }
  14058. if (typeof currentDts === 'bigint') {
  14059. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  14060. currentDts += window$2.BigInt(sample.duration);
  14061. } else {
  14062. sample.pts = currentDts + sample.compositionTimeOffset;
  14063. currentDts += sample.duration;
  14064. }
  14065. });
  14066. allSamples = allSamples.concat(samples);
  14067. });
  14068. return allSamples;
  14069. };
  14070. /**
  14071. * Parses out caption nals from an FMP4 segment's video tracks.
  14072. *
  14073. * @param {Uint8Array} segment - The bytes of a single segment
  14074. * @param {Number} videoTrackId - The trackId of a video track in the segment
  14075. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  14076. * a list of seiNals found in that track
  14077. **/
  14078. var parseCaptionNals = function (segment, videoTrackId) {
  14079. // To get the samples
  14080. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  14081. var mdats = findBox$1(segment, ['mdat']);
  14082. var captionNals = {};
  14083. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  14084. mdats.forEach(function (mdat, index) {
  14085. var matchingTraf = trafs[index];
  14086. mdatTrafPairs.push({
  14087. mdat: mdat,
  14088. traf: matchingTraf
  14089. });
  14090. });
  14091. mdatTrafPairs.forEach(function (pair) {
  14092. var mdat = pair.mdat;
  14093. var traf = pair.traf;
  14094. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  14095. var headerInfo = parseTfhd$1(tfhd[0]);
  14096. var trackId = headerInfo.trackId;
  14097. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  14098. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  14099. var truns = findBox$1(traf, ['trun']);
  14100. var samples;
  14101. var result; // Only parse video data for the chosen video track
  14102. if (videoTrackId === trackId && truns.length > 0) {
  14103. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  14104. result = findSeiNals(mdat, samples, trackId);
  14105. if (!captionNals[trackId]) {
  14106. captionNals[trackId] = {
  14107. seiNals: [],
  14108. logs: []
  14109. };
  14110. }
  14111. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  14112. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  14113. }
  14114. });
  14115. return captionNals;
  14116. };
  14117. /**
  14118. * Parses out inband captions from an MP4 container and returns
  14119. * caption objects that can be used by WebVTT and the TextTrack API.
  14120. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  14121. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  14122. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  14123. *
  14124. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  14125. * @param {Number} trackId - The id of the video track to parse
  14126. * @param {Number} timescale - The timescale for the video track from the init segment
  14127. *
  14128. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  14129. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  14130. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  14131. * @return {String} parsedCaptions[].text - The visible content of the caption
  14132. **/
  14133. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  14134. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  14135. if (trackId === null) {
  14136. return null;
  14137. }
  14138. captionNals = parseCaptionNals(segment, trackId);
  14139. var trackNals = captionNals[trackId] || {};
  14140. return {
  14141. seiNals: trackNals.seiNals,
  14142. logs: trackNals.logs,
  14143. timescale: timescale
  14144. };
  14145. };
  14146. /**
  14147. * Converts SEI NALUs into captions that can be used by video.js
  14148. **/
  14149. var CaptionParser = function () {
  14150. var isInitialized = false;
  14151. var captionStream; // Stores segments seen before trackId and timescale are set
  14152. var segmentCache; // Stores video track ID of the track being parsed
  14153. var trackId; // Stores the timescale of the track being parsed
  14154. var timescale; // Stores captions parsed so far
  14155. var parsedCaptions; // Stores whether we are receiving partial data or not
  14156. var parsingPartial;
  14157. /**
  14158. * A method to indicate whether a CaptionParser has been initalized
  14159. * @returns {Boolean}
  14160. **/
  14161. this.isInitialized = function () {
  14162. return isInitialized;
  14163. };
  14164. /**
  14165. * Initializes the underlying CaptionStream, SEI NAL parsing
  14166. * and management, and caption collection
  14167. **/
  14168. this.init = function (options) {
  14169. captionStream = new CaptionStream();
  14170. isInitialized = true;
  14171. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  14172. captionStream.on('data', function (event) {
  14173. // Convert to seconds in the source's timescale
  14174. event.startTime = event.startPts / timescale;
  14175. event.endTime = event.endPts / timescale;
  14176. parsedCaptions.captions.push(event);
  14177. parsedCaptions.captionStreams[event.stream] = true;
  14178. });
  14179. captionStream.on('log', function (log) {
  14180. parsedCaptions.logs.push(log);
  14181. });
  14182. };
  14183. /**
  14184. * Determines if a new video track will be selected
  14185. * or if the timescale changed
  14186. * @return {Boolean}
  14187. **/
  14188. this.isNewInit = function (videoTrackIds, timescales) {
  14189. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  14190. return false;
  14191. }
  14192. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  14193. };
  14194. /**
  14195. * Parses out SEI captions and interacts with underlying
  14196. * CaptionStream to return dispatched captions
  14197. *
  14198. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  14199. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  14200. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  14201. * @see parseEmbeddedCaptions
  14202. * @see m2ts/caption-stream.js
  14203. **/
  14204. this.parse = function (segment, videoTrackIds, timescales) {
  14205. var parsedData;
  14206. if (!this.isInitialized()) {
  14207. return null; // This is not likely to be a video segment
  14208. } else if (!videoTrackIds || !timescales) {
  14209. return null;
  14210. } else if (this.isNewInit(videoTrackIds, timescales)) {
  14211. // Use the first video track only as there is no
  14212. // mechanism to switch to other video tracks
  14213. trackId = videoTrackIds[0];
  14214. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  14215. // data until we have one.
  14216. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  14217. } else if (trackId === null || !timescale) {
  14218. segmentCache.push(segment);
  14219. return null;
  14220. } // Now that a timescale and trackId is set, parse cached segments
  14221. while (segmentCache.length > 0) {
  14222. var cachedSegment = segmentCache.shift();
  14223. this.parse(cachedSegment, videoTrackIds, timescales);
  14224. }
  14225. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  14226. if (parsedData && parsedData.logs) {
  14227. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  14228. }
  14229. if (parsedData === null || !parsedData.seiNals) {
  14230. if (parsedCaptions.logs.length) {
  14231. return {
  14232. logs: parsedCaptions.logs,
  14233. captions: [],
  14234. captionStreams: []
  14235. };
  14236. }
  14237. return null;
  14238. }
  14239. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  14240. this.flushStream();
  14241. return parsedCaptions;
  14242. };
  14243. /**
  14244. * Pushes SEI NALUs onto CaptionStream
  14245. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  14246. * Assumes that `parseCaptionNals` has been called first
  14247. * @see m2ts/caption-stream.js
  14248. **/
  14249. this.pushNals = function (nals) {
  14250. if (!this.isInitialized() || !nals || nals.length === 0) {
  14251. return null;
  14252. }
  14253. nals.forEach(function (nal) {
  14254. captionStream.push(nal);
  14255. });
  14256. };
  14257. /**
  14258. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  14259. * @see m2ts/caption-stream.js
  14260. **/
  14261. this.flushStream = function () {
  14262. if (!this.isInitialized()) {
  14263. return null;
  14264. }
  14265. if (!parsingPartial) {
  14266. captionStream.flush();
  14267. } else {
  14268. captionStream.partialFlush();
  14269. }
  14270. };
  14271. /**
  14272. * Reset caption buckets for new data
  14273. **/
  14274. this.clearParsedCaptions = function () {
  14275. parsedCaptions.captions = [];
  14276. parsedCaptions.captionStreams = {};
  14277. parsedCaptions.logs = [];
  14278. };
  14279. /**
  14280. * Resets underlying CaptionStream
  14281. * @see m2ts/caption-stream.js
  14282. **/
  14283. this.resetCaptionStream = function () {
  14284. if (!this.isInitialized()) {
  14285. return null;
  14286. }
  14287. captionStream.reset();
  14288. };
  14289. /**
  14290. * Convenience method to clear all captions flushed from the
  14291. * CaptionStream and still being parsed
  14292. * @see m2ts/caption-stream.js
  14293. **/
  14294. this.clearAllCaptions = function () {
  14295. this.clearParsedCaptions();
  14296. this.resetCaptionStream();
  14297. };
  14298. /**
  14299. * Reset caption parser
  14300. **/
  14301. this.reset = function () {
  14302. segmentCache = [];
  14303. trackId = null;
  14304. timescale = null;
  14305. if (!parsedCaptions) {
  14306. parsedCaptions = {
  14307. captions: [],
  14308. // CC1, CC2, CC3, CC4
  14309. captionStreams: {},
  14310. logs: []
  14311. };
  14312. } else {
  14313. this.clearParsedCaptions();
  14314. }
  14315. this.resetCaptionStream();
  14316. };
  14317. this.reset();
  14318. };
  14319. var captionParser = CaptionParser;
  14320. /**
  14321. * Returns the first string in the data array ending with a null char '\0'
  14322. * @param {UInt8} data
  14323. * @returns the string with the null char
  14324. */
  14325. var uint8ToCString$1 = function (data) {
  14326. var index = 0;
  14327. var curChar = String.fromCharCode(data[index]);
  14328. var retString = '';
  14329. while (curChar !== '\0') {
  14330. retString += curChar;
  14331. index++;
  14332. curChar = String.fromCharCode(data[index]);
  14333. } // Add nullChar
  14334. retString += curChar;
  14335. return retString;
  14336. };
  14337. var string = {
  14338. uint8ToCString: uint8ToCString$1
  14339. };
  14340. var uint8ToCString = string.uint8ToCString;
  14341. var getUint64$1 = numbers.getUint64;
  14342. /**
  14343. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  14344. * References:
  14345. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  14346. * https://aomediacodec.github.io/id3-emsg/
  14347. *
  14348. * Takes emsg box data as a uint8 array and returns a emsg box object
  14349. * @param {UInt8Array} boxData data from emsg box
  14350. * @returns A parsed emsg box object
  14351. */
  14352. var parseEmsgBox = function (boxData) {
  14353. // version + flags
  14354. var offset = 4;
  14355. var version = boxData[0];
  14356. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  14357. if (version === 0) {
  14358. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  14359. offset += scheme_id_uri.length;
  14360. value = uint8ToCString(boxData.subarray(offset));
  14361. offset += value.length;
  14362. var dv = new DataView(boxData.buffer);
  14363. timescale = dv.getUint32(offset);
  14364. offset += 4;
  14365. presentation_time_delta = dv.getUint32(offset);
  14366. offset += 4;
  14367. event_duration = dv.getUint32(offset);
  14368. offset += 4;
  14369. id = dv.getUint32(offset);
  14370. offset += 4;
  14371. } else if (version === 1) {
  14372. var dv = new DataView(boxData.buffer);
  14373. timescale = dv.getUint32(offset);
  14374. offset += 4;
  14375. presentation_time = getUint64$1(boxData.subarray(offset));
  14376. offset += 8;
  14377. event_duration = dv.getUint32(offset);
  14378. offset += 4;
  14379. id = dv.getUint32(offset);
  14380. offset += 4;
  14381. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  14382. offset += scheme_id_uri.length;
  14383. value = uint8ToCString(boxData.subarray(offset));
  14384. offset += value.length;
  14385. }
  14386. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  14387. var emsgBox = {
  14388. scheme_id_uri,
  14389. value,
  14390. // if timescale is undefined or 0 set to 1
  14391. timescale: timescale ? timescale : 1,
  14392. presentation_time,
  14393. presentation_time_delta,
  14394. event_duration,
  14395. id,
  14396. message_data
  14397. };
  14398. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  14399. };
  14400. /**
  14401. * Scales a presentation time or time delta with an offset with a provided timescale
  14402. * @param {number} presentationTime
  14403. * @param {number} timescale
  14404. * @param {number} timeDelta
  14405. * @param {number} offset
  14406. * @returns the scaled time as a number
  14407. */
  14408. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  14409. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  14410. };
  14411. /**
  14412. * Checks the emsg box data for validity based on the version
  14413. * @param {number} version of the emsg box to validate
  14414. * @param {Object} emsg the emsg data to validate
  14415. * @returns if the box is valid as a boolean
  14416. */
  14417. var isValidEmsgBox = function (version, emsg) {
  14418. var hasScheme = emsg.scheme_id_uri !== '\0';
  14419. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  14420. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  14421. return !(version > 1) && isValidV0Box || isValidV1Box;
  14422. }; // Utility function to check if an object is defined
  14423. var isDefined = function (data) {
  14424. return data !== undefined || data !== null;
  14425. };
  14426. var emsg$1 = {
  14427. parseEmsgBox: parseEmsgBox,
  14428. scaleTime: scaleTime
  14429. };
  14430. /**
  14431. * mux.js
  14432. *
  14433. * Copyright (c) Brightcove
  14434. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14435. *
  14436. * Utilities to detect basic properties and metadata about MP4s.
  14437. */
  14438. var toUnsigned = bin.toUnsigned;
  14439. var toHexString = bin.toHexString;
  14440. var findBox = findBox_1;
  14441. var parseType$1 = parseType_1;
  14442. var emsg = emsg$1;
  14443. var parseTfhd = parseTfhd$2;
  14444. var parseTrun = parseTrun$2;
  14445. var parseTfdt = parseTfdt$2;
  14446. var getUint64 = numbers.getUint64;
  14447. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  14448. var window$1 = window_1;
  14449. var parseId3Frames = parseId3.parseId3Frames;
  14450. /**
  14451. * Parses an MP4 initialization segment and extracts the timescale
  14452. * values for any declared tracks. Timescale values indicate the
  14453. * number of clock ticks per second to assume for time-based values
  14454. * elsewhere in the MP4.
  14455. *
  14456. * To determine the start time of an MP4, you need two pieces of
  14457. * information: the timescale unit and the earliest base media decode
  14458. * time. Multiple timescales can be specified within an MP4 but the
  14459. * base media decode time is always expressed in the timescale from
  14460. * the media header box for the track:
  14461. * ```
  14462. * moov > trak > mdia > mdhd.timescale
  14463. * ```
  14464. * @param init {Uint8Array} the bytes of the init segment
  14465. * @return {object} a hash of track ids to timescale values or null if
  14466. * the init segment is malformed.
  14467. */
  14468. timescale = function (init) {
  14469. var result = {},
  14470. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  14471. return traks.reduce(function (result, trak) {
  14472. var tkhd, version, index, id, mdhd;
  14473. tkhd = findBox(trak, ['tkhd'])[0];
  14474. if (!tkhd) {
  14475. return null;
  14476. }
  14477. version = tkhd[0];
  14478. index = version === 0 ? 12 : 20;
  14479. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  14480. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  14481. if (!mdhd) {
  14482. return null;
  14483. }
  14484. version = mdhd[0];
  14485. index = version === 0 ? 12 : 20;
  14486. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  14487. return result;
  14488. }, result);
  14489. };
  14490. /**
  14491. * Determine the base media decode start time, in seconds, for an MP4
  14492. * fragment. If multiple fragments are specified, the earliest time is
  14493. * returned.
  14494. *
  14495. * The base media decode time can be parsed from track fragment
  14496. * metadata:
  14497. * ```
  14498. * moof > traf > tfdt.baseMediaDecodeTime
  14499. * ```
  14500. * It requires the timescale value from the mdhd to interpret.
  14501. *
  14502. * @param timescale {object} a hash of track ids to timescale values.
  14503. * @return {number} the earliest base media decode start time for the
  14504. * fragment, in seconds
  14505. */
  14506. startTime = function (timescale, fragment) {
  14507. var trafs; // we need info from two childrend of each track fragment box
  14508. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  14509. var lowestTime = trafs.reduce(function (acc, traf) {
  14510. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  14511. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  14512. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  14513. var tfdt = findBox(traf, ['tfdt'])[0];
  14514. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  14515. var baseTime; // version 1 is 64 bit
  14516. if (tfdt[0] === 1) {
  14517. baseTime = getUint64(tfdt.subarray(4, 12));
  14518. } else {
  14519. baseTime = dv.getUint32(4);
  14520. } // convert base time to seconds if it is a valid number.
  14521. let seconds;
  14522. if (typeof baseTime === 'bigint') {
  14523. seconds = baseTime / window$1.BigInt(scale);
  14524. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  14525. seconds = baseTime / scale;
  14526. }
  14527. if (seconds < Number.MAX_SAFE_INTEGER) {
  14528. seconds = Number(seconds);
  14529. }
  14530. if (seconds < acc) {
  14531. acc = seconds;
  14532. }
  14533. return acc;
  14534. }, Infinity);
  14535. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  14536. };
  14537. /**
  14538. * Determine the composition start, in seconds, for an MP4
  14539. * fragment.
  14540. *
  14541. * The composition start time of a fragment can be calculated using the base
  14542. * media decode time, composition time offset, and timescale, as follows:
  14543. *
  14544. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  14545. *
  14546. * All of the aforementioned information is contained within a media fragment's
  14547. * `traf` box, except for timescale info, which comes from the initialization
  14548. * segment, so a track id (also contained within a `traf`) is also necessary to
  14549. * associate it with a timescale
  14550. *
  14551. *
  14552. * @param timescales {object} - a hash of track ids to timescale values.
  14553. * @param fragment {Unit8Array} - the bytes of a media segment
  14554. * @return {number} the composition start time for the fragment, in seconds
  14555. **/
  14556. compositionStartTime = function (timescales, fragment) {
  14557. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  14558. var baseMediaDecodeTime = 0;
  14559. var compositionTimeOffset = 0;
  14560. var trackId;
  14561. if (trafBoxes && trafBoxes.length) {
  14562. // The spec states that track run samples contained within a `traf` box are contiguous, but
  14563. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  14564. // We will assume that they are, so we only need the first to calculate start time.
  14565. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  14566. var trun = findBox(trafBoxes[0], ['trun'])[0];
  14567. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  14568. if (tfhd) {
  14569. var parsedTfhd = parseTfhd(tfhd);
  14570. trackId = parsedTfhd.trackId;
  14571. }
  14572. if (tfdt) {
  14573. var parsedTfdt = parseTfdt(tfdt);
  14574. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  14575. }
  14576. if (trun) {
  14577. var parsedTrun = parseTrun(trun);
  14578. if (parsedTrun.samples && parsedTrun.samples.length) {
  14579. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  14580. }
  14581. }
  14582. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  14583. // specified.
  14584. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  14585. if (typeof baseMediaDecodeTime === 'bigint') {
  14586. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  14587. timescale = window$1.BigInt(timescale);
  14588. }
  14589. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  14590. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  14591. result = Number(result);
  14592. }
  14593. return result;
  14594. };
  14595. /**
  14596. * Find the trackIds of the video tracks in this source.
  14597. * Found by parsing the Handler Reference and Track Header Boxes:
  14598. * moov > trak > mdia > hdlr
  14599. * moov > trak > tkhd
  14600. *
  14601. * @param {Uint8Array} init - The bytes of the init segment for this source
  14602. * @return {Number[]} A list of trackIds
  14603. *
  14604. * @see ISO-BMFF-12/2015, Section 8.4.3
  14605. **/
  14606. getVideoTrackIds = function (init) {
  14607. var traks = findBox(init, ['moov', 'trak']);
  14608. var videoTrackIds = [];
  14609. traks.forEach(function (trak) {
  14610. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  14611. var tkhds = findBox(trak, ['tkhd']);
  14612. hdlrs.forEach(function (hdlr, index) {
  14613. var handlerType = parseType$1(hdlr.subarray(8, 12));
  14614. var tkhd = tkhds[index];
  14615. var view;
  14616. var version;
  14617. var trackId;
  14618. if (handlerType === 'vide') {
  14619. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  14620. version = view.getUint8(0);
  14621. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  14622. videoTrackIds.push(trackId);
  14623. }
  14624. });
  14625. });
  14626. return videoTrackIds;
  14627. };
  14628. getTimescaleFromMediaHeader = function (mdhd) {
  14629. // mdhd is a FullBox, meaning it will have its own version as the first byte
  14630. var version = mdhd[0];
  14631. var index = version === 0 ? 12 : 20;
  14632. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  14633. };
  14634. /**
  14635. * Get all the video, audio, and hint tracks from a non fragmented
  14636. * mp4 segment
  14637. */
  14638. getTracks = function (init) {
  14639. var traks = findBox(init, ['moov', 'trak']);
  14640. var tracks = [];
  14641. traks.forEach(function (trak) {
  14642. var track = {};
  14643. var tkhd = findBox(trak, ['tkhd'])[0];
  14644. var view, tkhdVersion; // id
  14645. if (tkhd) {
  14646. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  14647. tkhdVersion = view.getUint8(0);
  14648. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  14649. }
  14650. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  14651. if (hdlr) {
  14652. var type = parseType$1(hdlr.subarray(8, 12));
  14653. if (type === 'vide') {
  14654. track.type = 'video';
  14655. } else if (type === 'soun') {
  14656. track.type = 'audio';
  14657. } else {
  14658. track.type = type;
  14659. }
  14660. } // codec
  14661. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  14662. if (stsd) {
  14663. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  14664. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  14665. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  14666. var codecConfig, codecConfigType;
  14667. if (codecBox) {
  14668. // https://tools.ietf.org/html/rfc6381#section-3.3
  14669. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  14670. // we don't need anything but the "config" parameter of the
  14671. // avc1 codecBox
  14672. codecConfig = codecBox.subarray(78);
  14673. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  14674. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  14675. track.codec += '.'; // left padded with zeroes for single digit hex
  14676. // profile idc
  14677. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  14678. track.codec += toHexString(codecConfig[10]); // level idc
  14679. track.codec += toHexString(codecConfig[11]);
  14680. } else {
  14681. // TODO: show a warning that we couldn't parse the codec
  14682. // and are using the default
  14683. track.codec = 'avc1.4d400d';
  14684. }
  14685. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  14686. // we do not need anything but the streamDescriptor of the mp4a codecBox
  14687. codecConfig = codecBox.subarray(28);
  14688. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  14689. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  14690. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  14691. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  14692. } else {
  14693. // TODO: show a warning that we couldn't parse the codec
  14694. // and are using the default
  14695. track.codec = 'mp4a.40.2';
  14696. }
  14697. } else {
  14698. // flac, opus, etc
  14699. track.codec = track.codec.toLowerCase();
  14700. }
  14701. }
  14702. }
  14703. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  14704. if (mdhd) {
  14705. track.timescale = getTimescaleFromMediaHeader(mdhd);
  14706. }
  14707. tracks.push(track);
  14708. });
  14709. return tracks;
  14710. };
  14711. /**
  14712. * Returns an array of emsg ID3 data from the provided segmentData.
  14713. * An offset can also be provided as the Latest Arrival Time to calculate
  14714. * the Event Start Time of v0 EMSG boxes.
  14715. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  14716. *
  14717. * @param {Uint8Array} segmentData the segment byte array.
  14718. * @param {number} offset the segment start time or Latest Arrival Time,
  14719. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  14720. */
  14721. getEmsgID3 = function (segmentData, offset = 0) {
  14722. var emsgBoxes = findBox(segmentData, ['emsg']);
  14723. return emsgBoxes.map(data => {
  14724. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  14725. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  14726. return {
  14727. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  14728. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  14729. frames: parsedId3Frames
  14730. };
  14731. });
  14732. };
  14733. var probe$2 = {
  14734. // export mp4 inspector's findBox and parseType for backwards compatibility
  14735. findBox: findBox,
  14736. parseType: parseType$1,
  14737. timescale: timescale,
  14738. startTime: startTime,
  14739. compositionStartTime: compositionStartTime,
  14740. videoTrackIds: getVideoTrackIds,
  14741. tracks: getTracks,
  14742. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  14743. getEmsgID3: getEmsgID3
  14744. };
  14745. /**
  14746. * mux.js
  14747. *
  14748. * Copyright (c) Brightcove
  14749. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14750. *
  14751. * Utilities to detect basic properties and metadata about TS Segments.
  14752. */
  14753. var StreamTypes$1 = streamTypes;
  14754. var parsePid = function (packet) {
  14755. var pid = packet[1] & 0x1f;
  14756. pid <<= 8;
  14757. pid |= packet[2];
  14758. return pid;
  14759. };
  14760. var parsePayloadUnitStartIndicator = function (packet) {
  14761. return !!(packet[1] & 0x40);
  14762. };
  14763. var parseAdaptionField = function (packet) {
  14764. var offset = 0; // if an adaption field is present, its length is specified by the
  14765. // fifth byte of the TS packet header. The adaptation field is
  14766. // used to add stuffing to PES packets that don't fill a complete
  14767. // TS packet, and to specify some forms of timing and control data
  14768. // that we do not currently use.
  14769. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  14770. offset += packet[4] + 1;
  14771. }
  14772. return offset;
  14773. };
  14774. var parseType = function (packet, pmtPid) {
  14775. var pid = parsePid(packet);
  14776. if (pid === 0) {
  14777. return 'pat';
  14778. } else if (pid === pmtPid) {
  14779. return 'pmt';
  14780. } else if (pmtPid) {
  14781. return 'pes';
  14782. }
  14783. return null;
  14784. };
  14785. var parsePat = function (packet) {
  14786. var pusi = parsePayloadUnitStartIndicator(packet);
  14787. var offset = 4 + parseAdaptionField(packet);
  14788. if (pusi) {
  14789. offset += packet[offset] + 1;
  14790. }
  14791. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  14792. };
  14793. var parsePmt = function (packet) {
  14794. var programMapTable = {};
  14795. var pusi = parsePayloadUnitStartIndicator(packet);
  14796. var payloadOffset = 4 + parseAdaptionField(packet);
  14797. if (pusi) {
  14798. payloadOffset += packet[payloadOffset] + 1;
  14799. } // PMTs can be sent ahead of the time when they should actually
  14800. // take effect. We don't believe this should ever be the case
  14801. // for HLS but we'll ignore "forward" PMT declarations if we see
  14802. // them. Future PMT declarations have the current_next_indicator
  14803. // set to zero.
  14804. if (!(packet[payloadOffset + 5] & 0x01)) {
  14805. return;
  14806. }
  14807. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  14808. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  14809. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  14810. // long the program info descriptors are
  14811. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  14812. var offset = 12 + programInfoLength;
  14813. while (offset < tableEnd) {
  14814. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  14815. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  14816. // skip past the elementary stream descriptors, if present
  14817. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  14818. }
  14819. return programMapTable;
  14820. };
  14821. var parsePesType = function (packet, programMapTable) {
  14822. var pid = parsePid(packet);
  14823. var type = programMapTable[pid];
  14824. switch (type) {
  14825. case StreamTypes$1.H264_STREAM_TYPE:
  14826. return 'video';
  14827. case StreamTypes$1.ADTS_STREAM_TYPE:
  14828. return 'audio';
  14829. case StreamTypes$1.METADATA_STREAM_TYPE:
  14830. return 'timed-metadata';
  14831. default:
  14832. return null;
  14833. }
  14834. };
  14835. var parsePesTime = function (packet) {
  14836. var pusi = parsePayloadUnitStartIndicator(packet);
  14837. if (!pusi) {
  14838. return null;
  14839. }
  14840. var offset = 4 + parseAdaptionField(packet);
  14841. if (offset >= packet.byteLength) {
  14842. // From the H 222.0 MPEG-TS spec
  14843. // "For transport stream packets carrying PES packets, stuffing is needed when there
  14844. // is insufficient PES packet data to completely fill the transport stream packet
  14845. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  14846. // the sum of the lengths of the data elements in it, so that the payload bytes
  14847. // remaining after the adaptation field exactly accommodates the available PES packet
  14848. // data."
  14849. //
  14850. // If the offset is >= the length of the packet, then the packet contains no data
  14851. // and instead is just adaption field stuffing bytes
  14852. return null;
  14853. }
  14854. var pes = null;
  14855. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  14856. // and a DTS value. Determine what combination of values is
  14857. // available to work with.
  14858. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  14859. // performs all bitwise operations on 32-bit integers but javascript
  14860. // supports a much greater range (52-bits) of integer using standard
  14861. // mathematical operations.
  14862. // We construct a 31-bit value using bitwise operators over the 31
  14863. // most significant bits and then multiply by 4 (equal to a left-shift
  14864. // of 2) before we add the final 2 least significant bits of the
  14865. // timestamp (equal to an OR.)
  14866. if (ptsDtsFlags & 0xC0) {
  14867. pes = {}; // the PTS and DTS are not written out directly. For information
  14868. // on how they are encoded, see
  14869. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  14870. pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
  14871. pes.pts *= 4; // Left shift by 2
  14872. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  14873. pes.dts = pes.pts;
  14874. if (ptsDtsFlags & 0x40) {
  14875. pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
  14876. pes.dts *= 4; // Left shift by 2
  14877. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  14878. }
  14879. }
  14880. return pes;
  14881. };
  14882. var parseNalUnitType = function (type) {
  14883. switch (type) {
  14884. case 0x05:
  14885. return 'slice_layer_without_partitioning_rbsp_idr';
  14886. case 0x06:
  14887. return 'sei_rbsp';
  14888. case 0x07:
  14889. return 'seq_parameter_set_rbsp';
  14890. case 0x08:
  14891. return 'pic_parameter_set_rbsp';
  14892. case 0x09:
  14893. return 'access_unit_delimiter_rbsp';
  14894. default:
  14895. return null;
  14896. }
  14897. };
  14898. var videoPacketContainsKeyFrame = function (packet) {
  14899. var offset = 4 + parseAdaptionField(packet);
  14900. var frameBuffer = packet.subarray(offset);
  14901. var frameI = 0;
  14902. var frameSyncPoint = 0;
  14903. var foundKeyFrame = false;
  14904. var nalType; // advance the sync point to a NAL start, if necessary
  14905. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  14906. if (frameBuffer[frameSyncPoint + 2] === 1) {
  14907. // the sync point is properly aligned
  14908. frameI = frameSyncPoint + 5;
  14909. break;
  14910. }
  14911. }
  14912. while (frameI < frameBuffer.byteLength) {
  14913. // look at the current byte to determine if we've hit the end of
  14914. // a NAL unit boundary
  14915. switch (frameBuffer[frameI]) {
  14916. case 0:
  14917. // skip past non-sync sequences
  14918. if (frameBuffer[frameI - 1] !== 0) {
  14919. frameI += 2;
  14920. break;
  14921. } else if (frameBuffer[frameI - 2] !== 0) {
  14922. frameI++;
  14923. break;
  14924. }
  14925. if (frameSyncPoint + 3 !== frameI - 2) {
  14926. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  14927. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  14928. foundKeyFrame = true;
  14929. }
  14930. } // drop trailing zeroes
  14931. do {
  14932. frameI++;
  14933. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  14934. frameSyncPoint = frameI - 2;
  14935. frameI += 3;
  14936. break;
  14937. case 1:
  14938. // skip past non-sync sequences
  14939. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  14940. frameI += 3;
  14941. break;
  14942. }
  14943. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  14944. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  14945. foundKeyFrame = true;
  14946. }
  14947. frameSyncPoint = frameI - 2;
  14948. frameI += 3;
  14949. break;
  14950. default:
  14951. // the current byte isn't a one or zero, so it cannot be part
  14952. // of a sync sequence
  14953. frameI += 3;
  14954. break;
  14955. }
  14956. }
  14957. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  14958. frameI -= frameSyncPoint;
  14959. frameSyncPoint = 0; // parse the final nal
  14960. if (frameBuffer && frameBuffer.byteLength > 3) {
  14961. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  14962. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  14963. foundKeyFrame = true;
  14964. }
  14965. }
  14966. return foundKeyFrame;
  14967. };
  14968. var probe$1 = {
  14969. parseType: parseType,
  14970. parsePat: parsePat,
  14971. parsePmt: parsePmt,
  14972. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  14973. parsePesType: parsePesType,
  14974. parsePesTime: parsePesTime,
  14975. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  14976. };
  14977. /**
  14978. * mux.js
  14979. *
  14980. * Copyright (c) Brightcove
  14981. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14982. *
  14983. * Parse mpeg2 transport stream packets to extract basic timing information
  14984. */
  14985. var StreamTypes = streamTypes;
  14986. var handleRollover = timestampRolloverStream.handleRollover;
  14987. var probe = {};
  14988. probe.ts = probe$1;
  14989. probe.aac = utils;
  14990. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  14991. var MP2T_PACKET_LENGTH = 188,
  14992. // bytes
  14993. SYNC_BYTE = 0x47;
  14994. /**
  14995. * walks through segment data looking for pat and pmt packets to parse out
  14996. * program map table information
  14997. */
  14998. var parsePsi_ = function (bytes, pmt) {
  14999. var startIndex = 0,
  15000. endIndex = MP2T_PACKET_LENGTH,
  15001. packet,
  15002. type;
  15003. while (endIndex < bytes.byteLength) {
  15004. // Look for a pair of start and end sync bytes in the data..
  15005. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15006. // We found a packet
  15007. packet = bytes.subarray(startIndex, endIndex);
  15008. type = probe.ts.parseType(packet, pmt.pid);
  15009. switch (type) {
  15010. case 'pat':
  15011. pmt.pid = probe.ts.parsePat(packet);
  15012. break;
  15013. case 'pmt':
  15014. var table = probe.ts.parsePmt(packet);
  15015. pmt.table = pmt.table || {};
  15016. Object.keys(table).forEach(function (key) {
  15017. pmt.table[key] = table[key];
  15018. });
  15019. break;
  15020. }
  15021. startIndex += MP2T_PACKET_LENGTH;
  15022. endIndex += MP2T_PACKET_LENGTH;
  15023. continue;
  15024. } // If we get here, we have somehow become de-synchronized and we need to step
  15025. // forward one byte at a time until we find a pair of sync bytes that denote
  15026. // a packet
  15027. startIndex++;
  15028. endIndex++;
  15029. }
  15030. };
  15031. /**
  15032. * walks through the segment data from the start and end to get timing information
  15033. * for the first and last audio pes packets
  15034. */
  15035. var parseAudioPes_ = function (bytes, pmt, result) {
  15036. var startIndex = 0,
  15037. endIndex = MP2T_PACKET_LENGTH,
  15038. packet,
  15039. type,
  15040. pesType,
  15041. pusi,
  15042. parsed;
  15043. var endLoop = false; // Start walking from start of segment to get first audio packet
  15044. while (endIndex <= bytes.byteLength) {
  15045. // Look for a pair of start and end sync bytes in the data..
  15046. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15047. // We found a packet
  15048. packet = bytes.subarray(startIndex, endIndex);
  15049. type = probe.ts.parseType(packet, pmt.pid);
  15050. switch (type) {
  15051. case 'pes':
  15052. pesType = probe.ts.parsePesType(packet, pmt.table);
  15053. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15054. if (pesType === 'audio' && pusi) {
  15055. parsed = probe.ts.parsePesTime(packet);
  15056. if (parsed) {
  15057. parsed.type = 'audio';
  15058. result.audio.push(parsed);
  15059. endLoop = true;
  15060. }
  15061. }
  15062. break;
  15063. }
  15064. if (endLoop) {
  15065. break;
  15066. }
  15067. startIndex += MP2T_PACKET_LENGTH;
  15068. endIndex += MP2T_PACKET_LENGTH;
  15069. continue;
  15070. } // If we get here, we have somehow become de-synchronized and we need to step
  15071. // forward one byte at a time until we find a pair of sync bytes that denote
  15072. // a packet
  15073. startIndex++;
  15074. endIndex++;
  15075. } // Start walking from end of segment to get last audio packet
  15076. endIndex = bytes.byteLength;
  15077. startIndex = endIndex - MP2T_PACKET_LENGTH;
  15078. endLoop = false;
  15079. while (startIndex >= 0) {
  15080. // Look for a pair of start and end sync bytes in the data..
  15081. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15082. // We found a packet
  15083. packet = bytes.subarray(startIndex, endIndex);
  15084. type = probe.ts.parseType(packet, pmt.pid);
  15085. switch (type) {
  15086. case 'pes':
  15087. pesType = probe.ts.parsePesType(packet, pmt.table);
  15088. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15089. if (pesType === 'audio' && pusi) {
  15090. parsed = probe.ts.parsePesTime(packet);
  15091. if (parsed) {
  15092. parsed.type = 'audio';
  15093. result.audio.push(parsed);
  15094. endLoop = true;
  15095. }
  15096. }
  15097. break;
  15098. }
  15099. if (endLoop) {
  15100. break;
  15101. }
  15102. startIndex -= MP2T_PACKET_LENGTH;
  15103. endIndex -= MP2T_PACKET_LENGTH;
  15104. continue;
  15105. } // If we get here, we have somehow become de-synchronized and we need to step
  15106. // forward one byte at a time until we find a pair of sync bytes that denote
  15107. // a packet
  15108. startIndex--;
  15109. endIndex--;
  15110. }
  15111. };
  15112. /**
  15113. * walks through the segment data from the start and end to get timing information
  15114. * for the first and last video pes packets as well as timing information for the first
  15115. * key frame.
  15116. */
  15117. var parseVideoPes_ = function (bytes, pmt, result) {
  15118. var startIndex = 0,
  15119. endIndex = MP2T_PACKET_LENGTH,
  15120. packet,
  15121. type,
  15122. pesType,
  15123. pusi,
  15124. parsed,
  15125. frame,
  15126. i,
  15127. pes;
  15128. var endLoop = false;
  15129. var currentFrame = {
  15130. data: [],
  15131. size: 0
  15132. }; // Start walking from start of segment to get first video packet
  15133. while (endIndex < bytes.byteLength) {
  15134. // Look for a pair of start and end sync bytes in the data..
  15135. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15136. // We found a packet
  15137. packet = bytes.subarray(startIndex, endIndex);
  15138. type = probe.ts.parseType(packet, pmt.pid);
  15139. switch (type) {
  15140. case 'pes':
  15141. pesType = probe.ts.parsePesType(packet, pmt.table);
  15142. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15143. if (pesType === 'video') {
  15144. if (pusi && !endLoop) {
  15145. parsed = probe.ts.parsePesTime(packet);
  15146. if (parsed) {
  15147. parsed.type = 'video';
  15148. result.video.push(parsed);
  15149. endLoop = true;
  15150. }
  15151. }
  15152. if (!result.firstKeyFrame) {
  15153. if (pusi) {
  15154. if (currentFrame.size !== 0) {
  15155. frame = new Uint8Array(currentFrame.size);
  15156. i = 0;
  15157. while (currentFrame.data.length) {
  15158. pes = currentFrame.data.shift();
  15159. frame.set(pes, i);
  15160. i += pes.byteLength;
  15161. }
  15162. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  15163. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  15164. // the keyframe seems to work fine with HLS playback
  15165. // and definitely preferable to a crash with TypeError...
  15166. if (firstKeyFrame) {
  15167. result.firstKeyFrame = firstKeyFrame;
  15168. result.firstKeyFrame.type = 'video';
  15169. } else {
  15170. // eslint-disable-next-line
  15171. console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
  15172. }
  15173. }
  15174. currentFrame.size = 0;
  15175. }
  15176. }
  15177. currentFrame.data.push(packet);
  15178. currentFrame.size += packet.byteLength;
  15179. }
  15180. }
  15181. break;
  15182. }
  15183. if (endLoop && result.firstKeyFrame) {
  15184. break;
  15185. }
  15186. startIndex += MP2T_PACKET_LENGTH;
  15187. endIndex += MP2T_PACKET_LENGTH;
  15188. continue;
  15189. } // If we get here, we have somehow become de-synchronized and we need to step
  15190. // forward one byte at a time until we find a pair of sync bytes that denote
  15191. // a packet
  15192. startIndex++;
  15193. endIndex++;
  15194. } // Start walking from end of segment to get last video packet
  15195. endIndex = bytes.byteLength;
  15196. startIndex = endIndex - MP2T_PACKET_LENGTH;
  15197. endLoop = false;
  15198. while (startIndex >= 0) {
  15199. // Look for a pair of start and end sync bytes in the data..
  15200. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15201. // We found a packet
  15202. packet = bytes.subarray(startIndex, endIndex);
  15203. type = probe.ts.parseType(packet, pmt.pid);
  15204. switch (type) {
  15205. case 'pes':
  15206. pesType = probe.ts.parsePesType(packet, pmt.table);
  15207. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15208. if (pesType === 'video' && pusi) {
  15209. parsed = probe.ts.parsePesTime(packet);
  15210. if (parsed) {
  15211. parsed.type = 'video';
  15212. result.video.push(parsed);
  15213. endLoop = true;
  15214. }
  15215. }
  15216. break;
  15217. }
  15218. if (endLoop) {
  15219. break;
  15220. }
  15221. startIndex -= MP2T_PACKET_LENGTH;
  15222. endIndex -= MP2T_PACKET_LENGTH;
  15223. continue;
  15224. } // If we get here, we have somehow become de-synchronized and we need to step
  15225. // forward one byte at a time until we find a pair of sync bytes that denote
  15226. // a packet
  15227. startIndex--;
  15228. endIndex--;
  15229. }
  15230. };
  15231. /**
  15232. * Adjusts the timestamp information for the segment to account for
  15233. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  15234. */
  15235. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  15236. if (segmentInfo.audio && segmentInfo.audio.length) {
  15237. var audioBaseTimestamp = baseTimestamp;
  15238. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  15239. audioBaseTimestamp = segmentInfo.audio[0].dts;
  15240. }
  15241. segmentInfo.audio.forEach(function (info) {
  15242. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  15243. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  15244. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  15245. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  15246. });
  15247. }
  15248. if (segmentInfo.video && segmentInfo.video.length) {
  15249. var videoBaseTimestamp = baseTimestamp;
  15250. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  15251. videoBaseTimestamp = segmentInfo.video[0].dts;
  15252. }
  15253. segmentInfo.video.forEach(function (info) {
  15254. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  15255. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  15256. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  15257. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  15258. });
  15259. if (segmentInfo.firstKeyFrame) {
  15260. var frame = segmentInfo.firstKeyFrame;
  15261. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  15262. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  15263. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  15264. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  15265. }
  15266. }
  15267. };
  15268. /**
  15269. * inspects the aac data stream for start and end time information
  15270. */
  15271. var inspectAac_ = function (bytes) {
  15272. var endLoop = false,
  15273. audioCount = 0,
  15274. sampleRate = null,
  15275. timestamp = null,
  15276. frameSize = 0,
  15277. byteIndex = 0,
  15278. packet;
  15279. while (bytes.length - byteIndex >= 3) {
  15280. var type = probe.aac.parseType(bytes, byteIndex);
  15281. switch (type) {
  15282. case 'timed-metadata':
  15283. // Exit early because we don't have enough to parse
  15284. // the ID3 tag header
  15285. if (bytes.length - byteIndex < 10) {
  15286. endLoop = true;
  15287. break;
  15288. }
  15289. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  15290. // to emit a full packet
  15291. if (frameSize > bytes.length) {
  15292. endLoop = true;
  15293. break;
  15294. }
  15295. if (timestamp === null) {
  15296. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  15297. timestamp = probe.aac.parseAacTimestamp(packet);
  15298. }
  15299. byteIndex += frameSize;
  15300. break;
  15301. case 'audio':
  15302. // Exit early because we don't have enough to parse
  15303. // the ADTS frame header
  15304. if (bytes.length - byteIndex < 7) {
  15305. endLoop = true;
  15306. break;
  15307. }
  15308. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  15309. // to emit a full packet
  15310. if (frameSize > bytes.length) {
  15311. endLoop = true;
  15312. break;
  15313. }
  15314. if (sampleRate === null) {
  15315. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  15316. sampleRate = probe.aac.parseSampleRate(packet);
  15317. }
  15318. audioCount++;
  15319. byteIndex += frameSize;
  15320. break;
  15321. default:
  15322. byteIndex++;
  15323. break;
  15324. }
  15325. if (endLoop) {
  15326. return null;
  15327. }
  15328. }
  15329. if (sampleRate === null || timestamp === null) {
  15330. return null;
  15331. }
  15332. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  15333. var result = {
  15334. audio: [{
  15335. type: 'audio',
  15336. dts: timestamp,
  15337. pts: timestamp
  15338. }, {
  15339. type: 'audio',
  15340. dts: timestamp + audioCount * 1024 * audioTimescale,
  15341. pts: timestamp + audioCount * 1024 * audioTimescale
  15342. }]
  15343. };
  15344. return result;
  15345. };
  15346. /**
  15347. * inspects the transport stream segment data for start and end time information
  15348. * of the audio and video tracks (when present) as well as the first key frame's
  15349. * start time.
  15350. */
  15351. var inspectTs_ = function (bytes) {
  15352. var pmt = {
  15353. pid: null,
  15354. table: null
  15355. };
  15356. var result = {};
  15357. parsePsi_(bytes, pmt);
  15358. for (var pid in pmt.table) {
  15359. if (pmt.table.hasOwnProperty(pid)) {
  15360. var type = pmt.table[pid];
  15361. switch (type) {
  15362. case StreamTypes.H264_STREAM_TYPE:
  15363. result.video = [];
  15364. parseVideoPes_(bytes, pmt, result);
  15365. if (result.video.length === 0) {
  15366. delete result.video;
  15367. }
  15368. break;
  15369. case StreamTypes.ADTS_STREAM_TYPE:
  15370. result.audio = [];
  15371. parseAudioPes_(bytes, pmt, result);
  15372. if (result.audio.length === 0) {
  15373. delete result.audio;
  15374. }
  15375. break;
  15376. }
  15377. }
  15378. }
  15379. return result;
  15380. };
  15381. /**
  15382. * Inspects segment byte data and returns an object with start and end timing information
  15383. *
  15384. * @param {Uint8Array} bytes The segment byte data
  15385. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  15386. * timestamps for rollover. This value must be in 90khz clock.
  15387. * @return {Object} Object containing start and end frame timing info of segment.
  15388. */
  15389. var inspect = function (bytes, baseTimestamp) {
  15390. var isAacData = probe.aac.isLikelyAacData(bytes);
  15391. var result;
  15392. if (isAacData) {
  15393. result = inspectAac_(bytes);
  15394. } else {
  15395. result = inspectTs_(bytes);
  15396. }
  15397. if (!result || !result.audio && !result.video) {
  15398. return null;
  15399. }
  15400. adjustTimestamp_(result, baseTimestamp);
  15401. return result;
  15402. };
  15403. var tsInspector = {
  15404. inspect: inspect,
  15405. parseAudioPes_: parseAudioPes_
  15406. };
  15407. /* global self */
  15408. /**
  15409. * Re-emits transmuxer events by converting them into messages to the
  15410. * world outside the worker.
  15411. *
  15412. * @param {Object} transmuxer the transmuxer to wire events on
  15413. * @private
  15414. */
  15415. const wireTransmuxerEvents = function (self, transmuxer) {
  15416. transmuxer.on('data', function (segment) {
  15417. // transfer ownership of the underlying ArrayBuffer
  15418. // instead of doing a copy to save memory
  15419. // ArrayBuffers are transferable but generic TypedArrays are not
  15420. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  15421. const initArray = segment.initSegment;
  15422. segment.initSegment = {
  15423. data: initArray.buffer,
  15424. byteOffset: initArray.byteOffset,
  15425. byteLength: initArray.byteLength
  15426. };
  15427. const typedArray = segment.data;
  15428. segment.data = typedArray.buffer;
  15429. self.postMessage({
  15430. action: 'data',
  15431. segment,
  15432. byteOffset: typedArray.byteOffset,
  15433. byteLength: typedArray.byteLength
  15434. }, [segment.data]);
  15435. });
  15436. transmuxer.on('done', function (data) {
  15437. self.postMessage({
  15438. action: 'done'
  15439. });
  15440. });
  15441. transmuxer.on('gopInfo', function (gopInfo) {
  15442. self.postMessage({
  15443. action: 'gopInfo',
  15444. gopInfo
  15445. });
  15446. });
  15447. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  15448. const videoSegmentTimingInfo = {
  15449. start: {
  15450. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  15451. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  15452. },
  15453. end: {
  15454. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  15455. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  15456. },
  15457. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  15458. };
  15459. if (timingInfo.prependedContentDuration) {
  15460. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  15461. }
  15462. self.postMessage({
  15463. action: 'videoSegmentTimingInfo',
  15464. videoSegmentTimingInfo
  15465. });
  15466. });
  15467. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  15468. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  15469. const audioSegmentTimingInfo = {
  15470. start: {
  15471. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  15472. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  15473. },
  15474. end: {
  15475. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  15476. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  15477. },
  15478. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  15479. };
  15480. if (timingInfo.prependedContentDuration) {
  15481. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  15482. }
  15483. self.postMessage({
  15484. action: 'audioSegmentTimingInfo',
  15485. audioSegmentTimingInfo
  15486. });
  15487. });
  15488. transmuxer.on('id3Frame', function (id3Frame) {
  15489. self.postMessage({
  15490. action: 'id3Frame',
  15491. id3Frame
  15492. });
  15493. });
  15494. transmuxer.on('caption', function (caption) {
  15495. self.postMessage({
  15496. action: 'caption',
  15497. caption
  15498. });
  15499. });
  15500. transmuxer.on('trackinfo', function (trackInfo) {
  15501. self.postMessage({
  15502. action: 'trackinfo',
  15503. trackInfo
  15504. });
  15505. });
  15506. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  15507. // convert to video TS since we prioritize video time over audio
  15508. self.postMessage({
  15509. action: 'audioTimingInfo',
  15510. audioTimingInfo: {
  15511. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  15512. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  15513. }
  15514. });
  15515. });
  15516. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  15517. self.postMessage({
  15518. action: 'videoTimingInfo',
  15519. videoTimingInfo: {
  15520. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  15521. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  15522. }
  15523. });
  15524. });
  15525. transmuxer.on('log', function (log) {
  15526. self.postMessage({
  15527. action: 'log',
  15528. log
  15529. });
  15530. });
  15531. };
  15532. /**
  15533. * All incoming messages route through this hash. If no function exists
  15534. * to handle an incoming message, then we ignore the message.
  15535. *
  15536. * @class MessageHandlers
  15537. * @param {Object} options the options to initialize with
  15538. */
  15539. class MessageHandlers {
  15540. constructor(self, options) {
  15541. this.options = options || {};
  15542. this.self = self;
  15543. this.init();
  15544. }
  15545. /**
  15546. * initialize our web worker and wire all the events.
  15547. */
  15548. init() {
  15549. if (this.transmuxer) {
  15550. this.transmuxer.dispose();
  15551. }
  15552. this.transmuxer = new transmuxer.Transmuxer(this.options);
  15553. wireTransmuxerEvents(this.self, this.transmuxer);
  15554. }
  15555. pushMp4Captions(data) {
  15556. if (!this.captionParser) {
  15557. this.captionParser = new captionParser();
  15558. this.captionParser.init();
  15559. }
  15560. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  15561. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  15562. this.self.postMessage({
  15563. action: 'mp4Captions',
  15564. captions: parsed && parsed.captions || [],
  15565. logs: parsed && parsed.logs || [],
  15566. data: segment.buffer
  15567. }, [segment.buffer]);
  15568. }
  15569. probeMp4StartTime({
  15570. timescales,
  15571. data
  15572. }) {
  15573. const startTime = probe$2.startTime(timescales, data);
  15574. this.self.postMessage({
  15575. action: 'probeMp4StartTime',
  15576. startTime,
  15577. data
  15578. }, [data.buffer]);
  15579. }
  15580. probeMp4Tracks({
  15581. data
  15582. }) {
  15583. const tracks = probe$2.tracks(data);
  15584. this.self.postMessage({
  15585. action: 'probeMp4Tracks',
  15586. tracks,
  15587. data
  15588. }, [data.buffer]);
  15589. }
  15590. /**
  15591. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  15592. * internal "media time," as well as whether it contains video and/or audio.
  15593. *
  15594. * @private
  15595. * @param {Uint8Array} bytes - segment bytes
  15596. * @param {number} baseStartTime
  15597. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  15598. * This value should be in seconds, as it's converted to a 90khz clock within the
  15599. * function body.
  15600. * @return {Object} The start time of the current segment in "media time" as well as
  15601. * whether it contains video and/or audio
  15602. */
  15603. probeTs({
  15604. data,
  15605. baseStartTime
  15606. }) {
  15607. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  15608. const timeInfo = tsInspector.inspect(data, tsStartTime);
  15609. let result = null;
  15610. if (timeInfo) {
  15611. result = {
  15612. // each type's time info comes back as an array of 2 times, start and end
  15613. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  15614. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  15615. };
  15616. if (result.hasVideo) {
  15617. result.videoStart = timeInfo.video[0].ptsTime;
  15618. }
  15619. if (result.hasAudio) {
  15620. result.audioStart = timeInfo.audio[0].ptsTime;
  15621. }
  15622. }
  15623. this.self.postMessage({
  15624. action: 'probeTs',
  15625. result,
  15626. data
  15627. }, [data.buffer]);
  15628. }
  15629. clearAllMp4Captions() {
  15630. if (this.captionParser) {
  15631. this.captionParser.clearAllCaptions();
  15632. }
  15633. }
  15634. clearParsedMp4Captions() {
  15635. if (this.captionParser) {
  15636. this.captionParser.clearParsedCaptions();
  15637. }
  15638. }
  15639. /**
  15640. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  15641. * processing.
  15642. *
  15643. * @param {ArrayBuffer} data data to push into the muxer
  15644. */
  15645. push(data) {
  15646. // Cast array buffer to correct type for transmuxer
  15647. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  15648. this.transmuxer.push(segment);
  15649. }
  15650. /**
  15651. * Recreate the transmuxer so that the next segment added via `push`
  15652. * start with a fresh transmuxer.
  15653. */
  15654. reset() {
  15655. this.transmuxer.reset();
  15656. }
  15657. /**
  15658. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  15659. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  15660. * set relative to the first based on the PTS values.
  15661. *
  15662. * @param {Object} data used to set the timestamp offset in the muxer
  15663. */
  15664. setTimestampOffset(data) {
  15665. const timestampOffset = data.timestampOffset || 0;
  15666. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  15667. }
  15668. setAudioAppendStart(data) {
  15669. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  15670. }
  15671. setRemux(data) {
  15672. this.transmuxer.setRemux(data.remux);
  15673. }
  15674. /**
  15675. * Forces the pipeline to finish processing the last segment and emit it's
  15676. * results.
  15677. *
  15678. * @param {Object} data event data, not really used
  15679. */
  15680. flush(data) {
  15681. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  15682. self.postMessage({
  15683. action: 'done',
  15684. type: 'transmuxed'
  15685. });
  15686. }
  15687. endTimeline() {
  15688. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  15689. // timelines
  15690. self.postMessage({
  15691. action: 'endedtimeline',
  15692. type: 'transmuxed'
  15693. });
  15694. }
  15695. alignGopsWith(data) {
  15696. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  15697. }
  15698. }
  15699. /**
  15700. * Our web worker interface so that things can talk to mux.js
  15701. * that will be running in a web worker. the scope is passed to this by
  15702. * webworkify.
  15703. *
  15704. * @param {Object} self the scope for the web worker
  15705. */
  15706. self.onmessage = function (event) {
  15707. if (event.data.action === 'init' && event.data.options) {
  15708. this.messageHandlers = new MessageHandlers(self, event.data.options);
  15709. return;
  15710. }
  15711. if (!this.messageHandlers) {
  15712. this.messageHandlers = new MessageHandlers(self);
  15713. }
  15714. if (event.data && event.data.action && event.data.action !== 'init') {
  15715. if (this.messageHandlers[event.data.action]) {
  15716. this.messageHandlers[event.data.action](event.data);
  15717. }
  15718. }
  15719. };
  15720. }));
  15721. var TransmuxWorker = factory(workerCode$1);
  15722. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  15723. const handleData_ = (event, transmuxedData, callback) => {
  15724. const {
  15725. type,
  15726. initSegment,
  15727. captions,
  15728. captionStreams,
  15729. metadata,
  15730. videoFrameDtsTime,
  15731. videoFramePtsTime
  15732. } = event.data.segment;
  15733. transmuxedData.buffer.push({
  15734. captions,
  15735. captionStreams,
  15736. metadata
  15737. });
  15738. const boxes = event.data.segment.boxes || {
  15739. data: event.data.segment.data
  15740. };
  15741. const result = {
  15742. type,
  15743. // cast ArrayBuffer to TypedArray
  15744. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  15745. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  15746. };
  15747. if (typeof videoFrameDtsTime !== 'undefined') {
  15748. result.videoFrameDtsTime = videoFrameDtsTime;
  15749. }
  15750. if (typeof videoFramePtsTime !== 'undefined') {
  15751. result.videoFramePtsTime = videoFramePtsTime;
  15752. }
  15753. callback(result);
  15754. };
  15755. const handleDone_ = ({
  15756. transmuxedData,
  15757. callback
  15758. }) => {
  15759. // Previously we only returned data on data events,
  15760. // not on done events. Clear out the buffer to keep that consistent.
  15761. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  15762. // have received
  15763. callback(transmuxedData);
  15764. };
  15765. const handleGopInfo_ = (event, transmuxedData) => {
  15766. transmuxedData.gopInfo = event.data.gopInfo;
  15767. };
  15768. const processTransmux = options => {
  15769. const {
  15770. transmuxer,
  15771. bytes,
  15772. audioAppendStart,
  15773. gopsToAlignWith,
  15774. remux,
  15775. onData,
  15776. onTrackInfo,
  15777. onAudioTimingInfo,
  15778. onVideoTimingInfo,
  15779. onVideoSegmentTimingInfo,
  15780. onAudioSegmentTimingInfo,
  15781. onId3,
  15782. onCaptions,
  15783. onDone,
  15784. onEndedTimeline,
  15785. onTransmuxerLog,
  15786. isEndOfTimeline
  15787. } = options;
  15788. const transmuxedData = {
  15789. buffer: []
  15790. };
  15791. let waitForEndedTimelineEvent = isEndOfTimeline;
  15792. const handleMessage = event => {
  15793. if (transmuxer.currentTransmux !== options) {
  15794. // disposed
  15795. return;
  15796. }
  15797. if (event.data.action === 'data') {
  15798. handleData_(event, transmuxedData, onData);
  15799. }
  15800. if (event.data.action === 'trackinfo') {
  15801. onTrackInfo(event.data.trackInfo);
  15802. }
  15803. if (event.data.action === 'gopInfo') {
  15804. handleGopInfo_(event, transmuxedData);
  15805. }
  15806. if (event.data.action === 'audioTimingInfo') {
  15807. onAudioTimingInfo(event.data.audioTimingInfo);
  15808. }
  15809. if (event.data.action === 'videoTimingInfo') {
  15810. onVideoTimingInfo(event.data.videoTimingInfo);
  15811. }
  15812. if (event.data.action === 'videoSegmentTimingInfo') {
  15813. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  15814. }
  15815. if (event.data.action === 'audioSegmentTimingInfo') {
  15816. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  15817. }
  15818. if (event.data.action === 'id3Frame') {
  15819. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  15820. }
  15821. if (event.data.action === 'caption') {
  15822. onCaptions(event.data.caption);
  15823. }
  15824. if (event.data.action === 'endedtimeline') {
  15825. waitForEndedTimelineEvent = false;
  15826. onEndedTimeline();
  15827. }
  15828. if (event.data.action === 'log') {
  15829. onTransmuxerLog(event.data.log);
  15830. } // wait for the transmuxed event since we may have audio and video
  15831. if (event.data.type !== 'transmuxed') {
  15832. return;
  15833. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  15834. // of a timeline, that means there may still be data events before the segment
  15835. // processing can be considerred complete. In that case, the final event should be
  15836. // an "endedtimeline" event with the type "transmuxed."
  15837. if (waitForEndedTimelineEvent) {
  15838. return;
  15839. }
  15840. transmuxer.onmessage = null;
  15841. handleDone_({
  15842. transmuxedData,
  15843. callback: onDone
  15844. });
  15845. /* eslint-disable no-use-before-define */
  15846. dequeue(transmuxer);
  15847. /* eslint-enable */
  15848. };
  15849. transmuxer.onmessage = handleMessage;
  15850. if (audioAppendStart) {
  15851. transmuxer.postMessage({
  15852. action: 'setAudioAppendStart',
  15853. appendStart: audioAppendStart
  15854. });
  15855. } // allow empty arrays to be passed to clear out GOPs
  15856. if (Array.isArray(gopsToAlignWith)) {
  15857. transmuxer.postMessage({
  15858. action: 'alignGopsWith',
  15859. gopsToAlignWith
  15860. });
  15861. }
  15862. if (typeof remux !== 'undefined') {
  15863. transmuxer.postMessage({
  15864. action: 'setRemux',
  15865. remux
  15866. });
  15867. }
  15868. if (bytes.byteLength) {
  15869. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  15870. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  15871. transmuxer.postMessage({
  15872. action: 'push',
  15873. // Send the typed-array of data as an ArrayBuffer so that
  15874. // it can be sent as a "Transferable" and avoid the costly
  15875. // memory copy
  15876. data: buffer,
  15877. // To recreate the original typed-array, we need information
  15878. // about what portion of the ArrayBuffer it was a view into
  15879. byteOffset,
  15880. byteLength: bytes.byteLength
  15881. }, [buffer]);
  15882. }
  15883. if (isEndOfTimeline) {
  15884. transmuxer.postMessage({
  15885. action: 'endTimeline'
  15886. });
  15887. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  15888. // the end of the segment
  15889. transmuxer.postMessage({
  15890. action: 'flush'
  15891. });
  15892. };
  15893. const dequeue = transmuxer => {
  15894. transmuxer.currentTransmux = null;
  15895. if (transmuxer.transmuxQueue.length) {
  15896. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  15897. if (typeof transmuxer.currentTransmux === 'function') {
  15898. transmuxer.currentTransmux();
  15899. } else {
  15900. processTransmux(transmuxer.currentTransmux);
  15901. }
  15902. }
  15903. };
  15904. const processAction = (transmuxer, action) => {
  15905. transmuxer.postMessage({
  15906. action
  15907. });
  15908. dequeue(transmuxer);
  15909. };
  15910. const enqueueAction = (action, transmuxer) => {
  15911. if (!transmuxer.currentTransmux) {
  15912. transmuxer.currentTransmux = action;
  15913. processAction(transmuxer, action);
  15914. return;
  15915. }
  15916. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  15917. };
  15918. const reset = transmuxer => {
  15919. enqueueAction('reset', transmuxer);
  15920. };
  15921. const endTimeline = transmuxer => {
  15922. enqueueAction('endTimeline', transmuxer);
  15923. };
  15924. const transmux = options => {
  15925. if (!options.transmuxer.currentTransmux) {
  15926. options.transmuxer.currentTransmux = options;
  15927. processTransmux(options);
  15928. return;
  15929. }
  15930. options.transmuxer.transmuxQueue.push(options);
  15931. };
  15932. const createTransmuxer = options => {
  15933. const transmuxer = new TransmuxWorker();
  15934. transmuxer.currentTransmux = null;
  15935. transmuxer.transmuxQueue = [];
  15936. const term = transmuxer.terminate;
  15937. transmuxer.terminate = () => {
  15938. transmuxer.currentTransmux = null;
  15939. transmuxer.transmuxQueue.length = 0;
  15940. return term.call(transmuxer);
  15941. };
  15942. transmuxer.postMessage({
  15943. action: 'init',
  15944. options
  15945. });
  15946. return transmuxer;
  15947. };
  15948. var segmentTransmuxer = {
  15949. reset,
  15950. endTimeline,
  15951. transmux,
  15952. createTransmuxer
  15953. };
  15954. const workerCallback = function (options) {
  15955. const transmuxer = options.transmuxer;
  15956. const endAction = options.endAction || options.action;
  15957. const callback = options.callback;
  15958. const message = _extends({}, options, {
  15959. endAction: null,
  15960. transmuxer: null,
  15961. callback: null
  15962. });
  15963. const listenForEndEvent = event => {
  15964. if (event.data.action !== endAction) {
  15965. return;
  15966. }
  15967. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  15968. if (event.data.data) {
  15969. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  15970. if (options.data) {
  15971. options.data = event.data.data;
  15972. }
  15973. }
  15974. callback(event.data);
  15975. };
  15976. transmuxer.addEventListener('message', listenForEndEvent);
  15977. if (options.data) {
  15978. const isArrayBuffer = options.data instanceof ArrayBuffer;
  15979. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  15980. message.byteLength = options.data.byteLength;
  15981. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  15982. transmuxer.postMessage(message, transfers);
  15983. } else {
  15984. transmuxer.postMessage(message);
  15985. }
  15986. };
  15987. const REQUEST_ERRORS = {
  15988. FAILURE: 2,
  15989. TIMEOUT: -101,
  15990. ABORTED: -102
  15991. };
  15992. /**
  15993. * Abort all requests
  15994. *
  15995. * @param {Object} activeXhrs - an object that tracks all XHR requests
  15996. */
  15997. const abortAll = activeXhrs => {
  15998. activeXhrs.forEach(xhr => {
  15999. xhr.abort();
  16000. });
  16001. };
  16002. /**
  16003. * Gather important bandwidth stats once a request has completed
  16004. *
  16005. * @param {Object} request - the XHR request from which to gather stats
  16006. */
  16007. const getRequestStats = request => {
  16008. return {
  16009. bandwidth: request.bandwidth,
  16010. bytesReceived: request.bytesReceived || 0,
  16011. roundTripTime: request.roundTripTime || 0
  16012. };
  16013. };
  16014. /**
  16015. * If possible gather bandwidth stats as a request is in
  16016. * progress
  16017. *
  16018. * @param {Event} progressEvent - an event object from an XHR's progress event
  16019. */
  16020. const getProgressStats = progressEvent => {
  16021. const request = progressEvent.target;
  16022. const roundTripTime = Date.now() - request.requestTime;
  16023. const stats = {
  16024. bandwidth: Infinity,
  16025. bytesReceived: 0,
  16026. roundTripTime: roundTripTime || 0
  16027. };
  16028. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  16029. // because we should only use bandwidth stats on progress to determine when
  16030. // abort a request early due to insufficient bandwidth
  16031. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  16032. return stats;
  16033. };
  16034. /**
  16035. * Handle all error conditions in one place and return an object
  16036. * with all the information
  16037. *
  16038. * @param {Error|null} error - if non-null signals an error occured with the XHR
  16039. * @param {Object} request - the XHR request that possibly generated the error
  16040. */
  16041. const handleErrors = (error, request) => {
  16042. if (request.timedout) {
  16043. return {
  16044. status: request.status,
  16045. message: 'HLS request timed-out at URL: ' + request.uri,
  16046. code: REQUEST_ERRORS.TIMEOUT,
  16047. xhr: request
  16048. };
  16049. }
  16050. if (request.aborted) {
  16051. return {
  16052. status: request.status,
  16053. message: 'HLS request aborted at URL: ' + request.uri,
  16054. code: REQUEST_ERRORS.ABORTED,
  16055. xhr: request
  16056. };
  16057. }
  16058. if (error) {
  16059. return {
  16060. status: request.status,
  16061. message: 'HLS request errored at URL: ' + request.uri,
  16062. code: REQUEST_ERRORS.FAILURE,
  16063. xhr: request
  16064. };
  16065. }
  16066. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  16067. return {
  16068. status: request.status,
  16069. message: 'Empty HLS response at URL: ' + request.uri,
  16070. code: REQUEST_ERRORS.FAILURE,
  16071. xhr: request
  16072. };
  16073. }
  16074. return null;
  16075. };
  16076. /**
  16077. * Handle responses for key data and convert the key data to the correct format
  16078. * for the decryption step later
  16079. *
  16080. * @param {Object} segment - a simplified copy of the segmentInfo object
  16081. * from SegmentLoader
  16082. * @param {Array} objects - objects to add the key bytes to.
  16083. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16084. * this request
  16085. */
  16086. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  16087. const response = request.response;
  16088. const errorObj = handleErrors(error, request);
  16089. if (errorObj) {
  16090. return finishProcessingFn(errorObj, segment);
  16091. }
  16092. if (response.byteLength !== 16) {
  16093. return finishProcessingFn({
  16094. status: request.status,
  16095. message: 'Invalid HLS key at URL: ' + request.uri,
  16096. code: REQUEST_ERRORS.FAILURE,
  16097. xhr: request
  16098. }, segment);
  16099. }
  16100. const view = new DataView(response);
  16101. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  16102. for (let i = 0; i < objects.length; i++) {
  16103. objects[i].bytes = bytes;
  16104. }
  16105. return finishProcessingFn(null, segment);
  16106. };
  16107. const parseInitSegment = (segment, callback) => {
  16108. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  16109. // only know how to parse mp4 init segments at the moment
  16110. if (type !== 'mp4') {
  16111. const uri = segment.map.resolvedUri || segment.map.uri;
  16112. return callback({
  16113. internal: true,
  16114. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  16115. code: REQUEST_ERRORS.FAILURE
  16116. });
  16117. }
  16118. workerCallback({
  16119. action: 'probeMp4Tracks',
  16120. data: segment.map.bytes,
  16121. transmuxer: segment.transmuxer,
  16122. callback: ({
  16123. tracks,
  16124. data
  16125. }) => {
  16126. // transfer bytes back to us
  16127. segment.map.bytes = data;
  16128. tracks.forEach(function (track) {
  16129. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  16130. if (segment.map.tracks[track.type]) {
  16131. return;
  16132. }
  16133. segment.map.tracks[track.type] = track;
  16134. if (typeof track.id === 'number' && track.timescale) {
  16135. segment.map.timescales = segment.map.timescales || {};
  16136. segment.map.timescales[track.id] = track.timescale;
  16137. }
  16138. });
  16139. return callback(null);
  16140. }
  16141. });
  16142. };
  16143. /**
  16144. * Handle init-segment responses
  16145. *
  16146. * @param {Object} segment - a simplified copy of the segmentInfo object
  16147. * from SegmentLoader
  16148. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16149. * this request
  16150. */
  16151. const handleInitSegmentResponse = ({
  16152. segment,
  16153. finishProcessingFn
  16154. }) => (error, request) => {
  16155. const errorObj = handleErrors(error, request);
  16156. if (errorObj) {
  16157. return finishProcessingFn(errorObj, segment);
  16158. }
  16159. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  16160. // until the key request is done to decrypt.
  16161. if (segment.map.key) {
  16162. segment.map.encryptedBytes = bytes;
  16163. return finishProcessingFn(null, segment);
  16164. }
  16165. segment.map.bytes = bytes;
  16166. parseInitSegment(segment, function (parseError) {
  16167. if (parseError) {
  16168. parseError.xhr = request;
  16169. parseError.status = request.status;
  16170. return finishProcessingFn(parseError, segment);
  16171. }
  16172. finishProcessingFn(null, segment);
  16173. });
  16174. };
  16175. /**
  16176. * Response handler for segment-requests being sure to set the correct
  16177. * property depending on whether the segment is encryped or not
  16178. * Also records and keeps track of stats that are used for ABR purposes
  16179. *
  16180. * @param {Object} segment - a simplified copy of the segmentInfo object
  16181. * from SegmentLoader
  16182. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16183. * this request
  16184. */
  16185. const handleSegmentResponse = ({
  16186. segment,
  16187. finishProcessingFn,
  16188. responseType
  16189. }) => (error, request) => {
  16190. const errorObj = handleErrors(error, request);
  16191. if (errorObj) {
  16192. return finishProcessingFn(errorObj, segment);
  16193. }
  16194. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  16195. // thrown for two primary cases:
  16196. // 1. the mime type override stops working, or is not implemented for a specific
  16197. // browser
  16198. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  16199. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  16200. segment.stats = getRequestStats(request);
  16201. if (segment.key) {
  16202. segment.encryptedBytes = new Uint8Array(newBytes);
  16203. } else {
  16204. segment.bytes = new Uint8Array(newBytes);
  16205. }
  16206. return finishProcessingFn(null, segment);
  16207. };
  16208. const transmuxAndNotify = ({
  16209. segment,
  16210. bytes,
  16211. trackInfoFn,
  16212. timingInfoFn,
  16213. videoSegmentTimingInfoFn,
  16214. audioSegmentTimingInfoFn,
  16215. id3Fn,
  16216. captionsFn,
  16217. isEndOfTimeline,
  16218. endedTimelineFn,
  16219. dataFn,
  16220. doneFn,
  16221. onTransmuxerLog
  16222. }) => {
  16223. const fmp4Tracks = segment.map && segment.map.tracks || {};
  16224. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  16225. // One reason for this is that in the case of full segments, we want to trust start
  16226. // times from the probe, rather than the transmuxer.
  16227. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  16228. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  16229. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  16230. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  16231. const finish = () => transmux({
  16232. bytes,
  16233. transmuxer: segment.transmuxer,
  16234. audioAppendStart: segment.audioAppendStart,
  16235. gopsToAlignWith: segment.gopsToAlignWith,
  16236. remux: isMuxed,
  16237. onData: result => {
  16238. result.type = result.type === 'combined' ? 'video' : result.type;
  16239. dataFn(segment, result);
  16240. },
  16241. onTrackInfo: trackInfo => {
  16242. if (trackInfoFn) {
  16243. if (isMuxed) {
  16244. trackInfo.isMuxed = true;
  16245. }
  16246. trackInfoFn(segment, trackInfo);
  16247. }
  16248. },
  16249. onAudioTimingInfo: audioTimingInfo => {
  16250. // we only want the first start value we encounter
  16251. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  16252. audioStartFn(audioTimingInfo.start);
  16253. audioStartFn = null;
  16254. } // we want to continually update the end time
  16255. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  16256. audioEndFn(audioTimingInfo.end);
  16257. }
  16258. },
  16259. onVideoTimingInfo: videoTimingInfo => {
  16260. // we only want the first start value we encounter
  16261. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  16262. videoStartFn(videoTimingInfo.start);
  16263. videoStartFn = null;
  16264. } // we want to continually update the end time
  16265. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  16266. videoEndFn(videoTimingInfo.end);
  16267. }
  16268. },
  16269. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  16270. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  16271. },
  16272. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  16273. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  16274. },
  16275. onId3: (id3Frames, dispatchType) => {
  16276. id3Fn(segment, id3Frames, dispatchType);
  16277. },
  16278. onCaptions: captions => {
  16279. captionsFn(segment, [captions]);
  16280. },
  16281. isEndOfTimeline,
  16282. onEndedTimeline: () => {
  16283. endedTimelineFn();
  16284. },
  16285. onTransmuxerLog,
  16286. onDone: result => {
  16287. if (!doneFn) {
  16288. return;
  16289. }
  16290. result.type = result.type === 'combined' ? 'video' : result.type;
  16291. doneFn(null, segment, result);
  16292. }
  16293. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  16294. // Meaning cached frame data may corrupt our notion of where this segment
  16295. // really starts. To get around this, probe for the info needed.
  16296. workerCallback({
  16297. action: 'probeTs',
  16298. transmuxer: segment.transmuxer,
  16299. data: bytes,
  16300. baseStartTime: segment.baseStartTime,
  16301. callback: data => {
  16302. segment.bytes = bytes = data.data;
  16303. const probeResult = data.result;
  16304. if (probeResult) {
  16305. trackInfoFn(segment, {
  16306. hasAudio: probeResult.hasAudio,
  16307. hasVideo: probeResult.hasVideo,
  16308. isMuxed
  16309. });
  16310. trackInfoFn = null;
  16311. if (probeResult.hasAudio && !isMuxed) {
  16312. audioStartFn(probeResult.audioStart);
  16313. }
  16314. if (probeResult.hasVideo) {
  16315. videoStartFn(probeResult.videoStart);
  16316. }
  16317. audioStartFn = null;
  16318. videoStartFn = null;
  16319. }
  16320. finish();
  16321. }
  16322. });
  16323. };
  16324. const handleSegmentBytes = ({
  16325. segment,
  16326. bytes,
  16327. trackInfoFn,
  16328. timingInfoFn,
  16329. videoSegmentTimingInfoFn,
  16330. audioSegmentTimingInfoFn,
  16331. id3Fn,
  16332. captionsFn,
  16333. isEndOfTimeline,
  16334. endedTimelineFn,
  16335. dataFn,
  16336. doneFn,
  16337. onTransmuxerLog
  16338. }) => {
  16339. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  16340. // We should have a handler that fetches the number of bytes required
  16341. // to check if something is fmp4. This will allow us to save bandwidth
  16342. // because we can only exclude a playlist and abort requests
  16343. // by codec after trackinfo triggers.
  16344. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  16345. segment.isFmp4 = true;
  16346. const {
  16347. tracks
  16348. } = segment.map;
  16349. const trackInfo = {
  16350. isFmp4: true,
  16351. hasVideo: !!tracks.video,
  16352. hasAudio: !!tracks.audio
  16353. }; // if we have a audio track, with a codec that is not set to
  16354. // encrypted audio
  16355. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  16356. trackInfo.audioCodec = tracks.audio.codec;
  16357. } // if we have a video track, with a codec that is not set to
  16358. // encrypted video
  16359. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  16360. trackInfo.videoCodec = tracks.video.codec;
  16361. }
  16362. if (tracks.video && tracks.audio) {
  16363. trackInfo.isMuxed = true;
  16364. } // since we don't support appending fmp4 data on progress, we know we have the full
  16365. // segment here
  16366. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  16367. // time. The end time can be roughly calculated by the receiver using the duration.
  16368. //
  16369. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  16370. // that is the true start of the segment (where the playback engine should begin
  16371. // decoding).
  16372. const finishLoading = captions => {
  16373. // if the track still has audio at this point it is only possible
  16374. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  16375. // above.
  16376. // we make sure to use segment.bytes here as that
  16377. dataFn(segment, {
  16378. data: bytesAsUint8Array,
  16379. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  16380. });
  16381. if (captions && captions.length) {
  16382. captionsFn(segment, captions);
  16383. }
  16384. doneFn(null, segment, {});
  16385. };
  16386. workerCallback({
  16387. action: 'probeMp4StartTime',
  16388. timescales: segment.map.timescales,
  16389. data: bytesAsUint8Array,
  16390. transmuxer: segment.transmuxer,
  16391. callback: ({
  16392. data,
  16393. startTime
  16394. }) => {
  16395. // transfer bytes back to us
  16396. bytes = data.buffer;
  16397. segment.bytes = bytesAsUint8Array = data;
  16398. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  16399. timingInfoFn(segment, 'audio', 'start', startTime);
  16400. }
  16401. if (trackInfo.hasVideo) {
  16402. timingInfoFn(segment, 'video', 'start', startTime);
  16403. } // Run through the CaptionParser in case there are captions.
  16404. // Initialize CaptionParser if it hasn't been yet
  16405. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  16406. finishLoading();
  16407. return;
  16408. }
  16409. workerCallback({
  16410. action: 'pushMp4Captions',
  16411. endAction: 'mp4Captions',
  16412. transmuxer: segment.transmuxer,
  16413. data: bytesAsUint8Array,
  16414. timescales: segment.map.timescales,
  16415. trackIds: [tracks.video.id],
  16416. callback: message => {
  16417. // transfer bytes back to us
  16418. bytes = message.data.buffer;
  16419. segment.bytes = bytesAsUint8Array = message.data;
  16420. message.logs.forEach(function (log) {
  16421. onTransmuxerLog(merge$1(log, {
  16422. stream: 'mp4CaptionParser'
  16423. }));
  16424. });
  16425. finishLoading(message.captions);
  16426. }
  16427. });
  16428. }
  16429. });
  16430. return;
  16431. } // VTT or other segments that don't need processing
  16432. if (!segment.transmuxer) {
  16433. doneFn(null, segment, {});
  16434. return;
  16435. }
  16436. if (typeof segment.container === 'undefined') {
  16437. segment.container = detectContainerForBytes(bytesAsUint8Array);
  16438. }
  16439. if (segment.container !== 'ts' && segment.container !== 'aac') {
  16440. trackInfoFn(segment, {
  16441. hasAudio: false,
  16442. hasVideo: false
  16443. });
  16444. doneFn(null, segment, {});
  16445. return;
  16446. } // ts or aac
  16447. transmuxAndNotify({
  16448. segment,
  16449. bytes,
  16450. trackInfoFn,
  16451. timingInfoFn,
  16452. videoSegmentTimingInfoFn,
  16453. audioSegmentTimingInfoFn,
  16454. id3Fn,
  16455. captionsFn,
  16456. isEndOfTimeline,
  16457. endedTimelineFn,
  16458. dataFn,
  16459. doneFn,
  16460. onTransmuxerLog
  16461. });
  16462. };
  16463. const decrypt = function ({
  16464. id,
  16465. key,
  16466. encryptedBytes,
  16467. decryptionWorker
  16468. }, callback) {
  16469. const decryptionHandler = event => {
  16470. if (event.data.source === id) {
  16471. decryptionWorker.removeEventListener('message', decryptionHandler);
  16472. const decrypted = event.data.decrypted;
  16473. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  16474. }
  16475. };
  16476. decryptionWorker.addEventListener('message', decryptionHandler);
  16477. let keyBytes;
  16478. if (key.bytes.slice) {
  16479. keyBytes = key.bytes.slice();
  16480. } else {
  16481. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  16482. } // incrementally decrypt the bytes
  16483. decryptionWorker.postMessage(createTransferableMessage({
  16484. source: id,
  16485. encrypted: encryptedBytes,
  16486. key: keyBytes,
  16487. iv: key.iv
  16488. }), [encryptedBytes.buffer, keyBytes.buffer]);
  16489. };
  16490. /**
  16491. * Decrypt the segment via the decryption web worker
  16492. *
  16493. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  16494. * routines
  16495. * @param {Object} segment - a simplified copy of the segmentInfo object
  16496. * from SegmentLoader
  16497. * @param {Function} trackInfoFn - a callback that receives track info
  16498. * @param {Function} timingInfoFn - a callback that receives timing info
  16499. * @param {Function} videoSegmentTimingInfoFn
  16500. * a callback that receives video timing info based on media times and
  16501. * any adjustments made by the transmuxer
  16502. * @param {Function} audioSegmentTimingInfoFn
  16503. * a callback that receives audio timing info based on media times and
  16504. * any adjustments made by the transmuxer
  16505. * @param {boolean} isEndOfTimeline
  16506. * true if this segment represents the last segment in a timeline
  16507. * @param {Function} endedTimelineFn
  16508. * a callback made when a timeline is ended, will only be called if
  16509. * isEndOfTimeline is true
  16510. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16511. * and ready to use
  16512. * @param {Function} doneFn - a callback that is executed after decryption has completed
  16513. */
  16514. const decryptSegment = ({
  16515. decryptionWorker,
  16516. segment,
  16517. trackInfoFn,
  16518. timingInfoFn,
  16519. videoSegmentTimingInfoFn,
  16520. audioSegmentTimingInfoFn,
  16521. id3Fn,
  16522. captionsFn,
  16523. isEndOfTimeline,
  16524. endedTimelineFn,
  16525. dataFn,
  16526. doneFn,
  16527. onTransmuxerLog
  16528. }) => {
  16529. decrypt({
  16530. id: segment.requestId,
  16531. key: segment.key,
  16532. encryptedBytes: segment.encryptedBytes,
  16533. decryptionWorker
  16534. }, decryptedBytes => {
  16535. segment.bytes = decryptedBytes;
  16536. handleSegmentBytes({
  16537. segment,
  16538. bytes: segment.bytes,
  16539. trackInfoFn,
  16540. timingInfoFn,
  16541. videoSegmentTimingInfoFn,
  16542. audioSegmentTimingInfoFn,
  16543. id3Fn,
  16544. captionsFn,
  16545. isEndOfTimeline,
  16546. endedTimelineFn,
  16547. dataFn,
  16548. doneFn,
  16549. onTransmuxerLog
  16550. });
  16551. });
  16552. };
  16553. /**
  16554. * This function waits for all XHRs to finish (with either success or failure)
  16555. * before continueing processing via it's callback. The function gathers errors
  16556. * from each request into a single errors array so that the error status for
  16557. * each request can be examined later.
  16558. *
  16559. * @param {Object} activeXhrs - an object that tracks all XHR requests
  16560. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  16561. * routines
  16562. * @param {Function} trackInfoFn - a callback that receives track info
  16563. * @param {Function} timingInfoFn - a callback that receives timing info
  16564. * @param {Function} videoSegmentTimingInfoFn
  16565. * a callback that receives video timing info based on media times and
  16566. * any adjustments made by the transmuxer
  16567. * @param {Function} audioSegmentTimingInfoFn
  16568. * a callback that receives audio timing info based on media times and
  16569. * any adjustments made by the transmuxer
  16570. * @param {Function} id3Fn - a callback that receives ID3 metadata
  16571. * @param {Function} captionsFn - a callback that receives captions
  16572. * @param {boolean} isEndOfTimeline
  16573. * true if this segment represents the last segment in a timeline
  16574. * @param {Function} endedTimelineFn
  16575. * a callback made when a timeline is ended, will only be called if
  16576. * isEndOfTimeline is true
  16577. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16578. * and ready to use
  16579. * @param {Function} doneFn - a callback that is executed after all resources have been
  16580. * downloaded and any decryption completed
  16581. */
  16582. const waitForCompletion = ({
  16583. activeXhrs,
  16584. decryptionWorker,
  16585. trackInfoFn,
  16586. timingInfoFn,
  16587. videoSegmentTimingInfoFn,
  16588. audioSegmentTimingInfoFn,
  16589. id3Fn,
  16590. captionsFn,
  16591. isEndOfTimeline,
  16592. endedTimelineFn,
  16593. dataFn,
  16594. doneFn,
  16595. onTransmuxerLog
  16596. }) => {
  16597. let count = 0;
  16598. let didError = false;
  16599. return (error, segment) => {
  16600. if (didError) {
  16601. return;
  16602. }
  16603. if (error) {
  16604. didError = true; // If there are errors, we have to abort any outstanding requests
  16605. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  16606. // handle the aborted events from those requests, there are some cases where we may
  16607. // never get an aborted event. For instance, if the network connection is lost and
  16608. // there were two requests, the first may have triggered an error immediately, while
  16609. // the second request remains unsent. In that case, the aborted algorithm will not
  16610. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  16611. //
  16612. // We also can't rely on the ready state of the XHR, since the request that
  16613. // triggered the connection error may also show as a ready state of 0 (unsent).
  16614. // Therefore, we have to finish this group of requests immediately after the first
  16615. // seen error.
  16616. return doneFn(error, segment);
  16617. }
  16618. count += 1;
  16619. if (count === activeXhrs.length) {
  16620. const segmentFinish = function () {
  16621. if (segment.encryptedBytes) {
  16622. return decryptSegment({
  16623. decryptionWorker,
  16624. segment,
  16625. trackInfoFn,
  16626. timingInfoFn,
  16627. videoSegmentTimingInfoFn,
  16628. audioSegmentTimingInfoFn,
  16629. id3Fn,
  16630. captionsFn,
  16631. isEndOfTimeline,
  16632. endedTimelineFn,
  16633. dataFn,
  16634. doneFn,
  16635. onTransmuxerLog
  16636. });
  16637. } // Otherwise, everything is ready just continue
  16638. handleSegmentBytes({
  16639. segment,
  16640. bytes: segment.bytes,
  16641. trackInfoFn,
  16642. timingInfoFn,
  16643. videoSegmentTimingInfoFn,
  16644. audioSegmentTimingInfoFn,
  16645. id3Fn,
  16646. captionsFn,
  16647. isEndOfTimeline,
  16648. endedTimelineFn,
  16649. dataFn,
  16650. doneFn,
  16651. onTransmuxerLog
  16652. });
  16653. }; // Keep track of when *all* of the requests have completed
  16654. segment.endOfAllRequests = Date.now();
  16655. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  16656. return decrypt({
  16657. decryptionWorker,
  16658. // add -init to the "id" to differentiate between segment
  16659. // and init segment decryption, just in case they happen
  16660. // at the same time at some point in the future.
  16661. id: segment.requestId + '-init',
  16662. encryptedBytes: segment.map.encryptedBytes,
  16663. key: segment.map.key
  16664. }, decryptedBytes => {
  16665. segment.map.bytes = decryptedBytes;
  16666. parseInitSegment(segment, parseError => {
  16667. if (parseError) {
  16668. abortAll(activeXhrs);
  16669. return doneFn(parseError, segment);
  16670. }
  16671. segmentFinish();
  16672. });
  16673. });
  16674. }
  16675. segmentFinish();
  16676. }
  16677. };
  16678. };
  16679. /**
  16680. * Calls the abort callback if any request within the batch was aborted. Will only call
  16681. * the callback once per batch of requests, even if multiple were aborted.
  16682. *
  16683. * @param {Object} loadendState - state to check to see if the abort function was called
  16684. * @param {Function} abortFn - callback to call for abort
  16685. */
  16686. const handleLoadEnd = ({
  16687. loadendState,
  16688. abortFn
  16689. }) => event => {
  16690. const request = event.target;
  16691. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  16692. abortFn();
  16693. loadendState.calledAbortFn = true;
  16694. }
  16695. };
  16696. /**
  16697. * Simple progress event callback handler that gathers some stats before
  16698. * executing a provided callback with the `segment` object
  16699. *
  16700. * @param {Object} segment - a simplified copy of the segmentInfo object
  16701. * from SegmentLoader
  16702. * @param {Function} progressFn - a callback that is executed each time a progress event
  16703. * is received
  16704. * @param {Function} trackInfoFn - a callback that receives track info
  16705. * @param {Function} timingInfoFn - a callback that receives timing info
  16706. * @param {Function} videoSegmentTimingInfoFn
  16707. * a callback that receives video timing info based on media times and
  16708. * any adjustments made by the transmuxer
  16709. * @param {Function} audioSegmentTimingInfoFn
  16710. * a callback that receives audio timing info based on media times and
  16711. * any adjustments made by the transmuxer
  16712. * @param {boolean} isEndOfTimeline
  16713. * true if this segment represents the last segment in a timeline
  16714. * @param {Function} endedTimelineFn
  16715. * a callback made when a timeline is ended, will only be called if
  16716. * isEndOfTimeline is true
  16717. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16718. * and ready to use
  16719. * @param {Event} event - the progress event object from XMLHttpRequest
  16720. */
  16721. const handleProgress = ({
  16722. segment,
  16723. progressFn,
  16724. trackInfoFn,
  16725. timingInfoFn,
  16726. videoSegmentTimingInfoFn,
  16727. audioSegmentTimingInfoFn,
  16728. id3Fn,
  16729. captionsFn,
  16730. isEndOfTimeline,
  16731. endedTimelineFn,
  16732. dataFn
  16733. }) => event => {
  16734. const request = event.target;
  16735. if (request.aborted) {
  16736. return;
  16737. }
  16738. segment.stats = merge$1(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  16739. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  16740. segment.stats.firstBytesReceivedAt = Date.now();
  16741. }
  16742. return progressFn(event, segment);
  16743. };
  16744. /**
  16745. * Load all resources and does any processing necessary for a media-segment
  16746. *
  16747. * Features:
  16748. * decrypts the media-segment if it has a key uri and an iv
  16749. * aborts *all* requests if *any* one request fails
  16750. *
  16751. * The segment object, at minimum, has the following format:
  16752. * {
  16753. * resolvedUri: String,
  16754. * [transmuxer]: Object,
  16755. * [byterange]: {
  16756. * offset: Number,
  16757. * length: Number
  16758. * },
  16759. * [key]: {
  16760. * resolvedUri: String
  16761. * [byterange]: {
  16762. * offset: Number,
  16763. * length: Number
  16764. * },
  16765. * iv: {
  16766. * bytes: Uint32Array
  16767. * }
  16768. * },
  16769. * [map]: {
  16770. * resolvedUri: String,
  16771. * [byterange]: {
  16772. * offset: Number,
  16773. * length: Number
  16774. * },
  16775. * [bytes]: Uint8Array
  16776. * }
  16777. * }
  16778. * ...where [name] denotes optional properties
  16779. *
  16780. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  16781. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  16782. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  16783. * decryption routines
  16784. * @param {Object} segment - a simplified copy of the segmentInfo object
  16785. * from SegmentLoader
  16786. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  16787. * aborted
  16788. * @param {Function} progressFn - a callback that receives progress events from the main
  16789. * segment's xhr request
  16790. * @param {Function} trackInfoFn - a callback that receives track info
  16791. * @param {Function} timingInfoFn - a callback that receives timing info
  16792. * @param {Function} videoSegmentTimingInfoFn
  16793. * a callback that receives video timing info based on media times and
  16794. * any adjustments made by the transmuxer
  16795. * @param {Function} audioSegmentTimingInfoFn
  16796. * a callback that receives audio timing info based on media times and
  16797. * any adjustments made by the transmuxer
  16798. * @param {Function} id3Fn - a callback that receives ID3 metadata
  16799. * @param {Function} captionsFn - a callback that receives captions
  16800. * @param {boolean} isEndOfTimeline
  16801. * true if this segment represents the last segment in a timeline
  16802. * @param {Function} endedTimelineFn
  16803. * a callback made when a timeline is ended, will only be called if
  16804. * isEndOfTimeline is true
  16805. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  16806. * request, transmuxed if needed
  16807. * @param {Function} doneFn - a callback that is executed only once all requests have
  16808. * succeeded or failed
  16809. * @return {Function} a function that, when invoked, immediately aborts all
  16810. * outstanding requests
  16811. */
  16812. const mediaSegmentRequest = ({
  16813. xhr,
  16814. xhrOptions,
  16815. decryptionWorker,
  16816. segment,
  16817. abortFn,
  16818. progressFn,
  16819. trackInfoFn,
  16820. timingInfoFn,
  16821. videoSegmentTimingInfoFn,
  16822. audioSegmentTimingInfoFn,
  16823. id3Fn,
  16824. captionsFn,
  16825. isEndOfTimeline,
  16826. endedTimelineFn,
  16827. dataFn,
  16828. doneFn,
  16829. onTransmuxerLog
  16830. }) => {
  16831. const activeXhrs = [];
  16832. const finishProcessingFn = waitForCompletion({
  16833. activeXhrs,
  16834. decryptionWorker,
  16835. trackInfoFn,
  16836. timingInfoFn,
  16837. videoSegmentTimingInfoFn,
  16838. audioSegmentTimingInfoFn,
  16839. id3Fn,
  16840. captionsFn,
  16841. isEndOfTimeline,
  16842. endedTimelineFn,
  16843. dataFn,
  16844. doneFn,
  16845. onTransmuxerLog
  16846. }); // optionally, request the decryption key
  16847. if (segment.key && !segment.key.bytes) {
  16848. const objects = [segment.key];
  16849. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  16850. objects.push(segment.map.key);
  16851. }
  16852. const keyRequestOptions = merge$1(xhrOptions, {
  16853. uri: segment.key.resolvedUri,
  16854. responseType: 'arraybuffer'
  16855. });
  16856. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  16857. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  16858. activeXhrs.push(keyXhr);
  16859. } // optionally, request the associated media init segment
  16860. if (segment.map && !segment.map.bytes) {
  16861. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  16862. if (differentMapKey) {
  16863. const mapKeyRequestOptions = merge$1(xhrOptions, {
  16864. uri: segment.map.key.resolvedUri,
  16865. responseType: 'arraybuffer'
  16866. });
  16867. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  16868. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  16869. activeXhrs.push(mapKeyXhr);
  16870. }
  16871. const initSegmentOptions = merge$1(xhrOptions, {
  16872. uri: segment.map.resolvedUri,
  16873. responseType: 'arraybuffer',
  16874. headers: segmentXhrHeaders(segment.map)
  16875. });
  16876. const initSegmentRequestCallback = handleInitSegmentResponse({
  16877. segment,
  16878. finishProcessingFn
  16879. });
  16880. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  16881. activeXhrs.push(initSegmentXhr);
  16882. }
  16883. const segmentRequestOptions = merge$1(xhrOptions, {
  16884. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  16885. responseType: 'arraybuffer',
  16886. headers: segmentXhrHeaders(segment)
  16887. });
  16888. const segmentRequestCallback = handleSegmentResponse({
  16889. segment,
  16890. finishProcessingFn,
  16891. responseType: segmentRequestOptions.responseType
  16892. });
  16893. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  16894. segmentXhr.addEventListener('progress', handleProgress({
  16895. segment,
  16896. progressFn,
  16897. trackInfoFn,
  16898. timingInfoFn,
  16899. videoSegmentTimingInfoFn,
  16900. audioSegmentTimingInfoFn,
  16901. id3Fn,
  16902. captionsFn,
  16903. isEndOfTimeline,
  16904. endedTimelineFn,
  16905. dataFn
  16906. }));
  16907. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  16908. // multiple times, provide a shared state object
  16909. const loadendState = {};
  16910. activeXhrs.forEach(activeXhr => {
  16911. activeXhr.addEventListener('loadend', handleLoadEnd({
  16912. loadendState,
  16913. abortFn
  16914. }));
  16915. });
  16916. return () => abortAll(activeXhrs);
  16917. };
  16918. /**
  16919. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  16920. * codec strings, or translating codec strings into objects that can be examined.
  16921. */
  16922. const logFn$1 = logger('CodecUtils');
  16923. /**
  16924. * Returns a set of codec strings parsed from the playlist or the default
  16925. * codec strings if no codecs were specified in the playlist
  16926. *
  16927. * @param {Playlist} media the current media playlist
  16928. * @return {Object} an object with the video and audio codecs
  16929. */
  16930. const getCodecs = function (media) {
  16931. // if the codecs were explicitly specified, use them instead of the
  16932. // defaults
  16933. const mediaAttributes = media.attributes || {};
  16934. if (mediaAttributes.CODECS) {
  16935. return parseCodecs(mediaAttributes.CODECS);
  16936. }
  16937. };
  16938. const isMaat = (main, media) => {
  16939. const mediaAttributes = media.attributes || {};
  16940. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  16941. };
  16942. const isMuxed = (main, media) => {
  16943. if (!isMaat(main, media)) {
  16944. return true;
  16945. }
  16946. const mediaAttributes = media.attributes || {};
  16947. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  16948. for (const groupId in audioGroup) {
  16949. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  16950. // or there are listed playlists (the case for DASH, as the manifest will have already
  16951. // provided all of the details necessary to generate the audio playlist, as opposed to
  16952. // HLS' externally requested playlists), then the content is demuxed.
  16953. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  16954. return true;
  16955. }
  16956. }
  16957. return false;
  16958. };
  16959. const unwrapCodecList = function (codecList) {
  16960. const codecs = {};
  16961. codecList.forEach(({
  16962. mediaType,
  16963. type,
  16964. details
  16965. }) => {
  16966. codecs[mediaType] = codecs[mediaType] || [];
  16967. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  16968. });
  16969. Object.keys(codecs).forEach(function (mediaType) {
  16970. if (codecs[mediaType].length > 1) {
  16971. logFn$1(`multiple ${mediaType} codecs found as attributes: ${codecs[mediaType].join(', ')}. Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.`);
  16972. codecs[mediaType] = null;
  16973. return;
  16974. }
  16975. codecs[mediaType] = codecs[mediaType][0];
  16976. });
  16977. return codecs;
  16978. };
  16979. const codecCount = function (codecObj) {
  16980. let count = 0;
  16981. if (codecObj.audio) {
  16982. count++;
  16983. }
  16984. if (codecObj.video) {
  16985. count++;
  16986. }
  16987. return count;
  16988. };
  16989. /**
  16990. * Calculates the codec strings for a working configuration of
  16991. * SourceBuffers to play variant streams in a main playlist. If
  16992. * there is no possible working configuration, an empty object will be
  16993. * returned.
  16994. *
  16995. * @param main {Object} the m3u8 object for the main playlist
  16996. * @param media {Object} the m3u8 object for the variant playlist
  16997. * @return {Object} the codec strings.
  16998. *
  16999. * @private
  17000. */
  17001. const codecsForPlaylist = function (main, media) {
  17002. const mediaAttributes = media.attributes || {};
  17003. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  17004. // Put another way, there is no way to have a video-only multiple-audio HLS!
  17005. if (isMaat(main, media) && !codecInfo.audio) {
  17006. if (!isMuxed(main, media)) {
  17007. // It is possible for codecs to be specified on the audio media group playlist but
  17008. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  17009. // video are always separate (and separately specified).
  17010. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  17011. if (defaultCodecs.audio) {
  17012. codecInfo.audio = defaultCodecs.audio;
  17013. }
  17014. }
  17015. }
  17016. return codecInfo;
  17017. };
  17018. const logFn = logger('PlaylistSelector');
  17019. const representationToString = function (representation) {
  17020. if (!representation || !representation.playlist) {
  17021. return;
  17022. }
  17023. const playlist = representation.playlist;
  17024. return JSON.stringify({
  17025. id: playlist.id,
  17026. bandwidth: representation.bandwidth,
  17027. width: representation.width,
  17028. height: representation.height,
  17029. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  17030. });
  17031. }; // Utilities
  17032. /**
  17033. * Returns the CSS value for the specified property on an element
  17034. * using `getComputedStyle`. Firefox has a long-standing issue where
  17035. * getComputedStyle() may return null when running in an iframe with
  17036. * `display: none`.
  17037. *
  17038. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  17039. * @param {HTMLElement} el the htmlelement to work on
  17040. * @param {string} the proprety to get the style for
  17041. */
  17042. const safeGetComputedStyle = function (el, property) {
  17043. if (!el) {
  17044. return '';
  17045. }
  17046. const result = window.getComputedStyle(el);
  17047. if (!result) {
  17048. return '';
  17049. }
  17050. return result[property];
  17051. };
  17052. /**
  17053. * Resuable stable sort function
  17054. *
  17055. * @param {Playlists} array
  17056. * @param {Function} sortFn Different comparators
  17057. * @function stableSort
  17058. */
  17059. const stableSort = function (array, sortFn) {
  17060. const newArray = array.slice();
  17061. array.sort(function (left, right) {
  17062. const cmp = sortFn(left, right);
  17063. if (cmp === 0) {
  17064. return newArray.indexOf(left) - newArray.indexOf(right);
  17065. }
  17066. return cmp;
  17067. });
  17068. };
  17069. /**
  17070. * A comparator function to sort two playlist object by bandwidth.
  17071. *
  17072. * @param {Object} left a media playlist object
  17073. * @param {Object} right a media playlist object
  17074. * @return {number} Greater than zero if the bandwidth attribute of
  17075. * left is greater than the corresponding attribute of right. Less
  17076. * than zero if the bandwidth of right is greater than left and
  17077. * exactly zero if the two are equal.
  17078. */
  17079. const comparePlaylistBandwidth = function (left, right) {
  17080. let leftBandwidth;
  17081. let rightBandwidth;
  17082. if (left.attributes.BANDWIDTH) {
  17083. leftBandwidth = left.attributes.BANDWIDTH;
  17084. }
  17085. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  17086. if (right.attributes.BANDWIDTH) {
  17087. rightBandwidth = right.attributes.BANDWIDTH;
  17088. }
  17089. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  17090. return leftBandwidth - rightBandwidth;
  17091. };
  17092. /**
  17093. * A comparator function to sort two playlist object by resolution (width).
  17094. *
  17095. * @param {Object} left a media playlist object
  17096. * @param {Object} right a media playlist object
  17097. * @return {number} Greater than zero if the resolution.width attribute of
  17098. * left is greater than the corresponding attribute of right. Less
  17099. * than zero if the resolution.width of right is greater than left and
  17100. * exactly zero if the two are equal.
  17101. */
  17102. const comparePlaylistResolution = function (left, right) {
  17103. let leftWidth;
  17104. let rightWidth;
  17105. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  17106. leftWidth = left.attributes.RESOLUTION.width;
  17107. }
  17108. leftWidth = leftWidth || window.Number.MAX_VALUE;
  17109. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  17110. rightWidth = right.attributes.RESOLUTION.width;
  17111. }
  17112. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  17113. // have the same media dimensions/ resolution
  17114. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  17115. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  17116. }
  17117. return leftWidth - rightWidth;
  17118. };
  17119. /**
  17120. * Chooses the appropriate media playlist based on bandwidth and player size
  17121. *
  17122. * @param {Object} main
  17123. * Object representation of the main manifest
  17124. * @param {number} playerBandwidth
  17125. * Current calculated bandwidth of the player
  17126. * @param {number} playerWidth
  17127. * Current width of the player element (should account for the device pixel ratio)
  17128. * @param {number} playerHeight
  17129. * Current height of the player element (should account for the device pixel ratio)
  17130. * @param {boolean} limitRenditionByPlayerDimensions
  17131. * True if the player width and height should be used during the selection, false otherwise
  17132. * @param {Object} playlistController
  17133. * the current playlistController object
  17134. * @return {Playlist} the highest bitrate playlist less than the
  17135. * currently detected bandwidth, accounting for some amount of
  17136. * bandwidth variance
  17137. */
  17138. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  17139. // If we end up getting called before `main` is available, exit early
  17140. if (!main) {
  17141. return;
  17142. }
  17143. const options = {
  17144. bandwidth: playerBandwidth,
  17145. width: playerWidth,
  17146. height: playerHeight,
  17147. limitRenditionByPlayerDimensions
  17148. };
  17149. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  17150. if (Playlist.isAudioOnly(main)) {
  17151. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  17152. // at the buttom of this function for debugging.
  17153. options.audioOnly = true;
  17154. } // convert the playlists to an intermediary representation to make comparisons easier
  17155. let sortedPlaylistReps = playlists.map(playlist => {
  17156. let bandwidth;
  17157. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  17158. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  17159. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  17160. bandwidth = bandwidth || window.Number.MAX_VALUE;
  17161. return {
  17162. bandwidth,
  17163. width,
  17164. height,
  17165. playlist
  17166. };
  17167. });
  17168. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  17169. // incompatible configurations
  17170. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  17171. // api or excluded temporarily due to playback errors.
  17172. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  17173. if (!enabledPlaylistReps.length) {
  17174. // if there are no enabled playlists, then they have all been excluded or disabled
  17175. // by the user through the representations api. In this case, ignore exclusion and
  17176. // fallback to what the user wants by using playlists the user has not disabled.
  17177. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  17178. } // filter out any variant that has greater effective bitrate
  17179. // than the current estimated bandwidth
  17180. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  17181. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  17182. // and then taking the very first element
  17183. const bandwidthBestRep = bandwidthPlaylistReps.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0]; // if we're not going to limit renditions by player size, make an early decision.
  17184. if (limitRenditionByPlayerDimensions === false) {
  17185. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  17186. if (chosenRep && chosenRep.playlist) {
  17187. let type = 'sortedPlaylistReps';
  17188. if (bandwidthBestRep) {
  17189. type = 'bandwidthBestRep';
  17190. }
  17191. if (enabledPlaylistReps[0]) {
  17192. type = 'enabledPlaylistReps';
  17193. }
  17194. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  17195. return chosenRep.playlist;
  17196. }
  17197. logFn('could not choose a playlist with options', options);
  17198. return null;
  17199. } // filter out playlists without resolution information
  17200. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  17201. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  17202. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  17203. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  17204. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  17205. let resolutionPlusOneList;
  17206. let resolutionPlusOneSmallest;
  17207. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  17208. // if there is no match of exact resolution
  17209. if (!resolutionBestRep) {
  17210. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  17211. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  17212. // is just-larger-than the video player
  17213. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  17214. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  17215. }
  17216. let leastPixelDiffRep; // If this selector proves to be better than others,
  17217. // resolutionPlusOneRep and resolutionBestRep and all
  17218. // the code involving them should be removed.
  17219. if (playlistController.leastPixelDiffSelector) {
  17220. // find the variant that is closest to the player's pixel size
  17221. const leastPixelDiffList = haveResolution.map(rep => {
  17222. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  17223. return rep;
  17224. }); // get the highest bandwidth, closest resolution playlist
  17225. stableSort(leastPixelDiffList, (left, right) => {
  17226. // sort by highest bandwidth if pixelDiff is the same
  17227. if (left.pixelDiff === right.pixelDiff) {
  17228. return right.bandwidth - left.bandwidth;
  17229. }
  17230. return left.pixelDiff - right.pixelDiff;
  17231. });
  17232. leastPixelDiffRep = leastPixelDiffList[0];
  17233. } // fallback chain of variants
  17234. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  17235. if (chosenRep && chosenRep.playlist) {
  17236. let type = 'sortedPlaylistReps';
  17237. if (leastPixelDiffRep) {
  17238. type = 'leastPixelDiffRep';
  17239. } else if (resolutionPlusOneRep) {
  17240. type = 'resolutionPlusOneRep';
  17241. } else if (resolutionBestRep) {
  17242. type = 'resolutionBestRep';
  17243. } else if (bandwidthBestRep) {
  17244. type = 'bandwidthBestRep';
  17245. } else if (enabledPlaylistReps[0]) {
  17246. type = 'enabledPlaylistReps';
  17247. }
  17248. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  17249. return chosenRep.playlist;
  17250. }
  17251. logFn('could not choose a playlist with options', options);
  17252. return null;
  17253. };
  17254. /**
  17255. * Chooses the appropriate media playlist based on the most recent
  17256. * bandwidth estimate and the player size.
  17257. *
  17258. * Expects to be called within the context of an instance of VhsHandler
  17259. *
  17260. * @return {Playlist} the highest bitrate playlist less than the
  17261. * currently detected bandwidth, accounting for some amount of
  17262. * bandwidth variance
  17263. */
  17264. const lastBandwidthSelector = function () {
  17265. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  17266. return simpleSelector(this.playlists.main, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  17267. };
  17268. /**
  17269. * Chooses the appropriate media playlist based on an
  17270. * exponential-weighted moving average of the bandwidth after
  17271. * filtering for player size.
  17272. *
  17273. * Expects to be called within the context of an instance of VhsHandler
  17274. *
  17275. * @param {number} decay - a number between 0 and 1. Higher values of
  17276. * this parameter will cause previous bandwidth estimates to lose
  17277. * significance more quickly.
  17278. * @return {Function} a function which can be invoked to create a new
  17279. * playlist selector function.
  17280. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  17281. */
  17282. const movingAverageBandwidthSelector = function (decay) {
  17283. let average = -1;
  17284. let lastSystemBandwidth = -1;
  17285. if (decay < 0 || decay > 1) {
  17286. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  17287. }
  17288. return function () {
  17289. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  17290. if (average < 0) {
  17291. average = this.systemBandwidth;
  17292. lastSystemBandwidth = this.systemBandwidth;
  17293. } // stop the average value from decaying for every 250ms
  17294. // when the systemBandwidth is constant
  17295. // and
  17296. // stop average from setting to a very low value when the
  17297. // systemBandwidth becomes 0 in case of chunk cancellation
  17298. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  17299. average = decay * this.systemBandwidth + (1 - decay) * average;
  17300. lastSystemBandwidth = this.systemBandwidth;
  17301. }
  17302. return simpleSelector(this.playlists.main, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.playlistController_);
  17303. };
  17304. };
  17305. /**
  17306. * Chooses the appropriate media playlist based on the potential to rebuffer
  17307. *
  17308. * @param {Object} settings
  17309. * Object of information required to use this selector
  17310. * @param {Object} settings.main
  17311. * Object representation of the main manifest
  17312. * @param {number} settings.currentTime
  17313. * The current time of the player
  17314. * @param {number} settings.bandwidth
  17315. * Current measured bandwidth
  17316. * @param {number} settings.duration
  17317. * Duration of the media
  17318. * @param {number} settings.segmentDuration
  17319. * Segment duration to be used in round trip time calculations
  17320. * @param {number} settings.timeUntilRebuffer
  17321. * Time left in seconds until the player has to rebuffer
  17322. * @param {number} settings.currentTimeline
  17323. * The current timeline segments are being loaded from
  17324. * @param {SyncController} settings.syncController
  17325. * SyncController for determining if we have a sync point for a given playlist
  17326. * @return {Object|null}
  17327. * {Object} return.playlist
  17328. * The highest bandwidth playlist with the least amount of rebuffering
  17329. * {Number} return.rebufferingImpact
  17330. * The amount of time in seconds switching to this playlist will rebuffer. A
  17331. * negative value means that switching will cause zero rebuffering.
  17332. */
  17333. const minRebufferMaxBandwidthSelector = function (settings) {
  17334. const {
  17335. main,
  17336. currentTime,
  17337. bandwidth,
  17338. duration,
  17339. segmentDuration,
  17340. timeUntilRebuffer,
  17341. currentTimeline,
  17342. syncController
  17343. } = settings; // filter out any playlists that have been excluded due to
  17344. // incompatible configurations
  17345. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  17346. // api or excluded temporarily due to playback errors.
  17347. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  17348. if (!enabledPlaylists.length) {
  17349. // if there are no enabled playlists, then they have all been excluded or disabled
  17350. // by the user through the representations api. In this case, ignore exclusion and
  17351. // fallback to what the user wants by using playlists the user has not disabled.
  17352. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  17353. }
  17354. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  17355. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  17356. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  17357. // sync request first. This will double the request time
  17358. const numRequests = syncPoint ? 1 : 2;
  17359. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  17360. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  17361. return {
  17362. playlist,
  17363. rebufferingImpact
  17364. };
  17365. });
  17366. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  17367. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  17368. if (noRebufferingPlaylists.length) {
  17369. return noRebufferingPlaylists[0];
  17370. }
  17371. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  17372. return rebufferingEstimates[0] || null;
  17373. };
  17374. /**
  17375. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  17376. * one with video. If no renditions with video exist, return the lowest audio rendition.
  17377. *
  17378. * Expects to be called within the context of an instance of VhsHandler
  17379. *
  17380. * @return {Object|null}
  17381. * {Object} return.playlist
  17382. * The lowest bitrate playlist that contains a video codec. If no such rendition
  17383. * exists pick the lowest audio rendition.
  17384. */
  17385. const lowestBitrateCompatibleVariantSelector = function () {
  17386. // filter out any playlists that have been excluded due to
  17387. // incompatible configurations or playback errors
  17388. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  17389. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  17390. // (this is not necessarily true, although it is generally true).
  17391. //
  17392. // If an entire manifest has no valid videos everything will get filtered
  17393. // out.
  17394. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  17395. return playlistsWithVideo[0] || null;
  17396. };
  17397. /**
  17398. * Combine all segments into a single Uint8Array
  17399. *
  17400. * @param {Object} segmentObj
  17401. * @return {Uint8Array} concatenated bytes
  17402. * @private
  17403. */
  17404. const concatSegments = segmentObj => {
  17405. let offset = 0;
  17406. let tempBuffer;
  17407. if (segmentObj.bytes) {
  17408. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  17409. segmentObj.segments.forEach(segment => {
  17410. tempBuffer.set(segment, offset);
  17411. offset += segment.byteLength;
  17412. });
  17413. }
  17414. return tempBuffer;
  17415. };
  17416. /**
  17417. * @file text-tracks.js
  17418. */
  17419. /**
  17420. * Create captions text tracks on video.js if they do not exist
  17421. *
  17422. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  17423. * @param {Object} tech the video.js tech
  17424. * @param {Object} captionStream the caption stream to create
  17425. * @private
  17426. */
  17427. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  17428. if (!inbandTextTracks[captionStream]) {
  17429. tech.trigger({
  17430. type: 'usage',
  17431. name: 'vhs-608'
  17432. });
  17433. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  17434. if (/^cc708_/.test(captionStream)) {
  17435. instreamId = 'SERVICE' + captionStream.split('_')[1];
  17436. }
  17437. const track = tech.textTracks().getTrackById(instreamId);
  17438. if (track) {
  17439. // Resuse an existing track with a CC# id because this was
  17440. // very likely created by videojs-contrib-hls from information
  17441. // in the m3u8 for us to use
  17442. inbandTextTracks[captionStream] = track;
  17443. } else {
  17444. // This section gets called when we have caption services that aren't specified in the manifest.
  17445. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  17446. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  17447. let label = captionStream;
  17448. let language = captionStream;
  17449. let def = false;
  17450. const captionService = captionServices[instreamId];
  17451. if (captionService) {
  17452. label = captionService.label;
  17453. language = captionService.language;
  17454. def = captionService.default;
  17455. } // Otherwise, create a track with the default `CC#` label and
  17456. // without a language
  17457. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  17458. kind: 'captions',
  17459. id: instreamId,
  17460. // TODO: investigate why this doesn't seem to turn the caption on by default
  17461. default: def,
  17462. label,
  17463. language
  17464. }, false).track;
  17465. }
  17466. }
  17467. };
  17468. /**
  17469. * Add caption text track data to a source handler given an array of captions
  17470. *
  17471. * @param {Object}
  17472. * @param {Object} inbandTextTracks the inband text tracks
  17473. * @param {number} timestampOffset the timestamp offset of the source buffer
  17474. * @param {Array} captionArray an array of caption data
  17475. * @private
  17476. */
  17477. const addCaptionData = function ({
  17478. inbandTextTracks,
  17479. captionArray,
  17480. timestampOffset
  17481. }) {
  17482. if (!captionArray) {
  17483. return;
  17484. }
  17485. const Cue = window.WebKitDataCue || window.VTTCue;
  17486. captionArray.forEach(caption => {
  17487. const track = caption.stream;
  17488. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  17489. });
  17490. };
  17491. /**
  17492. * Define properties on a cue for backwards compatability,
  17493. * but warn the user that the way that they are using it
  17494. * is depricated and will be removed at a later date.
  17495. *
  17496. * @param {Cue} cue the cue to add the properties on
  17497. * @private
  17498. */
  17499. const deprecateOldCue = function (cue) {
  17500. Object.defineProperties(cue.frame, {
  17501. id: {
  17502. get() {
  17503. videojs__default["default"].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  17504. return cue.value.key;
  17505. }
  17506. },
  17507. value: {
  17508. get() {
  17509. videojs__default["default"].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  17510. return cue.value.data;
  17511. }
  17512. },
  17513. privateData: {
  17514. get() {
  17515. videojs__default["default"].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  17516. return cue.value.data;
  17517. }
  17518. }
  17519. });
  17520. };
  17521. /**
  17522. * Add metadata text track data to a source handler given an array of metadata
  17523. *
  17524. * @param {Object}
  17525. * @param {Object} inbandTextTracks the inband text tracks
  17526. * @param {Array} metadataArray an array of meta data
  17527. * @param {number} timestampOffset the timestamp offset of the source buffer
  17528. * @param {number} videoDuration the duration of the video
  17529. * @private
  17530. */
  17531. const addMetadata = ({
  17532. inbandTextTracks,
  17533. metadataArray,
  17534. timestampOffset,
  17535. videoDuration
  17536. }) => {
  17537. if (!metadataArray) {
  17538. return;
  17539. }
  17540. const Cue = window.WebKitDataCue || window.VTTCue;
  17541. const metadataTrack = inbandTextTracks.metadataTrack_;
  17542. if (!metadataTrack) {
  17543. return;
  17544. }
  17545. metadataArray.forEach(metadata => {
  17546. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  17547. // ignore this bit of metadata.
  17548. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  17549. // which is the "Title/Songname/Content description" frame
  17550. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  17551. return;
  17552. }
  17553. metadata.frames.forEach(frame => {
  17554. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  17555. cue.frame = frame;
  17556. cue.value = frame;
  17557. deprecateOldCue(cue);
  17558. metadataTrack.addCue(cue);
  17559. });
  17560. });
  17561. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  17562. return;
  17563. } // Updating the metadeta cues so that
  17564. // the endTime of each cue is the startTime of the next cue
  17565. // the endTime of last cue is the duration of the video
  17566. const cues = metadataTrack.cues;
  17567. const cuesArray = []; // Create a copy of the TextTrackCueList...
  17568. // ...disregarding cues with a falsey value
  17569. for (let i = 0; i < cues.length; i++) {
  17570. if (cues[i]) {
  17571. cuesArray.push(cues[i]);
  17572. }
  17573. } // Group cues by their startTime value
  17574. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  17575. const timeSlot = obj[cue.startTime] || [];
  17576. timeSlot.push(cue);
  17577. obj[cue.startTime] = timeSlot;
  17578. return obj;
  17579. }, {}); // Sort startTimes by ascending order
  17580. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  17581. sortedStartTimes.forEach((startTime, idx) => {
  17582. const cueGroup = cuesGroupedByStartTime[startTime];
  17583. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  17584. cueGroup.forEach(cue => {
  17585. cue.endTime = nextTime;
  17586. });
  17587. });
  17588. };
  17589. /**
  17590. * Create metadata text track on video.js if it does not exist
  17591. *
  17592. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  17593. * @param {string} dispatchType the inband metadata track dispatch type
  17594. * @param {Object} tech the video.js tech
  17595. * @private
  17596. */
  17597. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  17598. if (inbandTextTracks.metadataTrack_) {
  17599. return;
  17600. }
  17601. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  17602. kind: 'metadata',
  17603. label: 'Timed Metadata'
  17604. }, false).track;
  17605. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  17606. };
  17607. /**
  17608. * Remove cues from a track on video.js.
  17609. *
  17610. * @param {Double} start start of where we should remove the cue
  17611. * @param {Double} end end of where the we should remove the cue
  17612. * @param {Object} track the text track to remove the cues from
  17613. * @private
  17614. */
  17615. const removeCuesFromTrack = function (start, end, track) {
  17616. let i;
  17617. let cue;
  17618. if (!track) {
  17619. return;
  17620. }
  17621. if (!track.cues) {
  17622. return;
  17623. }
  17624. i = track.cues.length;
  17625. while (i--) {
  17626. cue = track.cues[i]; // Remove any cue within the provided start and end time
  17627. if (cue.startTime >= start && cue.endTime <= end) {
  17628. track.removeCue(cue);
  17629. }
  17630. }
  17631. };
  17632. /**
  17633. * Remove duplicate cues from a track on video.js (a cue is considered a
  17634. * duplicate if it has the same time interval and text as another)
  17635. *
  17636. * @param {Object} track the text track to remove the duplicate cues from
  17637. * @private
  17638. */
  17639. const removeDuplicateCuesFromTrack = function (track) {
  17640. const cues = track.cues;
  17641. if (!cues) {
  17642. return;
  17643. }
  17644. for (let i = 0; i < cues.length; i++) {
  17645. const duplicates = [];
  17646. let occurrences = 0;
  17647. for (let j = 0; j < cues.length; j++) {
  17648. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  17649. occurrences++;
  17650. if (occurrences > 1) {
  17651. duplicates.push(cues[j]);
  17652. }
  17653. }
  17654. }
  17655. if (duplicates.length) {
  17656. duplicates.forEach(dupe => track.removeCue(dupe));
  17657. }
  17658. }
  17659. };
  17660. /**
  17661. * mux.js
  17662. *
  17663. * Copyright (c) Brightcove
  17664. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  17665. */
  17666. var ONE_SECOND_IN_TS = 90000,
  17667. // 90kHz clock
  17668. secondsToVideoTs,
  17669. secondsToAudioTs,
  17670. videoTsToSeconds,
  17671. audioTsToSeconds,
  17672. audioTsToVideoTs,
  17673. videoTsToAudioTs,
  17674. metadataTsToSeconds;
  17675. secondsToVideoTs = function (seconds) {
  17676. return seconds * ONE_SECOND_IN_TS;
  17677. };
  17678. secondsToAudioTs = function (seconds, sampleRate) {
  17679. return seconds * sampleRate;
  17680. };
  17681. videoTsToSeconds = function (timestamp) {
  17682. return timestamp / ONE_SECOND_IN_TS;
  17683. };
  17684. audioTsToSeconds = function (timestamp, sampleRate) {
  17685. return timestamp / sampleRate;
  17686. };
  17687. audioTsToVideoTs = function (timestamp, sampleRate) {
  17688. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  17689. };
  17690. videoTsToAudioTs = function (timestamp, sampleRate) {
  17691. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  17692. };
  17693. /**
  17694. * Adjust ID3 tag or caption timing information by the timeline pts values
  17695. * (if keepOriginalTimestamps is false) and convert to seconds
  17696. */
  17697. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  17698. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  17699. };
  17700. var clock = {
  17701. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  17702. secondsToVideoTs: secondsToVideoTs,
  17703. secondsToAudioTs: secondsToAudioTs,
  17704. videoTsToSeconds: videoTsToSeconds,
  17705. audioTsToSeconds: audioTsToSeconds,
  17706. audioTsToVideoTs: audioTsToVideoTs,
  17707. videoTsToAudioTs: videoTsToAudioTs,
  17708. metadataTsToSeconds: metadataTsToSeconds
  17709. };
  17710. /**
  17711. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  17712. * front of current time.
  17713. *
  17714. * @param {Array} buffer
  17715. * The current buffer of gop information
  17716. * @param {number} currentTime
  17717. * The current time
  17718. * @param {Double} mapping
  17719. * Offset to map display time to stream presentation time
  17720. * @return {Array}
  17721. * List of gops considered safe to append over
  17722. */
  17723. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  17724. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  17725. return [];
  17726. } // pts value for current time + 3 seconds to give a bit more wiggle room
  17727. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  17728. let i;
  17729. for (i = 0; i < buffer.length; i++) {
  17730. if (buffer[i].pts > currentTimePts) {
  17731. break;
  17732. }
  17733. }
  17734. return buffer.slice(i);
  17735. };
  17736. /**
  17737. * Appends gop information (timing and byteLength) received by the transmuxer for the
  17738. * gops appended in the last call to appendBuffer
  17739. *
  17740. * @param {Array} buffer
  17741. * The current buffer of gop information
  17742. * @param {Array} gops
  17743. * List of new gop information
  17744. * @param {boolean} replace
  17745. * If true, replace the buffer with the new gop information. If false, append the
  17746. * new gop information to the buffer in the right location of time.
  17747. * @return {Array}
  17748. * Updated list of gop information
  17749. */
  17750. const updateGopBuffer = (buffer, gops, replace) => {
  17751. if (!gops.length) {
  17752. return buffer;
  17753. }
  17754. if (replace) {
  17755. // If we are in safe append mode, then completely overwrite the gop buffer
  17756. // with the most recent appeneded data. This will make sure that when appending
  17757. // future segments, we only try to align with gops that are both ahead of current
  17758. // time and in the last segment appended.
  17759. return gops.slice();
  17760. }
  17761. const start = gops[0].pts;
  17762. let i = 0;
  17763. for (i; i < buffer.length; i++) {
  17764. if (buffer[i].pts >= start) {
  17765. break;
  17766. }
  17767. }
  17768. return buffer.slice(0, i).concat(gops);
  17769. };
  17770. /**
  17771. * Removes gop information in buffer that overlaps with provided start and end
  17772. *
  17773. * @param {Array} buffer
  17774. * The current buffer of gop information
  17775. * @param {Double} start
  17776. * position to start the remove at
  17777. * @param {Double} end
  17778. * position to end the remove at
  17779. * @param {Double} mapping
  17780. * Offset to map display time to stream presentation time
  17781. */
  17782. const removeGopBuffer = (buffer, start, end, mapping) => {
  17783. const startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  17784. const endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  17785. const updatedBuffer = buffer.slice();
  17786. let i = buffer.length;
  17787. while (i--) {
  17788. if (buffer[i].pts <= endPts) {
  17789. break;
  17790. }
  17791. }
  17792. if (i === -1) {
  17793. // no removal because end of remove range is before start of buffer
  17794. return updatedBuffer;
  17795. }
  17796. let j = i + 1;
  17797. while (j--) {
  17798. if (buffer[j].pts <= startPts) {
  17799. break;
  17800. }
  17801. } // clamp remove range start to 0 index
  17802. j = Math.max(j, 0);
  17803. updatedBuffer.splice(j, i - j + 1);
  17804. return updatedBuffer;
  17805. };
  17806. const shallowEqual = function (a, b) {
  17807. // if both are undefined
  17808. // or one or the other is undefined
  17809. // they are not equal
  17810. if (!a && !b || !a && b || a && !b) {
  17811. return false;
  17812. } // they are the same object and thus, equal
  17813. if (a === b) {
  17814. return true;
  17815. } // sort keys so we can make sure they have
  17816. // all the same keys later.
  17817. const akeys = Object.keys(a).sort();
  17818. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  17819. if (akeys.length !== bkeys.length) {
  17820. return false;
  17821. }
  17822. for (let i = 0; i < akeys.length; i++) {
  17823. const key = akeys[i]; // different sorted keys, not equal
  17824. if (key !== bkeys[i]) {
  17825. return false;
  17826. } // different values, not equal
  17827. if (a[key] !== b[key]) {
  17828. return false;
  17829. }
  17830. }
  17831. return true;
  17832. };
  17833. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  17834. const QUOTA_EXCEEDED_ERR = 22;
  17835. /**
  17836. * The segment loader has no recourse except to fetch a segment in the
  17837. * current playlist and use the internal timestamps in that segment to
  17838. * generate a syncPoint. This function returns a good candidate index
  17839. * for that process.
  17840. *
  17841. * @param {Array} segments - the segments array from a playlist.
  17842. * @return {number} An index of a segment from the playlist to load
  17843. */
  17844. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  17845. segments = segments || [];
  17846. const timelineSegments = [];
  17847. let time = 0;
  17848. for (let i = 0; i < segments.length; i++) {
  17849. const segment = segments[i];
  17850. if (currentTimeline === segment.timeline) {
  17851. timelineSegments.push(i);
  17852. time += segment.duration;
  17853. if (time > targetTime) {
  17854. return i;
  17855. }
  17856. }
  17857. }
  17858. if (timelineSegments.length === 0) {
  17859. return 0;
  17860. } // default to the last timeline segment
  17861. return timelineSegments[timelineSegments.length - 1];
  17862. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  17863. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  17864. // as a start to prevent any potential issues with removing content too close to the
  17865. // playhead.
  17866. const MIN_BACK_BUFFER = 1; // in ms
  17867. const CHECK_BUFFER_DELAY = 500;
  17868. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  17869. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  17870. // not accurately reflect the rest of the content.
  17871. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  17872. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  17873. // Although these checks should most likely cover non 'main' types, for now it narrows
  17874. // the scope of our checks.
  17875. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  17876. return null;
  17877. }
  17878. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  17879. return 'Neither audio nor video found in segment.';
  17880. }
  17881. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  17882. return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
  17883. }
  17884. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  17885. return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
  17886. }
  17887. return null;
  17888. };
  17889. /**
  17890. * Calculates a time value that is safe to remove from the back buffer without interrupting
  17891. * playback.
  17892. *
  17893. * @param {TimeRange} seekable
  17894. * The current seekable range
  17895. * @param {number} currentTime
  17896. * The current time of the player
  17897. * @param {number} targetDuration
  17898. * The target duration of the current playlist
  17899. * @return {number}
  17900. * Time that is safe to remove from the back buffer without interrupting playback
  17901. */
  17902. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  17903. // 30 seconds before the playhead provides a safe default for trimming.
  17904. //
  17905. // Choosing a reasonable default is particularly important for high bitrate content and
  17906. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  17907. // throw an APPEND_BUFFER_ERR.
  17908. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  17909. if (seekable.length) {
  17910. // Some live playlists may have a shorter window of content than the full allowed back
  17911. // buffer. For these playlists, don't save content that's no longer within the window.
  17912. trimTime = Math.max(trimTime, seekable.start(0));
  17913. } // Don't remove within target duration of the current time to avoid the possibility of
  17914. // removing the GOP currently being played, as removing it can cause playback stalls.
  17915. const maxTrimTime = currentTime - targetDuration;
  17916. return Math.min(maxTrimTime, trimTime);
  17917. };
  17918. const segmentInfoString = segmentInfo => {
  17919. const {
  17920. startOfSegment,
  17921. duration,
  17922. segment,
  17923. part,
  17924. playlist: {
  17925. mediaSequence: seq,
  17926. id,
  17927. segments = []
  17928. },
  17929. mediaIndex: index,
  17930. partIndex,
  17931. timeline
  17932. } = segmentInfo;
  17933. const segmentLen = segments.length - 1;
  17934. let selection = 'mediaIndex/partIndex increment';
  17935. if (segmentInfo.getMediaInfoForTime) {
  17936. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  17937. } else if (segmentInfo.isSyncRequest) {
  17938. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  17939. }
  17940. if (segmentInfo.independent) {
  17941. selection += ` with independent ${segmentInfo.independent}`;
  17942. }
  17943. const hasPartIndex = typeof partIndex === 'number';
  17944. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  17945. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  17946. preloadSegment: segment
  17947. }) - 1 : 0;
  17948. return `${name} [${seq + index}/${seq + segmentLen}]` + (hasPartIndex ? ` part [${partIndex}/${zeroBasedPartCount}]` : '') + ` segment start/end [${segment.start} => ${segment.end}]` + (hasPartIndex ? ` part start/end [${part.start} => ${part.end}]` : '') + ` startOfSegment [${startOfSegment}]` + ` duration [${duration}]` + ` timeline [${timeline}]` + ` selected by [${selection}]` + ` playlist [${id}]`;
  17949. };
  17950. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  17951. /**
  17952. * Returns the timestamp offset to use for the segment.
  17953. *
  17954. * @param {number} segmentTimeline
  17955. * The timeline of the segment
  17956. * @param {number} currentTimeline
  17957. * The timeline currently being followed by the loader
  17958. * @param {number} startOfSegment
  17959. * The estimated segment start
  17960. * @param {TimeRange[]} buffered
  17961. * The loader's buffer
  17962. * @param {boolean} overrideCheck
  17963. * If true, no checks are made to see if the timestamp offset value should be set,
  17964. * but sets it directly to a value.
  17965. *
  17966. * @return {number|null}
  17967. * Either a number representing a new timestamp offset, or null if the segment is
  17968. * part of the same timeline
  17969. */
  17970. const timestampOffsetForSegment = ({
  17971. segmentTimeline,
  17972. currentTimeline,
  17973. startOfSegment,
  17974. buffered,
  17975. overrideCheck
  17976. }) => {
  17977. // Check to see if we are crossing a discontinuity to see if we need to set the
  17978. // timestamp offset on the transmuxer and source buffer.
  17979. //
  17980. // Previously, we changed the timestampOffset if the start of this segment was less than
  17981. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  17982. // behavior, especially around long running live streams.
  17983. if (!overrideCheck && segmentTimeline === currentTimeline) {
  17984. return null;
  17985. } // When changing renditions, it's possible to request a segment on an older timeline. For
  17986. // instance, given two renditions with the following:
  17987. //
  17988. // #EXTINF:10
  17989. // segment1
  17990. // #EXT-X-DISCONTINUITY
  17991. // #EXTINF:10
  17992. // segment2
  17993. // #EXTINF:10
  17994. // segment3
  17995. //
  17996. // And the current player state:
  17997. //
  17998. // current time: 8
  17999. // buffer: 0 => 20
  18000. //
  18001. // The next segment on the current rendition would be segment3, filling the buffer from
  18002. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  18003. // then the next segment to be requested will be segment1 from the new rendition in
  18004. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  18005. // content (since it would position segment1 of the new rendition starting at 20s). This
  18006. // case can be identified when the new segment's timeline is a prior value. Instead of
  18007. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  18008. // more accurate to the actual start time of the segment.
  18009. if (segmentTimeline < currentTimeline) {
  18010. return startOfSegment;
  18011. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  18012. // value uses the end of the last segment if it is available. While this value
  18013. // should often be correct, it's better to rely on the buffered end, as the new
  18014. // content post discontinuity should line up with the buffered end as if it were
  18015. // time 0 for the new content.
  18016. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  18017. };
  18018. /**
  18019. * Returns whether or not the loader should wait for a timeline change from the timeline
  18020. * change controller before processing the segment.
  18021. *
  18022. * Primary timing in VHS goes by video. This is different from most media players, as
  18023. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  18024. * will continue to use video as the primary timing source, due to the current logic and
  18025. * expectations built around it.
  18026. * Since the timing follows video, in order to maintain sync, the video loader is
  18027. * responsible for setting both audio and video source buffer timestamp offsets.
  18028. *
  18029. * Setting different values for audio and video source buffers could lead to
  18030. * desyncing. The following examples demonstrate some of the situations where this
  18031. * distinction is important. Note that all of these cases involve demuxed content. When
  18032. * content is muxed, the audio and video are packaged together, therefore syncing
  18033. * separate media playlists is not an issue.
  18034. *
  18035. * CASE 1: Audio prepares to load a new timeline before video:
  18036. *
  18037. * Timeline: 0 1
  18038. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18039. * Audio Loader: ^
  18040. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18041. * Video Loader ^
  18042. *
  18043. * In the above example, the audio loader is preparing to load the 6th segment, the first
  18044. * after a discontinuity, while the video loader is still loading the 5th segment, before
  18045. * the discontinuity.
  18046. *
  18047. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  18048. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  18049. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  18050. * the audio loader must provide the audioAppendStart value to trim the content in the
  18051. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  18052. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  18053. * segment until that value is provided.
  18054. *
  18055. * CASE 2: Video prepares to load a new timeline before audio:
  18056. *
  18057. * Timeline: 0 1
  18058. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18059. * Audio Loader: ^
  18060. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18061. * Video Loader ^
  18062. *
  18063. * In the above example, the video loader is preparing to load the 6th segment, the first
  18064. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  18065. * the discontinuity.
  18066. *
  18067. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  18068. * segment is loaded and processed, both the video and audio timestamp offsets will be
  18069. * set, since video is used as the primary timing source. This is to ensure content lines
  18070. * up appropriately, as any modifications to the video timing are reflected by audio when
  18071. * the video loader sets the audio and video timestamp offsets to the same value. However,
  18072. * setting the timestamp offset for audio before audio has had a chance to change
  18073. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  18074. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  18075. *
  18076. * CASE 3: When seeking, audio prepares to load a new timeline before video
  18077. *
  18078. * Timeline: 0 1
  18079. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18080. * Audio Loader: ^
  18081. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18082. * Video Loader ^
  18083. *
  18084. * In the above example, both audio and video loaders are loading segments from timeline
  18085. * 0, but imagine that the seek originated from timeline 1.
  18086. *
  18087. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  18088. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  18089. * must wait for the video loader to load its segment and update both the audio and video
  18090. * timestamp offsets before it may load and append its own segment. This is the case
  18091. * whether the seek results in a mismatched segment request (e.g., the audio loader
  18092. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  18093. * loaders choose to load the same segment index from each playlist, as the segments may
  18094. * not be aligned perfectly, even for matching segment indexes.
  18095. *
  18096. * @param {Object} timelinechangeController
  18097. * @param {number} currentTimeline
  18098. * The timeline currently being followed by the loader
  18099. * @param {number} segmentTimeline
  18100. * The timeline of the segment being loaded
  18101. * @param {('main'|'audio')} loaderType
  18102. * The loader type
  18103. * @param {boolean} audioDisabled
  18104. * Whether the audio is disabled for the loader. This should only be true when the
  18105. * loader may have muxed audio in its segment, but should not append it, e.g., for
  18106. * the main loader when an alternate audio playlist is active.
  18107. *
  18108. * @return {boolean}
  18109. * Whether the loader should wait for a timeline change from the timeline change
  18110. * controller before processing the segment
  18111. */
  18112. const shouldWaitForTimelineChange = ({
  18113. timelineChangeController,
  18114. currentTimeline,
  18115. segmentTimeline,
  18116. loaderType,
  18117. audioDisabled
  18118. }) => {
  18119. if (currentTimeline === segmentTimeline) {
  18120. return false;
  18121. }
  18122. if (loaderType === 'audio') {
  18123. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  18124. type: 'main'
  18125. }); // Audio loader should wait if:
  18126. //
  18127. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  18128. // * main hasn't yet changed to the timeline audio is looking to load
  18129. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  18130. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  18131. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  18132. // loader's segments (or the content is audio/video only and handled by the main
  18133. // loader).
  18134. if (loaderType === 'main' && audioDisabled) {
  18135. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  18136. type: 'audio'
  18137. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  18138. // change to the current timeline.
  18139. //
  18140. // Since the main loader is responsible for setting the timestamp offset for both
  18141. // audio and video, the main loader must wait for audio to be about to change to its
  18142. // timeline before setting the offset, otherwise, if audio is behind in loading,
  18143. // segments from the previous timeline would be adjusted by the new timestamp offset.
  18144. //
  18145. // This requirement means that video will not cross a timeline until the audio is
  18146. // about to cross to it, so that way audio and video will always cross the timeline
  18147. // together.
  18148. //
  18149. // In addition to normal timeline changes, these rules also apply to the start of a
  18150. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  18151. // that these rules apply to the first timeline change because if they did not, it's
  18152. // possible that the main loader will cross two timelines before the audio loader has
  18153. // crossed one. Logic may be implemented to handle the startup as a special case, but
  18154. // it's easier to simply treat all timeline changes the same.
  18155. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  18156. return false;
  18157. }
  18158. return true;
  18159. }
  18160. return false;
  18161. };
  18162. const mediaDuration = timingInfos => {
  18163. let maxDuration = 0;
  18164. ['video', 'audio'].forEach(function (type) {
  18165. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  18166. if (!typeTimingInfo) {
  18167. return;
  18168. }
  18169. const {
  18170. start,
  18171. end
  18172. } = typeTimingInfo;
  18173. let duration;
  18174. if (typeof start === 'bigint' || typeof end === 'bigint') {
  18175. duration = window.BigInt(end) - window.BigInt(start);
  18176. } else if (typeof start === 'number' && typeof end === 'number') {
  18177. duration = end - start;
  18178. }
  18179. if (typeof duration !== 'undefined' && duration > maxDuration) {
  18180. maxDuration = duration;
  18181. }
  18182. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  18183. // as we only need BigInt when we are above that.
  18184. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  18185. maxDuration = Number(maxDuration);
  18186. }
  18187. return maxDuration;
  18188. };
  18189. const segmentTooLong = ({
  18190. segmentDuration,
  18191. maxDuration
  18192. }) => {
  18193. // 0 duration segments are most likely due to metadata only segments or a lack of
  18194. // information.
  18195. if (!segmentDuration) {
  18196. return false;
  18197. } // For HLS:
  18198. //
  18199. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  18200. // The EXTINF duration of each Media Segment in the Playlist
  18201. // file, when rounded to the nearest integer, MUST be less than or equal
  18202. // to the target duration; longer segments can trigger playback stalls
  18203. // or other errors.
  18204. //
  18205. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  18206. // duration. Although that reported duration is occasionally approximate (i.e., not
  18207. // exact), a strict check may report that a segment is too long more often in DASH.
  18208. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  18209. };
  18210. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  18211. // Right now we aren't following DASH's timing model exactly, so only perform
  18212. // this check for HLS content.
  18213. if (sourceType !== 'hls') {
  18214. return null;
  18215. }
  18216. const segmentDuration = mediaDuration({
  18217. audioTimingInfo: segmentInfo.audioTimingInfo,
  18218. videoTimingInfo: segmentInfo.videoTimingInfo
  18219. }); // Don't report if we lack information.
  18220. //
  18221. // If the segment has a duration of 0 it is either a lack of information or a
  18222. // metadata only segment and shouldn't be reported here.
  18223. if (!segmentDuration) {
  18224. return null;
  18225. }
  18226. const targetDuration = segmentInfo.playlist.targetDuration;
  18227. const isSegmentWayTooLong = segmentTooLong({
  18228. segmentDuration,
  18229. maxDuration: targetDuration * 2
  18230. });
  18231. const isSegmentSlightlyTooLong = segmentTooLong({
  18232. segmentDuration,
  18233. maxDuration: targetDuration
  18234. });
  18235. const segmentTooLongMessage = `Segment with index ${segmentInfo.mediaIndex} ` + `from playlist ${segmentInfo.playlist.id} ` + `has a duration of ${segmentDuration} ` + `when the reported duration is ${segmentInfo.duration} ` + `and the target duration is ${targetDuration}. ` + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
  18236. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  18237. return {
  18238. severity: isSegmentWayTooLong ? 'warn' : 'info',
  18239. message: segmentTooLongMessage
  18240. };
  18241. }
  18242. return null;
  18243. };
  18244. /**
  18245. * An object that manages segment loading and appending.
  18246. *
  18247. * @class SegmentLoader
  18248. * @param {Object} options required and optional options
  18249. * @extends videojs.EventTarget
  18250. */
  18251. class SegmentLoader extends videojs__default["default"].EventTarget {
  18252. constructor(settings, options = {}) {
  18253. super(); // check pre-conditions
  18254. if (!settings) {
  18255. throw new TypeError('Initialization settings are required');
  18256. }
  18257. if (typeof settings.currentTime !== 'function') {
  18258. throw new TypeError('No currentTime getter specified');
  18259. }
  18260. if (!settings.mediaSource) {
  18261. throw new TypeError('No MediaSource specified');
  18262. } // public properties
  18263. this.bandwidth = settings.bandwidth;
  18264. this.throughput = {
  18265. rate: 0,
  18266. count: 0
  18267. };
  18268. this.roundTrip = NaN;
  18269. this.resetStats_();
  18270. this.mediaIndex = null;
  18271. this.partIndex = null; // private settings
  18272. this.hasPlayed_ = settings.hasPlayed;
  18273. this.currentTime_ = settings.currentTime;
  18274. this.seekable_ = settings.seekable;
  18275. this.seeking_ = settings.seeking;
  18276. this.duration_ = settings.duration;
  18277. this.mediaSource_ = settings.mediaSource;
  18278. this.vhs_ = settings.vhs;
  18279. this.loaderType_ = settings.loaderType;
  18280. this.currentMediaInfo_ = void 0;
  18281. this.startingMediaInfo_ = void 0;
  18282. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  18283. this.goalBufferLength_ = settings.goalBufferLength;
  18284. this.sourceType_ = settings.sourceType;
  18285. this.sourceUpdater_ = settings.sourceUpdater;
  18286. this.inbandTextTracks_ = settings.inbandTextTracks;
  18287. this.state_ = 'INIT';
  18288. this.timelineChangeController_ = settings.timelineChangeController;
  18289. this.shouldSaveSegmentTimingInfo_ = true;
  18290. this.parse708captions_ = settings.parse708captions;
  18291. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  18292. this.captionServices_ = settings.captionServices;
  18293. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  18294. this.checkBufferTimeout_ = null;
  18295. this.error_ = void 0;
  18296. this.currentTimeline_ = -1;
  18297. this.pendingSegment_ = null;
  18298. this.xhrOptions_ = null;
  18299. this.pendingSegments_ = [];
  18300. this.audioDisabled_ = false;
  18301. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  18302. this.gopBuffer_ = [];
  18303. this.timeMapping_ = 0;
  18304. this.safeAppend_ = videojs__default["default"].browser.IE_VERSION >= 11;
  18305. this.appendInitSegment_ = {
  18306. audio: true,
  18307. video: true
  18308. };
  18309. this.playlistOfLastInitSegment_ = {
  18310. audio: null,
  18311. video: null
  18312. };
  18313. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  18314. // information yet to start the loading process (e.g., if the audio loader wants to
  18315. // load a segment from the next timeline but the main loader hasn't yet crossed that
  18316. // timeline), then the load call will be added to the queue until it is ready to be
  18317. // processed.
  18318. this.loadQueue_ = [];
  18319. this.metadataQueue_ = {
  18320. id3: [],
  18321. caption: []
  18322. };
  18323. this.waitingOnRemove_ = false;
  18324. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  18325. this.activeInitSegmentId_ = null;
  18326. this.initSegments_ = {}; // HLSe playback
  18327. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  18328. this.keyCache_ = {};
  18329. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  18330. // between a time in the display time and a segment index within
  18331. // a playlist
  18332. this.syncController_ = settings.syncController;
  18333. this.syncPoint_ = {
  18334. segmentIndex: 0,
  18335. time: 0
  18336. };
  18337. this.transmuxer_ = this.createTransmuxer_();
  18338. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  18339. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  18340. this.mediaSource_.addEventListener('sourceopen', () => {
  18341. if (!this.isEndOfStream_()) {
  18342. this.ended_ = false;
  18343. }
  18344. }); // ...for determining the fetch location
  18345. this.fetchAtBuffer_ = false;
  18346. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  18347. Object.defineProperty(this, 'state', {
  18348. get() {
  18349. return this.state_;
  18350. },
  18351. set(newState) {
  18352. if (newState !== this.state_) {
  18353. this.logger_(`${this.state_} -> ${newState}`);
  18354. this.state_ = newState;
  18355. this.trigger('statechange');
  18356. }
  18357. }
  18358. });
  18359. this.sourceUpdater_.on('ready', () => {
  18360. if (this.hasEnoughInfoToAppend_()) {
  18361. this.processCallQueue_();
  18362. }
  18363. }); // Only the main loader needs to listen for pending timeline changes, as the main
  18364. // loader should wait for audio to be ready to change its timeline so that both main
  18365. // and audio timelines change together. For more details, see the
  18366. // shouldWaitForTimelineChange function.
  18367. if (this.loaderType_ === 'main') {
  18368. this.timelineChangeController_.on('pendingtimelinechange', () => {
  18369. if (this.hasEnoughInfoToAppend_()) {
  18370. this.processCallQueue_();
  18371. }
  18372. });
  18373. } // The main loader only listens on pending timeline changes, but the audio loader,
  18374. // since its loads follow main, needs to listen on timeline changes. For more details,
  18375. // see the shouldWaitForTimelineChange function.
  18376. if (this.loaderType_ === 'audio') {
  18377. this.timelineChangeController_.on('timelinechange', () => {
  18378. if (this.hasEnoughInfoToLoad_()) {
  18379. this.processLoadQueue_();
  18380. }
  18381. if (this.hasEnoughInfoToAppend_()) {
  18382. this.processCallQueue_();
  18383. }
  18384. });
  18385. }
  18386. }
  18387. createTransmuxer_() {
  18388. return segmentTransmuxer.createTransmuxer({
  18389. remux: false,
  18390. alignGopsAtEnd: this.safeAppend_,
  18391. keepOriginalTimestamps: true,
  18392. parse708captions: this.parse708captions_,
  18393. captionServices: this.captionServices_
  18394. });
  18395. }
  18396. /**
  18397. * reset all of our media stats
  18398. *
  18399. * @private
  18400. */
  18401. resetStats_() {
  18402. this.mediaBytesTransferred = 0;
  18403. this.mediaRequests = 0;
  18404. this.mediaRequestsAborted = 0;
  18405. this.mediaRequestsTimedout = 0;
  18406. this.mediaRequestsErrored = 0;
  18407. this.mediaTransferDuration = 0;
  18408. this.mediaSecondsLoaded = 0;
  18409. this.mediaAppends = 0;
  18410. }
  18411. /**
  18412. * dispose of the SegmentLoader and reset to the default state
  18413. */
  18414. dispose() {
  18415. this.trigger('dispose');
  18416. this.state = 'DISPOSED';
  18417. this.pause();
  18418. this.abort_();
  18419. if (this.transmuxer_) {
  18420. this.transmuxer_.terminate();
  18421. }
  18422. this.resetStats_();
  18423. if (this.checkBufferTimeout_) {
  18424. window.clearTimeout(this.checkBufferTimeout_);
  18425. }
  18426. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  18427. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  18428. }
  18429. this.off();
  18430. }
  18431. setAudio(enable) {
  18432. this.audioDisabled_ = !enable;
  18433. if (enable) {
  18434. this.appendInitSegment_.audio = true;
  18435. } else {
  18436. // remove current track audio if it gets disabled
  18437. this.sourceUpdater_.removeAudio(0, this.duration_());
  18438. }
  18439. }
  18440. /**
  18441. * abort anything that is currently doing on with the SegmentLoader
  18442. * and reset to a default state
  18443. */
  18444. abort() {
  18445. if (this.state !== 'WAITING') {
  18446. if (this.pendingSegment_) {
  18447. this.pendingSegment_ = null;
  18448. }
  18449. return;
  18450. }
  18451. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  18452. // since we are no longer "waiting" on any requests. XHR callback is not always run
  18453. // when the request is aborted. This will prevent the loader from being stuck in the
  18454. // WAITING state indefinitely.
  18455. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  18456. // next segment
  18457. if (!this.paused()) {
  18458. this.monitorBuffer_();
  18459. }
  18460. }
  18461. /**
  18462. * abort all pending xhr requests and null any pending segements
  18463. *
  18464. * @private
  18465. */
  18466. abort_() {
  18467. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  18468. this.pendingSegment_.abortRequests();
  18469. } // clear out the segment being processed
  18470. this.pendingSegment_ = null;
  18471. this.callQueue_ = [];
  18472. this.loadQueue_ = [];
  18473. this.metadataQueue_.id3 = [];
  18474. this.metadataQueue_.caption = [];
  18475. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  18476. this.waitingOnRemove_ = false;
  18477. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  18478. this.quotaExceededErrorRetryTimeout_ = null;
  18479. }
  18480. checkForAbort_(requestId) {
  18481. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  18482. // callback that happens should reset the state to READY so that loading can continue.
  18483. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  18484. this.state = 'READY';
  18485. return true;
  18486. }
  18487. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  18488. return true;
  18489. }
  18490. return false;
  18491. }
  18492. /**
  18493. * set an error on the segment loader and null out any pending segements
  18494. *
  18495. * @param {Error} error the error to set on the SegmentLoader
  18496. * @return {Error} the error that was set or that is currently set
  18497. */
  18498. error(error) {
  18499. if (typeof error !== 'undefined') {
  18500. this.logger_('error occurred:', error);
  18501. this.error_ = error;
  18502. }
  18503. this.pendingSegment_ = null;
  18504. return this.error_;
  18505. }
  18506. endOfStream() {
  18507. this.ended_ = true;
  18508. if (this.transmuxer_) {
  18509. // need to clear out any cached data to prepare for the new segment
  18510. segmentTransmuxer.reset(this.transmuxer_);
  18511. }
  18512. this.gopBuffer_.length = 0;
  18513. this.pause();
  18514. this.trigger('ended');
  18515. }
  18516. /**
  18517. * Indicates which time ranges are buffered
  18518. *
  18519. * @return {TimeRange}
  18520. * TimeRange object representing the current buffered ranges
  18521. */
  18522. buffered_() {
  18523. const trackInfo = this.getMediaInfo_();
  18524. if (!this.sourceUpdater_ || !trackInfo) {
  18525. return createTimeRanges();
  18526. }
  18527. if (this.loaderType_ === 'main') {
  18528. const {
  18529. hasAudio,
  18530. hasVideo,
  18531. isMuxed
  18532. } = trackInfo;
  18533. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  18534. return this.sourceUpdater_.buffered();
  18535. }
  18536. if (hasVideo) {
  18537. return this.sourceUpdater_.videoBuffered();
  18538. }
  18539. } // One case that can be ignored for now is audio only with alt audio,
  18540. // as we don't yet have proper support for that.
  18541. return this.sourceUpdater_.audioBuffered();
  18542. }
  18543. /**
  18544. * Gets and sets init segment for the provided map
  18545. *
  18546. * @param {Object} map
  18547. * The map object representing the init segment to get or set
  18548. * @param {boolean=} set
  18549. * If true, the init segment for the provided map should be saved
  18550. * @return {Object}
  18551. * map object for desired init segment
  18552. */
  18553. initSegmentForMap(map, set = false) {
  18554. if (!map) {
  18555. return null;
  18556. }
  18557. const id = initSegmentId(map);
  18558. let storedMap = this.initSegments_[id];
  18559. if (set && !storedMap && map.bytes) {
  18560. this.initSegments_[id] = storedMap = {
  18561. resolvedUri: map.resolvedUri,
  18562. byterange: map.byterange,
  18563. bytes: map.bytes,
  18564. tracks: map.tracks,
  18565. timescales: map.timescales
  18566. };
  18567. }
  18568. return storedMap || map;
  18569. }
  18570. /**
  18571. * Gets and sets key for the provided key
  18572. *
  18573. * @param {Object} key
  18574. * The key object representing the key to get or set
  18575. * @param {boolean=} set
  18576. * If true, the key for the provided key should be saved
  18577. * @return {Object}
  18578. * Key object for desired key
  18579. */
  18580. segmentKey(key, set = false) {
  18581. if (!key) {
  18582. return null;
  18583. }
  18584. const id = segmentKeyId(key);
  18585. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  18586. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  18587. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  18588. this.keyCache_[id] = storedKey = {
  18589. resolvedUri: key.resolvedUri,
  18590. bytes: key.bytes
  18591. };
  18592. }
  18593. const result = {
  18594. resolvedUri: (storedKey || key).resolvedUri
  18595. };
  18596. if (storedKey) {
  18597. result.bytes = storedKey.bytes;
  18598. }
  18599. return result;
  18600. }
  18601. /**
  18602. * Returns true if all configuration required for loading is present, otherwise false.
  18603. *
  18604. * @return {boolean} True if the all configuration is ready for loading
  18605. * @private
  18606. */
  18607. couldBeginLoading_() {
  18608. return this.playlist_ && !this.paused();
  18609. }
  18610. /**
  18611. * load a playlist and start to fill the buffer
  18612. */
  18613. load() {
  18614. // un-pause
  18615. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  18616. // specified
  18617. if (!this.playlist_) {
  18618. return;
  18619. } // if all the configuration is ready, initialize and begin loading
  18620. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  18621. return this.init_();
  18622. } // if we're in the middle of processing a segment already, don't
  18623. // kick off an additional segment request
  18624. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  18625. return;
  18626. }
  18627. this.state = 'READY';
  18628. }
  18629. /**
  18630. * Once all the starting parameters have been specified, begin
  18631. * operation. This method should only be invoked from the INIT
  18632. * state.
  18633. *
  18634. * @private
  18635. */
  18636. init_() {
  18637. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  18638. // audio data from the muxed content should be removed
  18639. this.resetEverything();
  18640. return this.monitorBuffer_();
  18641. }
  18642. /**
  18643. * set a playlist on the segment loader
  18644. *
  18645. * @param {PlaylistLoader} media the playlist to set on the segment loader
  18646. */
  18647. playlist(newPlaylist, options = {}) {
  18648. if (!newPlaylist) {
  18649. return;
  18650. }
  18651. const oldPlaylist = this.playlist_;
  18652. const segmentInfo = this.pendingSegment_;
  18653. this.playlist_ = newPlaylist;
  18654. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  18655. // is always our zero-time so force a sync update each time the playlist
  18656. // is refreshed from the server
  18657. //
  18658. // Use the INIT state to determine if playback has started, as the playlist sync info
  18659. // should be fixed once requests begin (as sync points are generated based on sync
  18660. // info), but not before then.
  18661. if (this.state === 'INIT') {
  18662. newPlaylist.syncInfo = {
  18663. mediaSequence: newPlaylist.mediaSequence,
  18664. time: 0
  18665. }; // Setting the date time mapping means mapping the program date time (if available)
  18666. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  18667. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  18668. // be updated as the playlist is refreshed before the loader starts loading, the
  18669. // program date time mapping needs to be updated as well.
  18670. //
  18671. // This mapping is only done for the main loader because a program date time should
  18672. // map equivalently between playlists.
  18673. if (this.loaderType_ === 'main') {
  18674. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  18675. }
  18676. }
  18677. let oldId = null;
  18678. if (oldPlaylist) {
  18679. if (oldPlaylist.id) {
  18680. oldId = oldPlaylist.id;
  18681. } else if (oldPlaylist.uri) {
  18682. oldId = oldPlaylist.uri;
  18683. }
  18684. }
  18685. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  18686. // in LIVE, we always want to update with new playlists (including refreshes)
  18687. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  18688. // buffering now
  18689. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  18690. return this.init_();
  18691. }
  18692. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  18693. if (this.mediaIndex !== null) {
  18694. // we must reset/resync the segment loader when we switch renditions and
  18695. // the segment loader is already synced to the previous rendition
  18696. // on playlist changes we want it to be possible to fetch
  18697. // at the buffer for vod but not for live. So we use resetLoader
  18698. // for live and resyncLoader for vod. We want this because
  18699. // if a playlist uses independent and non-independent segments/parts the
  18700. // buffer may not accurately reflect the next segment that we should try
  18701. // downloading.
  18702. if (!newPlaylist.endList) {
  18703. this.resetLoader();
  18704. } else {
  18705. this.resyncLoader();
  18706. }
  18707. }
  18708. this.currentMediaInfo_ = void 0;
  18709. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  18710. return;
  18711. } // we reloaded the same playlist so we are in a live scenario
  18712. // and we will likely need to adjust the mediaIndex
  18713. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  18714. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  18715. // this is important because we can abort a request and this value must be
  18716. // equal to the last appended mediaIndex
  18717. if (this.mediaIndex !== null) {
  18718. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  18719. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  18720. // new playlist was incremented by 1.
  18721. if (this.mediaIndex < 0) {
  18722. this.mediaIndex = null;
  18723. this.partIndex = null;
  18724. } else {
  18725. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  18726. // unless parts fell off of the playlist for this segment.
  18727. // In that case we need to reset partIndex and resync
  18728. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  18729. const mediaIndex = this.mediaIndex;
  18730. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  18731. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  18732. // as the part was dropped from our current playlists segment.
  18733. // The mediaIndex will still be valid so keep that around.
  18734. this.mediaIndex = mediaIndex;
  18735. }
  18736. }
  18737. } // update the mediaIndex on the SegmentInfo object
  18738. // this is important because we will update this.mediaIndex with this value
  18739. // in `handleAppendsDone_` after the segment has been successfully appended
  18740. if (segmentInfo) {
  18741. segmentInfo.mediaIndex -= mediaSequenceDiff;
  18742. if (segmentInfo.mediaIndex < 0) {
  18743. segmentInfo.mediaIndex = null;
  18744. segmentInfo.partIndex = null;
  18745. } else {
  18746. // we need to update the referenced segment so that timing information is
  18747. // saved for the new playlist's segment, however, if the segment fell off the
  18748. // playlist, we can leave the old reference and just lose the timing info
  18749. if (segmentInfo.mediaIndex >= 0) {
  18750. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  18751. }
  18752. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  18753. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  18754. }
  18755. }
  18756. }
  18757. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  18758. }
  18759. /**
  18760. * Prevent the loader from fetching additional segments. If there
  18761. * is a segment request outstanding, it will finish processing
  18762. * before the loader halts. A segment loader can be unpaused by
  18763. * calling load().
  18764. */
  18765. pause() {
  18766. if (this.checkBufferTimeout_) {
  18767. window.clearTimeout(this.checkBufferTimeout_);
  18768. this.checkBufferTimeout_ = null;
  18769. }
  18770. }
  18771. /**
  18772. * Returns whether the segment loader is fetching additional
  18773. * segments when given the opportunity. This property can be
  18774. * modified through calls to pause() and load().
  18775. */
  18776. paused() {
  18777. return this.checkBufferTimeout_ === null;
  18778. }
  18779. /**
  18780. * Delete all the buffered data and reset the SegmentLoader
  18781. *
  18782. * @param {Function} [done] an optional callback to be executed when the remove
  18783. * operation is complete
  18784. */
  18785. resetEverything(done) {
  18786. this.ended_ = false;
  18787. this.activeInitSegmentId_ = null;
  18788. this.appendInitSegment_ = {
  18789. audio: true,
  18790. video: true
  18791. };
  18792. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  18793. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  18794. // we then clamp the value to duration if necessary.
  18795. this.remove(0, Infinity, done); // clears fmp4 captions
  18796. if (this.transmuxer_) {
  18797. this.transmuxer_.postMessage({
  18798. action: 'clearAllMp4Captions'
  18799. }); // reset the cache in the transmuxer
  18800. this.transmuxer_.postMessage({
  18801. action: 'reset'
  18802. });
  18803. }
  18804. }
  18805. /**
  18806. * Force the SegmentLoader to resync and start loading around the currentTime instead
  18807. * of starting at the end of the buffer
  18808. *
  18809. * Useful for fast quality changes
  18810. */
  18811. resetLoader() {
  18812. this.fetchAtBuffer_ = false;
  18813. this.resyncLoader();
  18814. }
  18815. /**
  18816. * Force the SegmentLoader to restart synchronization and make a conservative guess
  18817. * before returning to the simple walk-forward method
  18818. */
  18819. resyncLoader() {
  18820. if (this.transmuxer_) {
  18821. // need to clear out any cached data to prepare for the new segment
  18822. segmentTransmuxer.reset(this.transmuxer_);
  18823. }
  18824. this.mediaIndex = null;
  18825. this.partIndex = null;
  18826. this.syncPoint_ = null;
  18827. this.isPendingTimestampOffset_ = false;
  18828. this.callQueue_ = [];
  18829. this.loadQueue_ = [];
  18830. this.metadataQueue_.id3 = [];
  18831. this.metadataQueue_.caption = [];
  18832. this.abort();
  18833. if (this.transmuxer_) {
  18834. this.transmuxer_.postMessage({
  18835. action: 'clearParsedMp4Captions'
  18836. });
  18837. }
  18838. }
  18839. /**
  18840. * Remove any data in the source buffer between start and end times
  18841. *
  18842. * @param {number} start - the start time of the region to remove from the buffer
  18843. * @param {number} end - the end time of the region to remove from the buffer
  18844. * @param {Function} [done] - an optional callback to be executed when the remove
  18845. * @param {boolean} force - force all remove operations to happen
  18846. * operation is complete
  18847. */
  18848. remove(start, end, done = () => {}, force = false) {
  18849. // clamp end to duration if we need to remove everything.
  18850. // This is due to a browser bug that causes issues if we remove to Infinity.
  18851. // videojs/videojs-contrib-hls#1225
  18852. if (end === Infinity) {
  18853. end = this.duration_();
  18854. } // skip removes that would throw an error
  18855. // commonly happens during a rendition switch at the start of a video
  18856. // from start 0 to end 0
  18857. if (end <= start) {
  18858. this.logger_('skipping remove because end ${end} is <= start ${start}');
  18859. return;
  18860. }
  18861. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  18862. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  18863. return;
  18864. } // set it to one to complete this function's removes
  18865. let removesRemaining = 1;
  18866. const removeFinished = () => {
  18867. removesRemaining--;
  18868. if (removesRemaining === 0) {
  18869. done();
  18870. }
  18871. };
  18872. if (force || !this.audioDisabled_) {
  18873. removesRemaining++;
  18874. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  18875. } // While it would be better to only remove video if the main loader has video, this
  18876. // should be safe with audio only as removeVideo will call back even if there's no
  18877. // video buffer.
  18878. //
  18879. // In theory we can check to see if there's video before calling the remove, but in
  18880. // the event that we're switching between renditions and from video to audio only
  18881. // (when we add support for that), we may need to clear the video contents despite
  18882. // what the new media will contain.
  18883. if (force || this.loaderType_ === 'main') {
  18884. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  18885. removesRemaining++;
  18886. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  18887. } // remove any captions and ID3 tags
  18888. for (const track in this.inbandTextTracks_) {
  18889. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  18890. }
  18891. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  18892. removeFinished();
  18893. }
  18894. /**
  18895. * (re-)schedule monitorBufferTick_ to run as soon as possible
  18896. *
  18897. * @private
  18898. */
  18899. monitorBuffer_() {
  18900. if (this.checkBufferTimeout_) {
  18901. window.clearTimeout(this.checkBufferTimeout_);
  18902. }
  18903. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  18904. }
  18905. /**
  18906. * As long as the SegmentLoader is in the READY state, periodically
  18907. * invoke fillBuffer_().
  18908. *
  18909. * @private
  18910. */
  18911. monitorBufferTick_() {
  18912. if (this.state === 'READY') {
  18913. this.fillBuffer_();
  18914. }
  18915. if (this.checkBufferTimeout_) {
  18916. window.clearTimeout(this.checkBufferTimeout_);
  18917. }
  18918. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  18919. }
  18920. /**
  18921. * fill the buffer with segements unless the sourceBuffers are
  18922. * currently updating
  18923. *
  18924. * Note: this function should only ever be called by monitorBuffer_
  18925. * and never directly
  18926. *
  18927. * @private
  18928. */
  18929. fillBuffer_() {
  18930. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  18931. // except when we're ready for the next segment, this check can most likely be removed
  18932. if (this.sourceUpdater_.updating()) {
  18933. return;
  18934. } // see if we need to begin loading immediately
  18935. const segmentInfo = this.chooseNextRequest_();
  18936. if (!segmentInfo) {
  18937. return;
  18938. }
  18939. if (typeof segmentInfo.timestampOffset === 'number') {
  18940. this.isPendingTimestampOffset_ = false;
  18941. this.timelineChangeController_.pendingTimelineChange({
  18942. type: this.loaderType_,
  18943. from: this.currentTimeline_,
  18944. to: segmentInfo.timeline
  18945. });
  18946. }
  18947. this.loadSegment_(segmentInfo);
  18948. }
  18949. /**
  18950. * Determines if we should call endOfStream on the media source based
  18951. * on the state of the buffer or if appened segment was the final
  18952. * segment in the playlist.
  18953. *
  18954. * @param {number} [mediaIndex] the media index of segment we last appended
  18955. * @param {Object} [playlist] a media playlist object
  18956. * @return {boolean} do we need to call endOfStream on the MediaSource
  18957. */
  18958. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  18959. if (!playlist || !this.mediaSource_) {
  18960. return false;
  18961. }
  18962. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  18963. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  18964. const appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
  18965. // so that MediaSources can trigger the `ended` event when it runs out of
  18966. // buffered data instead of waiting for me
  18967. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  18968. }
  18969. /**
  18970. * Determines what request should be made given current segment loader state.
  18971. *
  18972. * @return {Object} a request object that describes the segment/part to load
  18973. */
  18974. chooseNextRequest_() {
  18975. const buffered = this.buffered_();
  18976. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  18977. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  18978. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  18979. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  18980. const segments = this.playlist_.segments; // return no segment if:
  18981. // 1. we don't have segments
  18982. // 2. The video has not yet played and we already downloaded a segment
  18983. // 3. we already have enough buffered time
  18984. if (!segments.length || preloaded || haveEnoughBuffer) {
  18985. return null;
  18986. }
  18987. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  18988. const next = {
  18989. partIndex: null,
  18990. mediaIndex: null,
  18991. startOfSegment: null,
  18992. playlist: this.playlist_,
  18993. isSyncRequest: Boolean(!this.syncPoint_)
  18994. };
  18995. if (next.isSyncRequest) {
  18996. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  18997. } else if (this.mediaIndex !== null) {
  18998. const segment = segments[this.mediaIndex];
  18999. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  19000. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  19001. if (segment.parts && segment.parts[partIndex + 1]) {
  19002. next.mediaIndex = this.mediaIndex;
  19003. next.partIndex = partIndex + 1;
  19004. } else {
  19005. next.mediaIndex = this.mediaIndex + 1;
  19006. }
  19007. } else {
  19008. // Find the segment containing the end of the buffer or current time.
  19009. const {
  19010. segmentIndex,
  19011. startTime,
  19012. partIndex
  19013. } = Playlist.getMediaInfoForTime({
  19014. exactManifestTimings: this.exactManifestTimings,
  19015. playlist: this.playlist_,
  19016. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  19017. startingPartIndex: this.syncPoint_.partIndex,
  19018. startingSegmentIndex: this.syncPoint_.segmentIndex,
  19019. startTime: this.syncPoint_.time
  19020. });
  19021. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  19022. next.mediaIndex = segmentIndex;
  19023. next.startOfSegment = startTime;
  19024. next.partIndex = partIndex;
  19025. }
  19026. const nextSegment = segments[next.mediaIndex];
  19027. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  19028. // the next partIndex is invalid do not choose a next segment.
  19029. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  19030. return null;
  19031. } // if the next segment has parts, and we don't have a partIndex.
  19032. // Set partIndex to 0
  19033. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  19034. next.partIndex = 0;
  19035. nextPart = nextSegment.parts[0];
  19036. } // if we have no buffered data then we need to make sure
  19037. // that the next part we append is "independent" if possible.
  19038. // So we check if the previous part is independent, and request
  19039. // it if it is.
  19040. if (!bufferedTime && nextPart && !nextPart.independent) {
  19041. if (next.partIndex === 0) {
  19042. const lastSegment = segments[next.mediaIndex - 1];
  19043. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  19044. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  19045. next.mediaIndex -= 1;
  19046. next.partIndex = lastSegment.parts.length - 1;
  19047. next.independent = 'previous segment';
  19048. }
  19049. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  19050. next.partIndex -= 1;
  19051. next.independent = 'previous part';
  19052. }
  19053. }
  19054. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  19055. // 1. this is the last segment in the playlist
  19056. // 2. end of stream has been called on the media source already
  19057. // 3. the player is not seeking
  19058. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  19059. return null;
  19060. }
  19061. return this.generateSegmentInfo_(next);
  19062. }
  19063. generateSegmentInfo_(options) {
  19064. const {
  19065. independent,
  19066. playlist,
  19067. mediaIndex,
  19068. startOfSegment,
  19069. isSyncRequest,
  19070. partIndex,
  19071. forceTimestampOffset,
  19072. getMediaInfoForTime
  19073. } = options;
  19074. const segment = playlist.segments[mediaIndex];
  19075. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  19076. const segmentInfo = {
  19077. requestId: 'segment-loader-' + Math.random(),
  19078. // resolve the segment URL relative to the playlist
  19079. uri: part && part.resolvedUri || segment.resolvedUri,
  19080. // the segment's mediaIndex at the time it was requested
  19081. mediaIndex,
  19082. partIndex: part ? partIndex : null,
  19083. // whether or not to update the SegmentLoader's state with this
  19084. // segment's mediaIndex
  19085. isSyncRequest,
  19086. startOfSegment,
  19087. // the segment's playlist
  19088. playlist,
  19089. // unencrypted bytes of the segment
  19090. bytes: null,
  19091. // when a key is defined for this segment, the encrypted bytes
  19092. encryptedBytes: null,
  19093. // The target timestampOffset for this segment when we append it
  19094. // to the source buffer
  19095. timestampOffset: null,
  19096. // The timeline that the segment is in
  19097. timeline: segment.timeline,
  19098. // The expected duration of the segment in seconds
  19099. duration: part && part.duration || segment.duration,
  19100. // retain the segment in case the playlist updates while doing an async process
  19101. segment,
  19102. part,
  19103. byteLength: 0,
  19104. transmuxer: this.transmuxer_,
  19105. // type of getMediaInfoForTime that was used to get this segment
  19106. getMediaInfoForTime,
  19107. independent
  19108. };
  19109. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  19110. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  19111. segmentTimeline: segment.timeline,
  19112. currentTimeline: this.currentTimeline_,
  19113. startOfSegment,
  19114. buffered: this.buffered_(),
  19115. overrideCheck
  19116. });
  19117. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  19118. if (typeof audioBufferedEnd === 'number') {
  19119. // since the transmuxer is using the actual timing values, but the buffer is
  19120. // adjusted by the timestamp offset, we must adjust the value here
  19121. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  19122. }
  19123. if (this.sourceUpdater_.videoBuffered().length) {
  19124. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  19125. // adjusted by the timestmap offset, we must adjust the value here
  19126. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  19127. }
  19128. return segmentInfo;
  19129. } // get the timestampoffset for a segment,
  19130. // added so that vtt segment loader can override and prevent
  19131. // adding timestamp offsets.
  19132. timestampOffsetForSegment_(options) {
  19133. return timestampOffsetForSegment(options);
  19134. }
  19135. /**
  19136. * Determines if the network has enough bandwidth to complete the current segment
  19137. * request in a timely manner. If not, the request will be aborted early and bandwidth
  19138. * updated to trigger a playlist switch.
  19139. *
  19140. * @param {Object} stats
  19141. * Object containing stats about the request timing and size
  19142. * @private
  19143. */
  19144. earlyAbortWhenNeeded_(stats) {
  19145. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  19146. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  19147. // the lowestEnabledRendition.
  19148. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  19149. !this.playlist_.attributes.BANDWIDTH) {
  19150. return;
  19151. } // Wait at least 1 second since the first byte of data has been received before
  19152. // using the calculated bandwidth from the progress event to allow the bitrate
  19153. // to stabilize
  19154. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  19155. return;
  19156. }
  19157. const currentTime = this.currentTime_();
  19158. const measuredBandwidth = stats.bandwidth;
  19159. const segmentDuration = this.pendingSegment_.duration;
  19160. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  19161. // if we are only left with less than 1 second when the request completes.
  19162. // A negative timeUntilRebuffering indicates we are already rebuffering
  19163. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  19164. // is larger than the estimated time until the player runs out of forward buffer
  19165. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  19166. return;
  19167. }
  19168. const switchCandidate = minRebufferMaxBandwidthSelector({
  19169. main: this.vhs_.playlists.main,
  19170. currentTime,
  19171. bandwidth: measuredBandwidth,
  19172. duration: this.duration_(),
  19173. segmentDuration,
  19174. timeUntilRebuffer: timeUntilRebuffer$1,
  19175. currentTimeline: this.currentTimeline_,
  19176. syncController: this.syncController_
  19177. });
  19178. if (!switchCandidate) {
  19179. return;
  19180. }
  19181. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  19182. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  19183. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  19184. // potential round trip time of the new request so that we are not too aggressive
  19185. // with switching to a playlist that might save us a fraction of a second.
  19186. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  19187. minimumTimeSaving = 1;
  19188. }
  19189. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  19190. return;
  19191. } // set the bandwidth to that of the desired playlist being sure to scale by
  19192. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  19193. // don't trigger a bandwidthupdate as the bandwidth is artifial
  19194. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  19195. this.trigger('earlyabort');
  19196. }
  19197. handleAbort_(segmentInfo) {
  19198. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  19199. this.mediaRequestsAborted += 1;
  19200. }
  19201. /**
  19202. * XHR `progress` event handler
  19203. *
  19204. * @param {Event}
  19205. * The XHR `progress` event
  19206. * @param {Object} simpleSegment
  19207. * A simplified segment object copy
  19208. * @private
  19209. */
  19210. handleProgress_(event, simpleSegment) {
  19211. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19212. if (this.checkForAbort_(simpleSegment.requestId)) {
  19213. return;
  19214. }
  19215. this.trigger('progress');
  19216. }
  19217. handleTrackInfo_(simpleSegment, trackInfo) {
  19218. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19219. if (this.checkForAbort_(simpleSegment.requestId)) {
  19220. return;
  19221. }
  19222. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  19223. return;
  19224. }
  19225. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  19226. // Guard against cases where we're not getting track info at all until we are
  19227. // certain that all streams will provide it.
  19228. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  19229. this.appendInitSegment_ = {
  19230. audio: true,
  19231. video: true
  19232. };
  19233. this.startingMediaInfo_ = trackInfo;
  19234. this.currentMediaInfo_ = trackInfo;
  19235. this.logger_('trackinfo update', trackInfo);
  19236. this.trigger('trackinfo');
  19237. } // trackinfo may cause an abort if the trackinfo
  19238. // causes a codec change to an unsupported codec.
  19239. if (this.checkForAbort_(simpleSegment.requestId)) {
  19240. return;
  19241. } // set trackinfo on the pending segment so that
  19242. // it can append.
  19243. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  19244. if (this.hasEnoughInfoToAppend_()) {
  19245. this.processCallQueue_();
  19246. }
  19247. }
  19248. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  19249. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19250. if (this.checkForAbort_(simpleSegment.requestId)) {
  19251. return;
  19252. }
  19253. const segmentInfo = this.pendingSegment_;
  19254. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  19255. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  19256. segmentInfo[timingInfoProperty][timeType] = time;
  19257. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  19258. if (this.hasEnoughInfoToAppend_()) {
  19259. this.processCallQueue_();
  19260. }
  19261. }
  19262. handleCaptions_(simpleSegment, captionData) {
  19263. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19264. if (this.checkForAbort_(simpleSegment.requestId)) {
  19265. return;
  19266. } // This could only happen with fmp4 segments, but
  19267. // should still not happen in general
  19268. if (captionData.length === 0) {
  19269. this.logger_('SegmentLoader received no captions from a caption event');
  19270. return;
  19271. }
  19272. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  19273. // can be adjusted by the timestamp offset
  19274. if (!segmentInfo.hasAppendedData_) {
  19275. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  19276. return;
  19277. }
  19278. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  19279. const captionTracks = {}; // get total start/end and captions for each track/stream
  19280. captionData.forEach(caption => {
  19281. // caption.stream is actually a track name...
  19282. // set to the existing values in tracks or default values
  19283. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  19284. // Infinity, as any other value will be less than this
  19285. startTime: Infinity,
  19286. captions: [],
  19287. // 0 as an other value will be more than this
  19288. endTime: 0
  19289. };
  19290. const captionTrack = captionTracks[caption.stream];
  19291. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  19292. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  19293. captionTrack.captions.push(caption);
  19294. });
  19295. Object.keys(captionTracks).forEach(trackName => {
  19296. const {
  19297. startTime,
  19298. endTime,
  19299. captions
  19300. } = captionTracks[trackName];
  19301. const inbandTextTracks = this.inbandTextTracks_;
  19302. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  19303. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  19304. // We do this because a rendition change that also changes the timescale for captions
  19305. // will result in captions being re-parsed for certain segments. If we add them again
  19306. // without clearing we will have two of the same captions visible.
  19307. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  19308. addCaptionData({
  19309. captionArray: captions,
  19310. inbandTextTracks,
  19311. timestampOffset
  19312. });
  19313. }); // Reset stored captions since we added parsed
  19314. // captions to a text track at this point
  19315. if (this.transmuxer_) {
  19316. this.transmuxer_.postMessage({
  19317. action: 'clearParsedMp4Captions'
  19318. });
  19319. }
  19320. }
  19321. handleId3_(simpleSegment, id3Frames, dispatchType) {
  19322. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19323. if (this.checkForAbort_(simpleSegment.requestId)) {
  19324. return;
  19325. }
  19326. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  19327. if (!segmentInfo.hasAppendedData_) {
  19328. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  19329. return;
  19330. }
  19331. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  19332. // audio/video source with a metadata track, and an alt audio with a metadata track.
  19333. // However, this probably won't happen, and if it does it can be handled then.
  19334. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  19335. addMetadata({
  19336. inbandTextTracks: this.inbandTextTracks_,
  19337. metadataArray: id3Frames,
  19338. timestampOffset,
  19339. videoDuration: this.duration_()
  19340. });
  19341. }
  19342. processMetadataQueue_() {
  19343. this.metadataQueue_.id3.forEach(fn => fn());
  19344. this.metadataQueue_.caption.forEach(fn => fn());
  19345. this.metadataQueue_.id3 = [];
  19346. this.metadataQueue_.caption = [];
  19347. }
  19348. processCallQueue_() {
  19349. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  19350. // functions may check the length of the load queue and default to pushing themselves
  19351. // back onto the queue.
  19352. this.callQueue_ = [];
  19353. callQueue.forEach(fun => fun());
  19354. }
  19355. processLoadQueue_() {
  19356. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  19357. // functions may check the length of the load queue and default to pushing themselves
  19358. // back onto the queue.
  19359. this.loadQueue_ = [];
  19360. loadQueue.forEach(fun => fun());
  19361. }
  19362. /**
  19363. * Determines whether the loader has enough info to load the next segment.
  19364. *
  19365. * @return {boolean}
  19366. * Whether or not the loader has enough info to load the next segment
  19367. */
  19368. hasEnoughInfoToLoad_() {
  19369. // Since primary timing goes by video, only the audio loader potentially needs to wait
  19370. // to load.
  19371. if (this.loaderType_ !== 'audio') {
  19372. return true;
  19373. }
  19374. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  19375. // enough info to load.
  19376. if (!segmentInfo) {
  19377. return false;
  19378. } // The first segment can and should be loaded immediately so that source buffers are
  19379. // created together (before appending). Source buffer creation uses the presence of
  19380. // audio and video data to determine whether to create audio/video source buffers, and
  19381. // uses processed (transmuxed or parsed) media to determine the types required.
  19382. if (!this.getCurrentMediaInfo_()) {
  19383. return true;
  19384. }
  19385. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  19386. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  19387. // But in practice, there are a few reasons why it is better to wait until a loader
  19388. // is ready to append that segment before requesting and downloading:
  19389. //
  19390. // 1. Because audio and main loaders cross discontinuities together, if this loader
  19391. // is waiting for the other to catch up, then instead of requesting another
  19392. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  19393. // allotted to the loader currently behind.
  19394. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  19395. // is ready to be processed or not, isolating the queueing behavior to the loader.
  19396. // 3. The audio loader bases some of its segment properties on timing information
  19397. // provided by the main loader, meaning that, if the logic for waiting on
  19398. // processing was in media-segment-request, then it would also need to know how
  19399. // to re-generate the segment information after the main loader caught up.
  19400. shouldWaitForTimelineChange({
  19401. timelineChangeController: this.timelineChangeController_,
  19402. currentTimeline: this.currentTimeline_,
  19403. segmentTimeline: segmentInfo.timeline,
  19404. loaderType: this.loaderType_,
  19405. audioDisabled: this.audioDisabled_
  19406. })) {
  19407. return false;
  19408. }
  19409. return true;
  19410. }
  19411. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  19412. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  19413. }
  19414. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  19415. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  19416. }
  19417. getPendingSegmentPlaylist() {
  19418. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  19419. }
  19420. hasEnoughInfoToAppend_() {
  19421. if (!this.sourceUpdater_.ready()) {
  19422. return false;
  19423. } // If content needs to be removed or the loader is waiting on an append reattempt,
  19424. // then no additional content should be appended until the prior append is resolved.
  19425. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  19426. return false;
  19427. }
  19428. const segmentInfo = this.pendingSegment_;
  19429. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  19430. // we do not have information on this specific
  19431. // segment yet
  19432. if (!segmentInfo || !trackInfo) {
  19433. return false;
  19434. }
  19435. const {
  19436. hasAudio,
  19437. hasVideo,
  19438. isMuxed
  19439. } = trackInfo;
  19440. if (hasVideo && !segmentInfo.videoTimingInfo) {
  19441. return false;
  19442. } // muxed content only relies on video timing information for now.
  19443. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  19444. return false;
  19445. }
  19446. if (shouldWaitForTimelineChange({
  19447. timelineChangeController: this.timelineChangeController_,
  19448. currentTimeline: this.currentTimeline_,
  19449. segmentTimeline: segmentInfo.timeline,
  19450. loaderType: this.loaderType_,
  19451. audioDisabled: this.audioDisabled_
  19452. })) {
  19453. return false;
  19454. }
  19455. return true;
  19456. }
  19457. handleData_(simpleSegment, result) {
  19458. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19459. if (this.checkForAbort_(simpleSegment.requestId)) {
  19460. return;
  19461. } // If there's anything in the call queue, then this data came later and should be
  19462. // executed after the calls currently queued.
  19463. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  19464. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  19465. return;
  19466. }
  19467. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  19468. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  19469. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  19470. // logic may change behavior depending on the state, and changing state too early may
  19471. // inflate our estimates of bandwidth. In the future this should be re-examined to
  19472. // note more granular states.
  19473. // don't process and append data if the mediaSource is closed
  19474. if (this.mediaSource_.readyState === 'closed') {
  19475. return;
  19476. } // if this request included an initialization segment, save that data
  19477. // to the initSegment cache
  19478. if (simpleSegment.map) {
  19479. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  19480. segmentInfo.segment.map = simpleSegment.map;
  19481. } // if this request included a segment key, save that data in the cache
  19482. if (simpleSegment.key) {
  19483. this.segmentKey(simpleSegment.key, true);
  19484. }
  19485. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  19486. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  19487. if (segmentInfo.isFmp4) {
  19488. this.trigger('fmp4');
  19489. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  19490. } else {
  19491. const trackInfo = this.getCurrentMediaInfo_();
  19492. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  19493. let firstVideoFrameTimeForData;
  19494. if (useVideoTimingInfo) {
  19495. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  19496. } // Segment loader knows more about segment timing than the transmuxer (in certain
  19497. // aspects), so make any changes required for a more accurate start time.
  19498. // Don't set the end time yet, as the segment may not be finished processing.
  19499. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  19500. currentStart: segmentInfo.timingInfo.start,
  19501. playlist: segmentInfo.playlist,
  19502. mediaIndex: segmentInfo.mediaIndex,
  19503. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  19504. useVideoTimingInfo,
  19505. firstVideoFrameTimeForData,
  19506. videoTimingInfo: segmentInfo.videoTimingInfo,
  19507. audioTimingInfo: segmentInfo.audioTimingInfo
  19508. });
  19509. } // Init segments for audio and video only need to be appended in certain cases. Now
  19510. // that data is about to be appended, we can check the final cases to determine
  19511. // whether we should append an init segment.
  19512. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  19513. // as we use the start of the segment to offset the best guess (playlist provided)
  19514. // timestamp offset.
  19515. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  19516. // be appended or not.
  19517. if (segmentInfo.isSyncRequest) {
  19518. // first save/update our timing info for this segment.
  19519. // this is what allows us to choose an accurate segment
  19520. // and the main reason we make a sync request.
  19521. this.updateTimingInfoEnd_(segmentInfo);
  19522. this.syncController_.saveSegmentTimingInfo({
  19523. segmentInfo,
  19524. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  19525. });
  19526. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  19527. // after taking into account its timing info, do not append it.
  19528. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  19529. this.logger_('sync segment was incorrect, not appending');
  19530. return;
  19531. } // otherwise append it like any other segment as our guess was correct.
  19532. this.logger_('sync segment was correct, appending');
  19533. } // Save some state so that in the future anything waiting on first append (and/or
  19534. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  19535. // we need some notion of whether the timestamp offset or other relevant information
  19536. // has had a chance to be set.
  19537. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  19538. this.processMetadataQueue_();
  19539. this.appendData_(segmentInfo, result);
  19540. }
  19541. updateAppendInitSegmentStatus(segmentInfo, type) {
  19542. // alt audio doesn't manage timestamp offset
  19543. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
  19544. // segment for each chunk
  19545. !segmentInfo.changedTimestampOffset) {
  19546. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  19547. // append init segments
  19548. this.appendInitSegment_ = {
  19549. audio: true,
  19550. video: true
  19551. };
  19552. }
  19553. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  19554. // make sure we append init segment on playlist changes, in case the media config
  19555. // changed
  19556. this.appendInitSegment_[type] = true;
  19557. }
  19558. }
  19559. getInitSegmentAndUpdateState_({
  19560. type,
  19561. initSegment,
  19562. map,
  19563. playlist
  19564. }) {
  19565. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  19566. // (Section 3) required to parse the applicable Media Segments. It applies to every
  19567. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  19568. // or until the end of the playlist."
  19569. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  19570. if (map) {
  19571. const id = initSegmentId(map);
  19572. if (this.activeInitSegmentId_ === id) {
  19573. // don't need to re-append the init segment if the ID matches
  19574. return null;
  19575. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  19576. // obtained) init segment
  19577. //
  19578. // this also caches the init segment for later use
  19579. initSegment = this.initSegmentForMap(map, true).bytes;
  19580. this.activeInitSegmentId_ = id;
  19581. } // We used to always prepend init segments for video, however, that shouldn't be
  19582. // necessary. Instead, we should only append on changes, similar to what we've always
  19583. // done for audio. This is more important (though may not be that important) for
  19584. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  19585. // appends.
  19586. if (initSegment && this.appendInitSegment_[type]) {
  19587. // Make sure we track the playlist that we last used for the init segment, so that
  19588. // we can re-append the init segment in the event that we get data from a new
  19589. // playlist. Discontinuities and track changes are handled in other sections.
  19590. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  19591. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  19592. // we are appending the muxer init segment
  19593. this.activeInitSegmentId_ = null;
  19594. return initSegment;
  19595. }
  19596. return null;
  19597. }
  19598. handleQuotaExceededError_({
  19599. segmentInfo,
  19600. type,
  19601. bytes
  19602. }, error) {
  19603. const audioBuffered = this.sourceUpdater_.audioBuffered();
  19604. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  19605. // should be cleared out during the buffer removals. However, log in case it helps
  19606. // debug.
  19607. if (audioBuffered.length > 1) {
  19608. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  19609. }
  19610. if (videoBuffered.length > 1) {
  19611. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  19612. }
  19613. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  19614. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  19615. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  19616. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  19617. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  19618. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  19619. // allow for appends of segments this size). In the future, it may be possible to
  19620. // split up the segment and append in pieces, but for now, error out this playlist
  19621. // in an attempt to switch to a more manageable rendition.
  19622. this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + `Appended byte length: ${bytes.byteLength}, ` + `audio buffer: ${timeRangesToArray(audioBuffered).join(', ')}, ` + `video buffer: ${timeRangesToArray(videoBuffered).join(', ')}, `);
  19623. this.error({
  19624. message: 'Quota exceeded error with append of a single segment of content',
  19625. excludeUntil: Infinity
  19626. });
  19627. this.trigger('error');
  19628. return;
  19629. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  19630. // that the segment-loader should block on future events until this one is handled, so
  19631. // that it doesn't keep moving onto further segments. Adding the call to the call
  19632. // queue will prevent further appends until waitingOnRemove_ and
  19633. // quotaExceededErrorRetryTimeout_ are cleared.
  19634. //
  19635. // Note that this will only block the current loader. In the case of demuxed content,
  19636. // the other load may keep filling as fast as possible. In practice, this should be
  19637. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  19638. // source buffer, or video fills without enough room for audio to append (and without
  19639. // the availability of clearing out seconds of back buffer to make room for audio).
  19640. // But it might still be good to handle this case in the future as a TODO.
  19641. this.waitingOnRemove_ = true;
  19642. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  19643. segmentInfo,
  19644. type,
  19645. bytes
  19646. }));
  19647. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  19648. // before retrying.
  19649. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  19650. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  19651. this.remove(0, timeToRemoveUntil, () => {
  19652. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  19653. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  19654. // attempts (since we can't clear less than the minimum)
  19655. this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
  19656. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  19657. this.quotaExceededErrorRetryTimeout_ = null;
  19658. this.processCallQueue_();
  19659. }, MIN_BACK_BUFFER * 1000);
  19660. }, true);
  19661. }
  19662. handleAppendError_({
  19663. segmentInfo,
  19664. type,
  19665. bytes
  19666. }, error) {
  19667. // if there's no error, nothing to do
  19668. if (!error) {
  19669. return;
  19670. }
  19671. if (error.code === QUOTA_EXCEEDED_ERR) {
  19672. this.handleQuotaExceededError_({
  19673. segmentInfo,
  19674. type,
  19675. bytes
  19676. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  19677. // to trigger an append error.
  19678. return;
  19679. }
  19680. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  19681. this.error(`${type} append of ${bytes.length}b failed for segment ` + `#${segmentInfo.mediaIndex} in playlist ${segmentInfo.playlist.id}`); // If an append errors, we often can't recover.
  19682. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  19683. //
  19684. // Trigger a special error so that it can be handled separately from normal,
  19685. // recoverable errors.
  19686. this.trigger('appenderror');
  19687. }
  19688. appendToSourceBuffer_({
  19689. segmentInfo,
  19690. type,
  19691. initSegment,
  19692. data,
  19693. bytes
  19694. }) {
  19695. // If this is a re-append, bytes were already created and don't need to be recreated
  19696. if (!bytes) {
  19697. const segments = [data];
  19698. let byteLength = data.byteLength;
  19699. if (initSegment) {
  19700. // if the media initialization segment is changing, append it before the content
  19701. // segment
  19702. segments.unshift(initSegment);
  19703. byteLength += initSegment.byteLength;
  19704. } // Technically we should be OK appending the init segment separately, however, we
  19705. // haven't yet tested that, and prepending is how we have always done things.
  19706. bytes = concatSegments({
  19707. bytes: byteLength,
  19708. segments
  19709. });
  19710. }
  19711. this.sourceUpdater_.appendBuffer({
  19712. segmentInfo,
  19713. type,
  19714. bytes
  19715. }, this.handleAppendError_.bind(this, {
  19716. segmentInfo,
  19717. type,
  19718. bytes
  19719. }));
  19720. }
  19721. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  19722. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  19723. return;
  19724. }
  19725. const segment = this.pendingSegment_.segment;
  19726. const timingInfoProperty = `${type}TimingInfo`;
  19727. if (!segment[timingInfoProperty]) {
  19728. segment[timingInfoProperty] = {};
  19729. }
  19730. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  19731. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  19732. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  19733. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  19734. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  19735. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  19736. }
  19737. appendData_(segmentInfo, result) {
  19738. const {
  19739. type,
  19740. data
  19741. } = result;
  19742. if (!data || !data.byteLength) {
  19743. return;
  19744. }
  19745. if (type === 'audio' && this.audioDisabled_) {
  19746. return;
  19747. }
  19748. const initSegment = this.getInitSegmentAndUpdateState_({
  19749. type,
  19750. initSegment: result.initSegment,
  19751. playlist: segmentInfo.playlist,
  19752. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  19753. });
  19754. this.appendToSourceBuffer_({
  19755. segmentInfo,
  19756. type,
  19757. initSegment,
  19758. data
  19759. });
  19760. }
  19761. /**
  19762. * load a specific segment from a request into the buffer
  19763. *
  19764. * @private
  19765. */
  19766. loadSegment_(segmentInfo) {
  19767. this.state = 'WAITING';
  19768. this.pendingSegment_ = segmentInfo;
  19769. this.trimBackBuffer_(segmentInfo);
  19770. if (typeof segmentInfo.timestampOffset === 'number') {
  19771. if (this.transmuxer_) {
  19772. this.transmuxer_.postMessage({
  19773. action: 'clearAllMp4Captions'
  19774. });
  19775. }
  19776. }
  19777. if (!this.hasEnoughInfoToLoad_()) {
  19778. this.loadQueue_.push(() => {
  19779. // regenerate the audioAppendStart, timestampOffset, etc as they
  19780. // may have changed since this function was added to the queue.
  19781. const options = _extends({}, segmentInfo, {
  19782. forceTimestampOffset: true
  19783. });
  19784. _extends(segmentInfo, this.generateSegmentInfo_(options));
  19785. this.isPendingTimestampOffset_ = false;
  19786. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  19787. });
  19788. return;
  19789. }
  19790. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  19791. }
  19792. updateTransmuxerAndRequestSegment_(segmentInfo) {
  19793. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  19794. // the transmuxer still needs to be updated before then.
  19795. //
  19796. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  19797. // offset must be passed to the transmuxer for stream correcting adjustments.
  19798. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  19799. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  19800. segmentInfo.gopsToAlignWith = [];
  19801. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  19802. this.transmuxer_.postMessage({
  19803. action: 'reset'
  19804. });
  19805. this.transmuxer_.postMessage({
  19806. action: 'setTimestampOffset',
  19807. timestampOffset: segmentInfo.timestampOffset
  19808. });
  19809. }
  19810. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  19811. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  19812. const isWalkingForward = this.mediaIndex !== null;
  19813. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  19814. // the first timeline
  19815. segmentInfo.timeline > 0;
  19816. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  19817. this.logger_(`Requesting ${segmentInfoString(segmentInfo)}`); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
  19818. // then this init segment has never been seen before and should be appended.
  19819. //
  19820. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  19821. // both to true and leave the decision of whether to append the init segment to append time.
  19822. if (simpleSegment.map && !simpleSegment.map.bytes) {
  19823. this.logger_('going to request init segment.');
  19824. this.appendInitSegment_ = {
  19825. video: true,
  19826. audio: true
  19827. };
  19828. }
  19829. segmentInfo.abortRequests = mediaSegmentRequest({
  19830. xhr: this.vhs_.xhr,
  19831. xhrOptions: this.xhrOptions_,
  19832. decryptionWorker: this.decrypter_,
  19833. segment: simpleSegment,
  19834. abortFn: this.handleAbort_.bind(this, segmentInfo),
  19835. progressFn: this.handleProgress_.bind(this),
  19836. trackInfoFn: this.handleTrackInfo_.bind(this),
  19837. timingInfoFn: this.handleTimingInfo_.bind(this),
  19838. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  19839. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  19840. captionsFn: this.handleCaptions_.bind(this),
  19841. isEndOfTimeline,
  19842. endedTimelineFn: () => {
  19843. this.logger_('received endedtimeline callback');
  19844. },
  19845. id3Fn: this.handleId3_.bind(this),
  19846. dataFn: this.handleData_.bind(this),
  19847. doneFn: this.segmentRequestFinished_.bind(this),
  19848. onTransmuxerLog: ({
  19849. message,
  19850. level,
  19851. stream
  19852. }) => {
  19853. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  19854. }
  19855. });
  19856. }
  19857. /**
  19858. * trim the back buffer so that we don't have too much data
  19859. * in the source buffer
  19860. *
  19861. * @private
  19862. *
  19863. * @param {Object} segmentInfo - the current segment
  19864. */
  19865. trimBackBuffer_(segmentInfo) {
  19866. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  19867. // buffer and a very conservative "garbage collector"
  19868. // We manually clear out the old buffer to ensure
  19869. // we don't trigger the QuotaExceeded error
  19870. // on the source buffer during subsequent appends
  19871. if (removeToTime > 0) {
  19872. this.remove(0, removeToTime);
  19873. }
  19874. }
  19875. /**
  19876. * created a simplified copy of the segment object with just the
  19877. * information necessary to perform the XHR and decryption
  19878. *
  19879. * @private
  19880. *
  19881. * @param {Object} segmentInfo - the current segment
  19882. * @return {Object} a simplified segment object copy
  19883. */
  19884. createSimplifiedSegmentObj_(segmentInfo) {
  19885. const segment = segmentInfo.segment;
  19886. const part = segmentInfo.part;
  19887. const simpleSegment = {
  19888. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  19889. byterange: part ? part.byterange : segment.byterange,
  19890. requestId: segmentInfo.requestId,
  19891. transmuxer: segmentInfo.transmuxer,
  19892. audioAppendStart: segmentInfo.audioAppendStart,
  19893. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  19894. part: segmentInfo.part
  19895. };
  19896. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  19897. if (previousSegment && previousSegment.timeline === segment.timeline) {
  19898. // The baseStartTime of a segment is used to handle rollover when probing the TS
  19899. // segment to retrieve timing information. Since the probe only looks at the media's
  19900. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  19901. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  19902. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  19903. // seconds of media time, so should be used here. The previous segment is used since
  19904. // the end of the previous segment should represent the beginning of the current
  19905. // segment, so long as they are on the same timeline.
  19906. if (previousSegment.videoTimingInfo) {
  19907. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  19908. } else if (previousSegment.audioTimingInfo) {
  19909. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  19910. }
  19911. }
  19912. if (segment.key) {
  19913. // if the media sequence is greater than 2^32, the IV will be incorrect
  19914. // assuming 10s segments, that would be about 1300 years
  19915. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  19916. simpleSegment.key = this.segmentKey(segment.key);
  19917. simpleSegment.key.iv = iv;
  19918. }
  19919. if (segment.map) {
  19920. simpleSegment.map = this.initSegmentForMap(segment.map);
  19921. }
  19922. return simpleSegment;
  19923. }
  19924. saveTransferStats_(stats) {
  19925. // every request counts as a media request even if it has been aborted
  19926. // or canceled due to a timeout
  19927. this.mediaRequests += 1;
  19928. if (stats) {
  19929. this.mediaBytesTransferred += stats.bytesReceived;
  19930. this.mediaTransferDuration += stats.roundTripTime;
  19931. }
  19932. }
  19933. saveBandwidthRelatedStats_(duration, stats) {
  19934. // byteLength will be used for throughput, and should be based on bytes receieved,
  19935. // which we only know at the end of the request and should reflect total bytes
  19936. // downloaded rather than just bytes processed from components of the segment
  19937. this.pendingSegment_.byteLength = stats.bytesReceived;
  19938. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  19939. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  19940. return;
  19941. }
  19942. this.bandwidth = stats.bandwidth;
  19943. this.roundTrip = stats.roundTripTime;
  19944. }
  19945. handleTimeout_() {
  19946. // although the VTT segment loader bandwidth isn't really used, it's good to
  19947. // maintain functinality between segment loaders
  19948. this.mediaRequestsTimedout += 1;
  19949. this.bandwidth = 1;
  19950. this.roundTrip = NaN;
  19951. this.trigger('bandwidthupdate');
  19952. this.trigger('timeout');
  19953. }
  19954. /**
  19955. * Handle the callback from the segmentRequest function and set the
  19956. * associated SegmentLoader state and errors if necessary
  19957. *
  19958. * @private
  19959. */
  19960. segmentRequestFinished_(error, simpleSegment, result) {
  19961. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  19962. // check the call queue directly since this function doesn't need to deal with any
  19963. // data, and can continue even if the source buffers are not set up and we didn't get
  19964. // any data from the segment
  19965. if (this.callQueue_.length) {
  19966. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  19967. return;
  19968. }
  19969. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  19970. if (!this.pendingSegment_) {
  19971. return;
  19972. } // the request was aborted and the SegmentLoader has already started
  19973. // another request. this can happen when the timeout for an aborted
  19974. // request triggers due to a limitation in the XHR library
  19975. // do not count this as any sort of request or we risk double-counting
  19976. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  19977. return;
  19978. } // an error occurred from the active pendingSegment_ so reset everything
  19979. if (error) {
  19980. this.pendingSegment_ = null;
  19981. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  19982. if (error.code === REQUEST_ERRORS.ABORTED) {
  19983. return;
  19984. }
  19985. this.pause(); // the error is really just that at least one of the requests timed-out
  19986. // set the bandwidth to a very low value and trigger an ABR switch to
  19987. // take emergency action
  19988. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  19989. this.handleTimeout_();
  19990. return;
  19991. } // if control-flow has arrived here, then the error is real
  19992. // emit an error event to exclude the current playlist
  19993. this.mediaRequestsErrored += 1;
  19994. this.error(error);
  19995. this.trigger('error');
  19996. return;
  19997. }
  19998. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  19999. // generated for ABR purposes
  20000. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  20001. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  20002. if (result.gopInfo) {
  20003. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  20004. } // Although we may have already started appending on progress, we shouldn't switch the
  20005. // state away from loading until we are officially done loading the segment data.
  20006. this.state = 'APPENDING'; // used for testing
  20007. this.trigger('appending');
  20008. this.waitForAppendsToComplete_(segmentInfo);
  20009. }
  20010. setTimeMapping_(timeline) {
  20011. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  20012. if (timelineMapping !== null) {
  20013. this.timeMapping_ = timelineMapping;
  20014. }
  20015. }
  20016. updateMediaSecondsLoaded_(segment) {
  20017. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  20018. this.mediaSecondsLoaded += segment.end - segment.start;
  20019. } else {
  20020. this.mediaSecondsLoaded += segment.duration;
  20021. }
  20022. }
  20023. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  20024. if (timestampOffset === null) {
  20025. return false;
  20026. } // note that we're potentially using the same timestamp offset for both video and
  20027. // audio
  20028. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  20029. return true;
  20030. }
  20031. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  20032. return true;
  20033. }
  20034. return false;
  20035. }
  20036. trueSegmentStart_({
  20037. currentStart,
  20038. playlist,
  20039. mediaIndex,
  20040. firstVideoFrameTimeForData,
  20041. currentVideoTimestampOffset,
  20042. useVideoTimingInfo,
  20043. videoTimingInfo,
  20044. audioTimingInfo
  20045. }) {
  20046. if (typeof currentStart !== 'undefined') {
  20047. // if start was set once, keep using it
  20048. return currentStart;
  20049. }
  20050. if (!useVideoTimingInfo) {
  20051. return audioTimingInfo.start;
  20052. }
  20053. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  20054. // within that segment. Since the transmuxer maintains a cache of incomplete data
  20055. // from and/or the last frame seen, the start time may reflect a frame that starts
  20056. // in the previous segment. Check for that case and ensure the start time is
  20057. // accurate for the segment.
  20058. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  20059. return firstVideoFrameTimeForData;
  20060. }
  20061. return videoTimingInfo.start;
  20062. }
  20063. waitForAppendsToComplete_(segmentInfo) {
  20064. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  20065. if (!trackInfo) {
  20066. this.error({
  20067. message: 'No starting media returned, likely due to an unsupported media format.',
  20068. playlistExclusionDuration: Infinity
  20069. });
  20070. this.trigger('error');
  20071. return;
  20072. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  20073. // on each queue this loader is responsible for to ensure that the appends are
  20074. // complete.
  20075. const {
  20076. hasAudio,
  20077. hasVideo,
  20078. isMuxed
  20079. } = trackInfo;
  20080. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  20081. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  20082. segmentInfo.waitingOnAppends = 0; // segments with no data
  20083. if (!segmentInfo.hasAppendedData_) {
  20084. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  20085. // When there's no audio or video data in the segment, there's no audio or video
  20086. // timing information.
  20087. //
  20088. // If there's no audio or video timing information, then the timestamp offset
  20089. // can't be adjusted to the appropriate value for the transmuxer and source
  20090. // buffers.
  20091. //
  20092. // Therefore, the next segment should be used to set the timestamp offset.
  20093. this.isPendingTimestampOffset_ = true;
  20094. } // override settings for metadata only segments
  20095. segmentInfo.timingInfo = {
  20096. start: 0
  20097. };
  20098. segmentInfo.waitingOnAppends++;
  20099. if (!this.isPendingTimestampOffset_) {
  20100. // update the timestampoffset
  20101. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  20102. // no video/audio data.
  20103. this.processMetadataQueue_();
  20104. } // append is "done" instantly with no data.
  20105. this.checkAppendsDone_(segmentInfo);
  20106. return;
  20107. } // Since source updater could call back synchronously, do the increments first.
  20108. if (waitForVideo) {
  20109. segmentInfo.waitingOnAppends++;
  20110. }
  20111. if (waitForAudio) {
  20112. segmentInfo.waitingOnAppends++;
  20113. }
  20114. if (waitForVideo) {
  20115. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  20116. }
  20117. if (waitForAudio) {
  20118. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  20119. }
  20120. }
  20121. checkAppendsDone_(segmentInfo) {
  20122. if (this.checkForAbort_(segmentInfo.requestId)) {
  20123. return;
  20124. }
  20125. segmentInfo.waitingOnAppends--;
  20126. if (segmentInfo.waitingOnAppends === 0) {
  20127. this.handleAppendsDone_();
  20128. }
  20129. }
  20130. checkForIllegalMediaSwitch(trackInfo) {
  20131. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  20132. if (illegalMediaSwitchError) {
  20133. this.error({
  20134. message: illegalMediaSwitchError,
  20135. playlistExclusionDuration: Infinity
  20136. });
  20137. this.trigger('error');
  20138. return true;
  20139. }
  20140. return false;
  20141. }
  20142. updateSourceBufferTimestampOffset_(segmentInfo) {
  20143. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  20144. // priority, timing-wise, so we must wait
  20145. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  20146. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  20147. this.loaderType_ !== 'main') {
  20148. return;
  20149. }
  20150. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  20151. // the timing info here comes from video. In the event that the audio is longer than
  20152. // the video, this will trim the start of the audio.
  20153. // This also trims any offset from 0 at the beginning of the media
  20154. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  20155. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  20156. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  20157. timingInfo: segmentInfo.timingInfo
  20158. }); // In the event that there are part segment downloads, each will try to update the
  20159. // timestamp offset. Retaining this bit of state prevents us from updating in the
  20160. // future (within the same segment), however, there may be a better way to handle it.
  20161. segmentInfo.changedTimestampOffset = true;
  20162. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  20163. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  20164. didChange = true;
  20165. }
  20166. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  20167. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  20168. didChange = true;
  20169. }
  20170. if (didChange) {
  20171. this.trigger('timestampoffset');
  20172. }
  20173. }
  20174. getSegmentStartTimeForTimestampOffsetCalculation_({
  20175. videoTimingInfo,
  20176. audioTimingInfo,
  20177. timingInfo
  20178. }) {
  20179. if (!this.useDtsForTimestampOffset_) {
  20180. return timingInfo.start;
  20181. }
  20182. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  20183. return videoTimingInfo.transmuxedDecodeStart;
  20184. } // handle audio only
  20185. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  20186. return audioTimingInfo.transmuxedDecodeStart;
  20187. } // handle content not transmuxed (e.g., MP4)
  20188. return timingInfo.start;
  20189. }
  20190. updateTimingInfoEnd_(segmentInfo) {
  20191. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  20192. const trackInfo = this.getMediaInfo_();
  20193. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  20194. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  20195. if (!prioritizedTimingInfo) {
  20196. return;
  20197. }
  20198. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  20199. // current example is the case of fmp4), so use the rough duration to calculate an
  20200. // end time.
  20201. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  20202. }
  20203. /**
  20204. * callback to run when appendBuffer is finished. detects if we are
  20205. * in a good state to do things with the data we got, or if we need
  20206. * to wait for more
  20207. *
  20208. * @private
  20209. */
  20210. handleAppendsDone_() {
  20211. // appendsdone can cause an abort
  20212. if (this.pendingSegment_) {
  20213. this.trigger('appendsdone');
  20214. }
  20215. if (!this.pendingSegment_) {
  20216. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  20217. // all appending cases?
  20218. if (!this.paused()) {
  20219. this.monitorBuffer_();
  20220. }
  20221. return;
  20222. }
  20223. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  20224. // best to wait until all appends are done so we're sure that the primary media is
  20225. // finished (and we have its end time).
  20226. this.updateTimingInfoEnd_(segmentInfo);
  20227. if (this.shouldSaveSegmentTimingInfo_) {
  20228. // Timeline mappings should only be saved for the main loader. This is for multiple
  20229. // reasons:
  20230. //
  20231. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  20232. // and the main loader try to save the timeline mapping, whichever comes later
  20233. // will overwrite the first. In theory this is OK, as the mappings should be the
  20234. // same, however, it breaks for (2)
  20235. // 2) In the event of a live stream, the initial live point will make for a somewhat
  20236. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  20237. // the mapping will be off for one of the streams, dependent on which one was
  20238. // first saved (see (1)).
  20239. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  20240. //
  20241. // Since the audio loader will wait for the main loader to load the first segment,
  20242. // the main loader will save the first timeline mapping, and ensure that there won't
  20243. // be a case where audio loads two segments without saving a mapping (thus leading
  20244. // to missing segment timing info).
  20245. this.syncController_.saveSegmentTimingInfo({
  20246. segmentInfo,
  20247. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  20248. });
  20249. }
  20250. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  20251. if (segmentDurationMessage) {
  20252. if (segmentDurationMessage.severity === 'warn') {
  20253. videojs__default["default"].log.warn(segmentDurationMessage.message);
  20254. } else {
  20255. this.logger_(segmentDurationMessage.message);
  20256. }
  20257. }
  20258. this.recordThroughput_(segmentInfo);
  20259. this.pendingSegment_ = null;
  20260. this.state = 'READY';
  20261. if (segmentInfo.isSyncRequest) {
  20262. this.trigger('syncinfoupdate'); // if the sync request was not appended
  20263. // then it was not the correct segment.
  20264. // throw it away and use the data it gave us
  20265. // to get the correct one.
  20266. if (!segmentInfo.hasAppendedData_) {
  20267. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  20268. return;
  20269. }
  20270. }
  20271. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  20272. this.addSegmentMetadataCue_(segmentInfo);
  20273. this.fetchAtBuffer_ = true;
  20274. if (this.currentTimeline_ !== segmentInfo.timeline) {
  20275. this.timelineChangeController_.lastTimelineChange({
  20276. type: this.loaderType_,
  20277. from: this.currentTimeline_,
  20278. to: segmentInfo.timeline
  20279. }); // If audio is not disabled, the main segment loader is responsible for updating
  20280. // the audio timeline as well. If the content is video only, this won't have any
  20281. // impact.
  20282. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  20283. this.timelineChangeController_.lastTimelineChange({
  20284. type: 'audio',
  20285. from: this.currentTimeline_,
  20286. to: segmentInfo.timeline
  20287. });
  20288. }
  20289. }
  20290. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  20291. // the following conditional otherwise it may consider this a bad "guess"
  20292. // and attempt to resync when the post-update seekable window and live
  20293. // point would mean that this was the perfect segment to fetch
  20294. this.trigger('syncinfoupdate');
  20295. const segment = segmentInfo.segment;
  20296. const part = segmentInfo.part;
  20297. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  20298. const badPartGuess = part && part.end && this.currentTime_() - part.end > segmentInfo.playlist.partTargetDuration * 3; // If we previously appended a segment/part that ends more than 3 part/targetDurations before
  20299. // the currentTime_ that means that our conservative guess was too conservative.
  20300. // In that case, reset the loader state so that we try to use any information gained
  20301. // from the previous request to create a new, more accurate, sync-point.
  20302. if (badSegmentGuess || badPartGuess) {
  20303. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  20304. this.resetEverything();
  20305. return;
  20306. }
  20307. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  20308. // and conservatively guess
  20309. if (isWalkingForward) {
  20310. this.trigger('bandwidthupdate');
  20311. }
  20312. this.trigger('progress');
  20313. this.mediaIndex = segmentInfo.mediaIndex;
  20314. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  20315. // buffer, end the stream. this ensures the "ended" event will
  20316. // fire if playback reaches that point.
  20317. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  20318. this.endOfStream();
  20319. } // used for testing
  20320. this.trigger('appended');
  20321. if (segmentInfo.hasAppendedData_) {
  20322. this.mediaAppends++;
  20323. }
  20324. if (!this.paused()) {
  20325. this.monitorBuffer_();
  20326. }
  20327. }
  20328. /**
  20329. * Records the current throughput of the decrypt, transmux, and append
  20330. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  20331. * moving average of the throughput. `throughput.count` is the number of
  20332. * data points in the average.
  20333. *
  20334. * @private
  20335. * @param {Object} segmentInfo the object returned by loadSegment
  20336. */
  20337. recordThroughput_(segmentInfo) {
  20338. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  20339. this.logger_(`Ignoring segment's throughput because its duration of ${segmentInfo.duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  20340. return;
  20341. }
  20342. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  20343. // by zero in the case where the throughput is ridiculously high
  20344. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  20345. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  20346. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  20347. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  20348. }
  20349. /**
  20350. * Adds a cue to the segment-metadata track with some metadata information about the
  20351. * segment
  20352. *
  20353. * @private
  20354. * @param {Object} segmentInfo
  20355. * the object returned by loadSegment
  20356. * @method addSegmentMetadataCue_
  20357. */
  20358. addSegmentMetadataCue_(segmentInfo) {
  20359. if (!this.segmentMetadataTrack_) {
  20360. return;
  20361. }
  20362. const segment = segmentInfo.segment;
  20363. const start = segment.start;
  20364. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  20365. if (!finite(start) || !finite(end)) {
  20366. return;
  20367. }
  20368. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  20369. const Cue = window.WebKitDataCue || window.VTTCue;
  20370. const value = {
  20371. custom: segment.custom,
  20372. dateTimeObject: segment.dateTimeObject,
  20373. dateTimeString: segment.dateTimeString,
  20374. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  20375. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  20376. codecs: segmentInfo.playlist.attributes.CODECS,
  20377. byteLength: segmentInfo.byteLength,
  20378. uri: segmentInfo.uri,
  20379. timeline: segmentInfo.timeline,
  20380. playlist: segmentInfo.playlist.id,
  20381. start,
  20382. end
  20383. };
  20384. const data = JSON.stringify(value);
  20385. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  20386. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  20387. cue.value = value;
  20388. this.segmentMetadataTrack_.addCue(cue);
  20389. }
  20390. }
  20391. function noop() {}
  20392. const toTitleCase = function (string) {
  20393. if (typeof string !== 'string') {
  20394. return string;
  20395. }
  20396. return string.replace(/./, w => w.toUpperCase());
  20397. };
  20398. /**
  20399. * @file source-updater.js
  20400. */
  20401. const bufferTypes = ['video', 'audio'];
  20402. const updating = (type, sourceUpdater) => {
  20403. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20404. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  20405. };
  20406. const nextQueueIndexOfType = (type, queue) => {
  20407. for (let i = 0; i < queue.length; i++) {
  20408. const queueEntry = queue[i];
  20409. if (queueEntry.type === 'mediaSource') {
  20410. // If the next entry is a media source entry (uses multiple source buffers), block
  20411. // processing to allow it to go through first.
  20412. return null;
  20413. }
  20414. if (queueEntry.type === type) {
  20415. return i;
  20416. }
  20417. }
  20418. return null;
  20419. };
  20420. const shiftQueue = (type, sourceUpdater) => {
  20421. if (sourceUpdater.queue.length === 0) {
  20422. return;
  20423. }
  20424. let queueIndex = 0;
  20425. let queueEntry = sourceUpdater.queue[queueIndex];
  20426. if (queueEntry.type === 'mediaSource') {
  20427. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  20428. sourceUpdater.queue.shift();
  20429. queueEntry.action(sourceUpdater);
  20430. if (queueEntry.doneFn) {
  20431. queueEntry.doneFn();
  20432. } // Only specific source buffer actions must wait for async updateend events. Media
  20433. // Source actions process synchronously. Therefore, both audio and video source
  20434. // buffers are now clear to process the next queue entries.
  20435. shiftQueue('audio', sourceUpdater);
  20436. shiftQueue('video', sourceUpdater);
  20437. } // Media Source actions require both source buffers, so if the media source action
  20438. // couldn't process yet (because one or both source buffers are busy), block other
  20439. // queue actions until both are available and the media source action can process.
  20440. return;
  20441. }
  20442. if (type === 'mediaSource') {
  20443. // If the queue was shifted by a media source action (this happens when pushing a
  20444. // media source action onto the queue), then it wasn't from an updateend event from an
  20445. // audio or video source buffer, so there's no change from previous state, and no
  20446. // processing should be done.
  20447. return;
  20448. } // Media source queue entries don't need to consider whether the source updater is
  20449. // started (i.e., source buffers are created) as they don't need the source buffers, but
  20450. // source buffer queue entries do.
  20451. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  20452. return;
  20453. }
  20454. if (queueEntry.type !== type) {
  20455. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  20456. if (queueIndex === null) {
  20457. // Either there's no queue entry that uses this source buffer type in the queue, or
  20458. // there's a media source queue entry before the next entry of this type, in which
  20459. // case wait for that action to process first.
  20460. return;
  20461. }
  20462. queueEntry = sourceUpdater.queue[queueIndex];
  20463. }
  20464. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  20465. //
  20466. // The queue pending operation must be set before the action is performed in the event
  20467. // that the action results in a synchronous event that is acted upon. For instance, if
  20468. // an exception is thrown that can be handled, it's possible that new actions will be
  20469. // appended to an empty queue and immediately executed, but would not have the correct
  20470. // pending information if this property was set after the action was performed.
  20471. sourceUpdater.queuePending[type] = queueEntry;
  20472. queueEntry.action(type, sourceUpdater);
  20473. if (!queueEntry.doneFn) {
  20474. // synchronous operation, process next entry
  20475. sourceUpdater.queuePending[type] = null;
  20476. shiftQueue(type, sourceUpdater);
  20477. return;
  20478. }
  20479. };
  20480. const cleanupBuffer = (type, sourceUpdater) => {
  20481. const buffer = sourceUpdater[`${type}Buffer`];
  20482. const titleType = toTitleCase(type);
  20483. if (!buffer) {
  20484. return;
  20485. }
  20486. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  20487. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  20488. sourceUpdater.codecs[type] = null;
  20489. sourceUpdater[`${type}Buffer`] = null;
  20490. };
  20491. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  20492. const actions = {
  20493. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  20494. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20495. // or the media source does not contain this source buffer.
  20496. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20497. return;
  20498. }
  20499. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  20500. try {
  20501. sourceBuffer.appendBuffer(bytes);
  20502. } catch (e) {
  20503. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  20504. sourceUpdater.queuePending[type] = null;
  20505. onError(e);
  20506. }
  20507. },
  20508. remove: (start, end) => (type, sourceUpdater) => {
  20509. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20510. // or the media source does not contain this source buffer.
  20511. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20512. return;
  20513. }
  20514. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  20515. try {
  20516. sourceBuffer.remove(start, end);
  20517. } catch (e) {
  20518. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  20519. }
  20520. },
  20521. timestampOffset: offset => (type, sourceUpdater) => {
  20522. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20523. // or the media source does not contain this source buffer.
  20524. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20525. return;
  20526. }
  20527. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  20528. sourceBuffer.timestampOffset = offset;
  20529. },
  20530. callback: callback => (type, sourceUpdater) => {
  20531. callback();
  20532. },
  20533. endOfStream: error => sourceUpdater => {
  20534. if (sourceUpdater.mediaSource.readyState !== 'open') {
  20535. return;
  20536. }
  20537. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  20538. try {
  20539. sourceUpdater.mediaSource.endOfStream(error);
  20540. } catch (e) {
  20541. videojs__default["default"].log.warn('Failed to call media source endOfStream', e);
  20542. }
  20543. },
  20544. duration: duration => sourceUpdater => {
  20545. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  20546. try {
  20547. sourceUpdater.mediaSource.duration = duration;
  20548. } catch (e) {
  20549. videojs__default["default"].log.warn('Failed to set media source duration', e);
  20550. }
  20551. },
  20552. abort: () => (type, sourceUpdater) => {
  20553. if (sourceUpdater.mediaSource.readyState !== 'open') {
  20554. return;
  20555. }
  20556. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20557. // or the media source does not contain this source buffer.
  20558. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20559. return;
  20560. }
  20561. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  20562. try {
  20563. sourceBuffer.abort();
  20564. } catch (e) {
  20565. videojs__default["default"].log.warn(`Failed to abort on ${type}Buffer`, e);
  20566. }
  20567. },
  20568. addSourceBuffer: (type, codec) => sourceUpdater => {
  20569. const titleType = toTitleCase(type);
  20570. const mime = getMimeForCodec(codec);
  20571. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  20572. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  20573. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  20574. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  20575. sourceUpdater.codecs[type] = codec;
  20576. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  20577. },
  20578. removeSourceBuffer: type => sourceUpdater => {
  20579. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20580. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  20581. // or the media source does not contain this source buffer.
  20582. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20583. return;
  20584. }
  20585. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  20586. try {
  20587. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  20588. } catch (e) {
  20589. videojs__default["default"].log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  20590. }
  20591. },
  20592. changeType: codec => (type, sourceUpdater) => {
  20593. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20594. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  20595. // or the media source does not contain this source buffer.
  20596. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20597. return;
  20598. } // do not update codec if we don't need to.
  20599. if (sourceUpdater.codecs[type] === codec) {
  20600. return;
  20601. }
  20602. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  20603. sourceBuffer.changeType(mime);
  20604. sourceUpdater.codecs[type] = codec;
  20605. }
  20606. };
  20607. const pushQueue = ({
  20608. type,
  20609. sourceUpdater,
  20610. action,
  20611. doneFn,
  20612. name
  20613. }) => {
  20614. sourceUpdater.queue.push({
  20615. type,
  20616. action,
  20617. doneFn,
  20618. name
  20619. });
  20620. shiftQueue(type, sourceUpdater);
  20621. };
  20622. const onUpdateend = (type, sourceUpdater) => e => {
  20623. // Although there should, in theory, be a pending action for any updateend receieved,
  20624. // there are some actions that may trigger updateend events without set definitions in
  20625. // the w3c spec. For instance, setting the duration on the media source may trigger
  20626. // updateend events on source buffers. This does not appear to be in the spec. As such,
  20627. // if we encounter an updateend without a corresponding pending action from our queue
  20628. // for that source buffer type, process the next action.
  20629. if (sourceUpdater.queuePending[type]) {
  20630. const doneFn = sourceUpdater.queuePending[type].doneFn;
  20631. sourceUpdater.queuePending[type] = null;
  20632. if (doneFn) {
  20633. // if there's an error, report it
  20634. doneFn(sourceUpdater[`${type}Error_`]);
  20635. }
  20636. }
  20637. shiftQueue(type, sourceUpdater);
  20638. };
  20639. /**
  20640. * A queue of callbacks to be serialized and applied when a
  20641. * MediaSource and its associated SourceBuffers are not in the
  20642. * updating state. It is used by the segment loader to update the
  20643. * underlying SourceBuffers when new data is loaded, for instance.
  20644. *
  20645. * @class SourceUpdater
  20646. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  20647. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  20648. */
  20649. class SourceUpdater extends videojs__default["default"].EventTarget {
  20650. constructor(mediaSource) {
  20651. super();
  20652. this.mediaSource = mediaSource;
  20653. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  20654. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  20655. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  20656. this.audioTimestampOffset_ = 0;
  20657. this.videoTimestampOffset_ = 0;
  20658. this.queue = [];
  20659. this.queuePending = {
  20660. audio: null,
  20661. video: null
  20662. };
  20663. this.delayedAudioAppendQueue_ = [];
  20664. this.videoAppendQueued_ = false;
  20665. this.codecs = {};
  20666. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  20667. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  20668. this.onVideoError_ = e => {
  20669. // used for debugging
  20670. this.videoError_ = e;
  20671. };
  20672. this.onAudioError_ = e => {
  20673. // used for debugging
  20674. this.audioError_ = e;
  20675. };
  20676. this.createdSourceBuffers_ = false;
  20677. this.initializedEme_ = false;
  20678. this.triggeredReady_ = false;
  20679. }
  20680. initializedEme() {
  20681. this.initializedEme_ = true;
  20682. this.triggerReady();
  20683. }
  20684. hasCreatedSourceBuffers() {
  20685. // if false, likely waiting on one of the segment loaders to get enough data to create
  20686. // source buffers
  20687. return this.createdSourceBuffers_;
  20688. }
  20689. hasInitializedAnyEme() {
  20690. return this.initializedEme_;
  20691. }
  20692. ready() {
  20693. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  20694. }
  20695. createSourceBuffers(codecs) {
  20696. if (this.hasCreatedSourceBuffers()) {
  20697. // already created them before
  20698. return;
  20699. } // the intial addOrChangeSourceBuffers will always be
  20700. // two add buffers.
  20701. this.addOrChangeSourceBuffers(codecs);
  20702. this.createdSourceBuffers_ = true;
  20703. this.trigger('createdsourcebuffers');
  20704. this.triggerReady();
  20705. }
  20706. triggerReady() {
  20707. // only allow ready to be triggered once, this prevents the case
  20708. // where:
  20709. // 1. we trigger createdsourcebuffers
  20710. // 2. ie 11 synchronously initializates eme
  20711. // 3. the synchronous initialization causes us to trigger ready
  20712. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  20713. if (this.ready() && !this.triggeredReady_) {
  20714. this.triggeredReady_ = true;
  20715. this.trigger('ready');
  20716. }
  20717. }
  20718. /**
  20719. * Add a type of source buffer to the media source.
  20720. *
  20721. * @param {string} type
  20722. * The type of source buffer to add.
  20723. *
  20724. * @param {string} codec
  20725. * The codec to add the source buffer with.
  20726. */
  20727. addSourceBuffer(type, codec) {
  20728. pushQueue({
  20729. type: 'mediaSource',
  20730. sourceUpdater: this,
  20731. action: actions.addSourceBuffer(type, codec),
  20732. name: 'addSourceBuffer'
  20733. });
  20734. }
  20735. /**
  20736. * call abort on a source buffer.
  20737. *
  20738. * @param {string} type
  20739. * The type of source buffer to call abort on.
  20740. */
  20741. abort(type) {
  20742. pushQueue({
  20743. type,
  20744. sourceUpdater: this,
  20745. action: actions.abort(type),
  20746. name: 'abort'
  20747. });
  20748. }
  20749. /**
  20750. * Call removeSourceBuffer and remove a specific type
  20751. * of source buffer on the mediaSource.
  20752. *
  20753. * @param {string} type
  20754. * The type of source buffer to remove.
  20755. */
  20756. removeSourceBuffer(type) {
  20757. if (!this.canRemoveSourceBuffer()) {
  20758. videojs__default["default"].log.error('removeSourceBuffer is not supported!');
  20759. return;
  20760. }
  20761. pushQueue({
  20762. type: 'mediaSource',
  20763. sourceUpdater: this,
  20764. action: actions.removeSourceBuffer(type),
  20765. name: 'removeSourceBuffer'
  20766. });
  20767. }
  20768. /**
  20769. * Whether or not the removeSourceBuffer function is supported
  20770. * on the mediaSource.
  20771. *
  20772. * @return {boolean}
  20773. * if removeSourceBuffer can be called.
  20774. */
  20775. canRemoveSourceBuffer() {
  20776. // IE reports that it supports removeSourceBuffer, but often throws
  20777. // errors when attempting to use the function. So we report that it
  20778. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  20779. // throws errors, so we report that it does not support this as well.
  20780. return !videojs__default["default"].browser.IE_VERSION && !videojs__default["default"].browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  20781. }
  20782. /**
  20783. * Whether or not the changeType function is supported
  20784. * on our SourceBuffers.
  20785. *
  20786. * @return {boolean}
  20787. * if changeType can be called.
  20788. */
  20789. static canChangeType() {
  20790. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  20791. }
  20792. /**
  20793. * Whether or not the changeType function is supported
  20794. * on our SourceBuffers.
  20795. *
  20796. * @return {boolean}
  20797. * if changeType can be called.
  20798. */
  20799. canChangeType() {
  20800. return this.constructor.canChangeType();
  20801. }
  20802. /**
  20803. * Call the changeType function on a source buffer, given the code and type.
  20804. *
  20805. * @param {string} type
  20806. * The type of source buffer to call changeType on.
  20807. *
  20808. * @param {string} codec
  20809. * The codec string to change type with on the source buffer.
  20810. */
  20811. changeType(type, codec) {
  20812. if (!this.canChangeType()) {
  20813. videojs__default["default"].log.error('changeType is not supported!');
  20814. return;
  20815. }
  20816. pushQueue({
  20817. type,
  20818. sourceUpdater: this,
  20819. action: actions.changeType(codec),
  20820. name: 'changeType'
  20821. });
  20822. }
  20823. /**
  20824. * Add source buffers with a codec or, if they are already created,
  20825. * call changeType on source buffers using changeType.
  20826. *
  20827. * @param {Object} codecs
  20828. * Codecs to switch to
  20829. */
  20830. addOrChangeSourceBuffers(codecs) {
  20831. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  20832. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  20833. }
  20834. Object.keys(codecs).forEach(type => {
  20835. const codec = codecs[type];
  20836. if (!this.hasCreatedSourceBuffers()) {
  20837. return this.addSourceBuffer(type, codec);
  20838. }
  20839. if (this.canChangeType()) {
  20840. this.changeType(type, codec);
  20841. }
  20842. });
  20843. }
  20844. /**
  20845. * Queue an update to append an ArrayBuffer.
  20846. *
  20847. * @param {MediaObject} object containing audioBytes and/or videoBytes
  20848. * @param {Function} done the function to call when done
  20849. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  20850. */
  20851. appendBuffer(options, doneFn) {
  20852. const {
  20853. segmentInfo,
  20854. type,
  20855. bytes
  20856. } = options;
  20857. this.processedAppend_ = true;
  20858. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  20859. this.delayedAudioAppendQueue_.push([options, doneFn]);
  20860. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  20861. return;
  20862. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  20863. // not be fired. This means that the queue will be blocked until the next action
  20864. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  20865. // these errors by calling the doneFn with the specific error.
  20866. const onError = doneFn;
  20867. pushQueue({
  20868. type,
  20869. sourceUpdater: this,
  20870. action: actions.appendBuffer(bytes, segmentInfo || {
  20871. mediaIndex: -1
  20872. }, onError),
  20873. doneFn,
  20874. name: 'appendBuffer'
  20875. });
  20876. if (type === 'video') {
  20877. this.videoAppendQueued_ = true;
  20878. if (!this.delayedAudioAppendQueue_.length) {
  20879. return;
  20880. }
  20881. const queue = this.delayedAudioAppendQueue_.slice();
  20882. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  20883. this.delayedAudioAppendQueue_.length = 0;
  20884. queue.forEach(que => {
  20885. this.appendBuffer.apply(this, que);
  20886. });
  20887. }
  20888. }
  20889. /**
  20890. * Get the audio buffer's buffered timerange.
  20891. *
  20892. * @return {TimeRange}
  20893. * The audio buffer's buffered time range
  20894. */
  20895. audioBuffered() {
  20896. // no media source/source buffer or it isn't in the media sources
  20897. // source buffer list
  20898. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  20899. return createTimeRanges();
  20900. }
  20901. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  20902. }
  20903. /**
  20904. * Get the video buffer's buffered timerange.
  20905. *
  20906. * @return {TimeRange}
  20907. * The video buffer's buffered time range
  20908. */
  20909. videoBuffered() {
  20910. // no media source/source buffer or it isn't in the media sources
  20911. // source buffer list
  20912. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  20913. return createTimeRanges();
  20914. }
  20915. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  20916. }
  20917. /**
  20918. * Get a combined video/audio buffer's buffered timerange.
  20919. *
  20920. * @return {TimeRange}
  20921. * the combined time range
  20922. */
  20923. buffered() {
  20924. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  20925. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  20926. if (audio && !video) {
  20927. return this.audioBuffered();
  20928. }
  20929. if (video && !audio) {
  20930. return this.videoBuffered();
  20931. }
  20932. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  20933. }
  20934. /**
  20935. * Add a callback to the queue that will set duration on the mediaSource.
  20936. *
  20937. * @param {number} duration
  20938. * The duration to set
  20939. *
  20940. * @param {Function} [doneFn]
  20941. * function to run after duration has been set.
  20942. */
  20943. setDuration(duration, doneFn = noop) {
  20944. // In order to set the duration on the media source, it's necessary to wait for all
  20945. // source buffers to no longer be updating. "If the updating attribute equals true on
  20946. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  20947. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  20948. pushQueue({
  20949. type: 'mediaSource',
  20950. sourceUpdater: this,
  20951. action: actions.duration(duration),
  20952. name: 'duration',
  20953. doneFn
  20954. });
  20955. }
  20956. /**
  20957. * Add a mediaSource endOfStream call to the queue
  20958. *
  20959. * @param {Error} [error]
  20960. * Call endOfStream with an error
  20961. *
  20962. * @param {Function} [doneFn]
  20963. * A function that should be called when the
  20964. * endOfStream call has finished.
  20965. */
  20966. endOfStream(error = null, doneFn = noop) {
  20967. if (typeof error !== 'string') {
  20968. error = undefined;
  20969. } // In order to set the duration on the media source, it's necessary to wait for all
  20970. // source buffers to no longer be updating. "If the updating attribute equals true on
  20971. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  20972. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  20973. pushQueue({
  20974. type: 'mediaSource',
  20975. sourceUpdater: this,
  20976. action: actions.endOfStream(error),
  20977. name: 'endOfStream',
  20978. doneFn
  20979. });
  20980. }
  20981. /**
  20982. * Queue an update to remove a time range from the buffer.
  20983. *
  20984. * @param {number} start where to start the removal
  20985. * @param {number} end where to end the removal
  20986. * @param {Function} [done=noop] optional callback to be executed when the remove
  20987. * operation is complete
  20988. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  20989. */
  20990. removeAudio(start, end, done = noop) {
  20991. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  20992. done();
  20993. return;
  20994. }
  20995. pushQueue({
  20996. type: 'audio',
  20997. sourceUpdater: this,
  20998. action: actions.remove(start, end),
  20999. doneFn: done,
  21000. name: 'remove'
  21001. });
  21002. }
  21003. /**
  21004. * Queue an update to remove a time range from the buffer.
  21005. *
  21006. * @param {number} start where to start the removal
  21007. * @param {number} end where to end the removal
  21008. * @param {Function} [done=noop] optional callback to be executed when the remove
  21009. * operation is complete
  21010. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  21011. */
  21012. removeVideo(start, end, done = noop) {
  21013. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  21014. done();
  21015. return;
  21016. }
  21017. pushQueue({
  21018. type: 'video',
  21019. sourceUpdater: this,
  21020. action: actions.remove(start, end),
  21021. doneFn: done,
  21022. name: 'remove'
  21023. });
  21024. }
  21025. /**
  21026. * Whether the underlying sourceBuffer is updating or not
  21027. *
  21028. * @return {boolean} the updating status of the SourceBuffer
  21029. */
  21030. updating() {
  21031. // the audio/video source buffer is updating
  21032. if (updating('audio', this) || updating('video', this)) {
  21033. return true;
  21034. }
  21035. return false;
  21036. }
  21037. /**
  21038. * Set/get the timestampoffset on the audio SourceBuffer
  21039. *
  21040. * @return {number} the timestamp offset
  21041. */
  21042. audioTimestampOffset(offset) {
  21043. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  21044. this.audioTimestampOffset_ !== offset) {
  21045. pushQueue({
  21046. type: 'audio',
  21047. sourceUpdater: this,
  21048. action: actions.timestampOffset(offset),
  21049. name: 'timestampOffset'
  21050. });
  21051. this.audioTimestampOffset_ = offset;
  21052. }
  21053. return this.audioTimestampOffset_;
  21054. }
  21055. /**
  21056. * Set/get the timestampoffset on the video SourceBuffer
  21057. *
  21058. * @return {number} the timestamp offset
  21059. */
  21060. videoTimestampOffset(offset) {
  21061. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  21062. this.videoTimestampOffset !== offset) {
  21063. pushQueue({
  21064. type: 'video',
  21065. sourceUpdater: this,
  21066. action: actions.timestampOffset(offset),
  21067. name: 'timestampOffset'
  21068. });
  21069. this.videoTimestampOffset_ = offset;
  21070. }
  21071. return this.videoTimestampOffset_;
  21072. }
  21073. /**
  21074. * Add a function to the queue that will be called
  21075. * when it is its turn to run in the audio queue.
  21076. *
  21077. * @param {Function} callback
  21078. * The callback to queue.
  21079. */
  21080. audioQueueCallback(callback) {
  21081. if (!this.audioBuffer) {
  21082. return;
  21083. }
  21084. pushQueue({
  21085. type: 'audio',
  21086. sourceUpdater: this,
  21087. action: actions.callback(callback),
  21088. name: 'callback'
  21089. });
  21090. }
  21091. /**
  21092. * Add a function to the queue that will be called
  21093. * when it is its turn to run in the video queue.
  21094. *
  21095. * @param {Function} callback
  21096. * The callback to queue.
  21097. */
  21098. videoQueueCallback(callback) {
  21099. if (!this.videoBuffer) {
  21100. return;
  21101. }
  21102. pushQueue({
  21103. type: 'video',
  21104. sourceUpdater: this,
  21105. action: actions.callback(callback),
  21106. name: 'callback'
  21107. });
  21108. }
  21109. /**
  21110. * dispose of the source updater and the underlying sourceBuffer
  21111. */
  21112. dispose() {
  21113. this.trigger('dispose');
  21114. bufferTypes.forEach(type => {
  21115. this.abort(type);
  21116. if (this.canRemoveSourceBuffer()) {
  21117. this.removeSourceBuffer(type);
  21118. } else {
  21119. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  21120. }
  21121. });
  21122. this.videoAppendQueued_ = false;
  21123. this.delayedAudioAppendQueue_.length = 0;
  21124. if (this.sourceopenListener_) {
  21125. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  21126. }
  21127. this.off();
  21128. }
  21129. }
  21130. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  21131. /**
  21132. * @file vtt-segment-loader.js
  21133. */
  21134. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  21135. class NoVttJsError extends Error {
  21136. constructor() {
  21137. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  21138. }
  21139. }
  21140. /**
  21141. * An object that manages segment loading and appending.
  21142. *
  21143. * @class VTTSegmentLoader
  21144. * @param {Object} options required and optional options
  21145. * @extends videojs.EventTarget
  21146. */
  21147. class VTTSegmentLoader extends SegmentLoader {
  21148. constructor(settings, options = {}) {
  21149. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  21150. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  21151. this.mediaSource_ = null;
  21152. this.subtitlesTrack_ = null;
  21153. this.loaderType_ = 'subtitle';
  21154. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  21155. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  21156. // the sync controller leads to improper behavior.
  21157. this.shouldSaveSegmentTimingInfo_ = false;
  21158. }
  21159. createTransmuxer_() {
  21160. // don't need to transmux any subtitles
  21161. return null;
  21162. }
  21163. /**
  21164. * Indicates which time ranges are buffered
  21165. *
  21166. * @return {TimeRange}
  21167. * TimeRange object representing the current buffered ranges
  21168. */
  21169. buffered_() {
  21170. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  21171. return createTimeRanges();
  21172. }
  21173. const cues = this.subtitlesTrack_.cues;
  21174. const start = cues[0].startTime;
  21175. const end = cues[cues.length - 1].startTime;
  21176. return createTimeRanges([[start, end]]);
  21177. }
  21178. /**
  21179. * Gets and sets init segment for the provided map
  21180. *
  21181. * @param {Object} map
  21182. * The map object representing the init segment to get or set
  21183. * @param {boolean=} set
  21184. * If true, the init segment for the provided map should be saved
  21185. * @return {Object}
  21186. * map object for desired init segment
  21187. */
  21188. initSegmentForMap(map, set = false) {
  21189. if (!map) {
  21190. return null;
  21191. }
  21192. const id = initSegmentId(map);
  21193. let storedMap = this.initSegments_[id];
  21194. if (set && !storedMap && map.bytes) {
  21195. // append WebVTT line terminators to the media initialization segment if it exists
  21196. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  21197. // requires two or more WebVTT line terminators between the WebVTT header and the
  21198. // rest of the file
  21199. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  21200. const combinedSegment = new Uint8Array(combinedByteLength);
  21201. combinedSegment.set(map.bytes);
  21202. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  21203. this.initSegments_[id] = storedMap = {
  21204. resolvedUri: map.resolvedUri,
  21205. byterange: map.byterange,
  21206. bytes: combinedSegment
  21207. };
  21208. }
  21209. return storedMap || map;
  21210. }
  21211. /**
  21212. * Returns true if all configuration required for loading is present, otherwise false.
  21213. *
  21214. * @return {boolean} True if the all configuration is ready for loading
  21215. * @private
  21216. */
  21217. couldBeginLoading_() {
  21218. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  21219. }
  21220. /**
  21221. * Once all the starting parameters have been specified, begin
  21222. * operation. This method should only be invoked from the INIT
  21223. * state.
  21224. *
  21225. * @private
  21226. */
  21227. init_() {
  21228. this.state = 'READY';
  21229. this.resetEverything();
  21230. return this.monitorBuffer_();
  21231. }
  21232. /**
  21233. * Set a subtitle track on the segment loader to add subtitles to
  21234. *
  21235. * @param {TextTrack=} track
  21236. * The text track to add loaded subtitles to
  21237. * @return {TextTrack}
  21238. * Returns the subtitles track
  21239. */
  21240. track(track) {
  21241. if (typeof track === 'undefined') {
  21242. return this.subtitlesTrack_;
  21243. }
  21244. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  21245. // buffering now
  21246. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  21247. this.init_();
  21248. }
  21249. return this.subtitlesTrack_;
  21250. }
  21251. /**
  21252. * Remove any data in the source buffer between start and end times
  21253. *
  21254. * @param {number} start - the start time of the region to remove from the buffer
  21255. * @param {number} end - the end time of the region to remove from the buffer
  21256. */
  21257. remove(start, end) {
  21258. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  21259. }
  21260. /**
  21261. * fill the buffer with segements unless the sourceBuffers are
  21262. * currently updating
  21263. *
  21264. * Note: this function should only ever be called by monitorBuffer_
  21265. * and never directly
  21266. *
  21267. * @private
  21268. */
  21269. fillBuffer_() {
  21270. // see if we need to begin loading immediately
  21271. const segmentInfo = this.chooseNextRequest_();
  21272. if (!segmentInfo) {
  21273. return;
  21274. }
  21275. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  21276. // We don't have the timestamp offset that we need to sync subtitles.
  21277. // Rerun on a timestamp offset or user interaction.
  21278. const checkTimestampOffset = () => {
  21279. this.state = 'READY';
  21280. if (!this.paused()) {
  21281. // if not paused, queue a buffer check as soon as possible
  21282. this.monitorBuffer_();
  21283. }
  21284. };
  21285. this.syncController_.one('timestampoffset', checkTimestampOffset);
  21286. this.state = 'WAITING_ON_TIMELINE';
  21287. return;
  21288. }
  21289. this.loadSegment_(segmentInfo);
  21290. } // never set a timestamp offset for vtt segments.
  21291. timestampOffsetForSegment_() {
  21292. return null;
  21293. }
  21294. chooseNextRequest_() {
  21295. return this.skipEmptySegments_(super.chooseNextRequest_());
  21296. }
  21297. /**
  21298. * Prevents the segment loader from requesting segments we know contain no subtitles
  21299. * by walking forward until we find the next segment that we don't know whether it is
  21300. * empty or not.
  21301. *
  21302. * @param {Object} segmentInfo
  21303. * a segment info object that describes the current segment
  21304. * @return {Object}
  21305. * a segment info object that describes the current segment
  21306. */
  21307. skipEmptySegments_(segmentInfo) {
  21308. while (segmentInfo && segmentInfo.segment.empty) {
  21309. // stop at the last possible segmentInfo
  21310. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  21311. segmentInfo = null;
  21312. break;
  21313. }
  21314. segmentInfo = this.generateSegmentInfo_({
  21315. playlist: segmentInfo.playlist,
  21316. mediaIndex: segmentInfo.mediaIndex + 1,
  21317. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  21318. isSyncRequest: segmentInfo.isSyncRequest
  21319. });
  21320. }
  21321. return segmentInfo;
  21322. }
  21323. stopForError(error) {
  21324. this.error(error);
  21325. this.state = 'READY';
  21326. this.pause();
  21327. this.trigger('error');
  21328. }
  21329. /**
  21330. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  21331. *
  21332. * @private
  21333. */
  21334. segmentRequestFinished_(error, simpleSegment, result) {
  21335. if (!this.subtitlesTrack_) {
  21336. this.state = 'READY';
  21337. return;
  21338. }
  21339. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  21340. if (!this.pendingSegment_) {
  21341. this.state = 'READY';
  21342. this.mediaRequestsAborted += 1;
  21343. return;
  21344. }
  21345. if (error) {
  21346. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  21347. this.handleTimeout_();
  21348. }
  21349. if (error.code === REQUEST_ERRORS.ABORTED) {
  21350. this.mediaRequestsAborted += 1;
  21351. } else {
  21352. this.mediaRequestsErrored += 1;
  21353. }
  21354. this.stopForError(error);
  21355. return;
  21356. }
  21357. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  21358. // maintain functionality between segment loaders
  21359. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  21360. if (simpleSegment.key) {
  21361. this.segmentKey(simpleSegment.key, true);
  21362. }
  21363. this.state = 'APPENDING'; // used for tests
  21364. this.trigger('appending');
  21365. const segment = segmentInfo.segment;
  21366. if (segment.map) {
  21367. segment.map.bytes = simpleSegment.map.bytes;
  21368. }
  21369. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  21370. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  21371. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  21372. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  21373. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  21374. message: 'Error loading vtt.js'
  21375. }));
  21376. return;
  21377. }
  21378. segment.requested = true;
  21379. try {
  21380. this.parseVTTCues_(segmentInfo);
  21381. } catch (e) {
  21382. this.stopForError({
  21383. message: e.message
  21384. });
  21385. return;
  21386. }
  21387. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  21388. if (segmentInfo.cues.length) {
  21389. segmentInfo.timingInfo = {
  21390. start: segmentInfo.cues[0].startTime,
  21391. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  21392. };
  21393. } else {
  21394. segmentInfo.timingInfo = {
  21395. start: segmentInfo.startOfSegment,
  21396. end: segmentInfo.startOfSegment + segmentInfo.duration
  21397. };
  21398. }
  21399. if (segmentInfo.isSyncRequest) {
  21400. this.trigger('syncinfoupdate');
  21401. this.pendingSegment_ = null;
  21402. this.state = 'READY';
  21403. return;
  21404. }
  21405. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  21406. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  21407. // the subtitle track
  21408. segmentInfo.cues.forEach(cue => {
  21409. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  21410. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  21411. // cues to have identical time-intervals, but if the text is also identical
  21412. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  21413. // "overlaps" VTT segments)
  21414. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  21415. this.handleAppendsDone_();
  21416. }
  21417. handleData_() {// noop as we shouldn't be getting video/audio data captions
  21418. // that we do not support here.
  21419. }
  21420. updateTimingInfoEnd_() {// noop
  21421. }
  21422. /**
  21423. * Uses the WebVTT parser to parse the segment response
  21424. *
  21425. * @throws NoVttJsError
  21426. *
  21427. * @param {Object} segmentInfo
  21428. * a segment info object that describes the current segment
  21429. * @private
  21430. */
  21431. parseVTTCues_(segmentInfo) {
  21432. let decoder;
  21433. let decodeBytesToString = false;
  21434. if (typeof window.WebVTT !== 'function') {
  21435. // caller is responsible for exception handling.
  21436. throw new NoVttJsError();
  21437. }
  21438. if (typeof window.TextDecoder === 'function') {
  21439. decoder = new window.TextDecoder('utf8');
  21440. } else {
  21441. decoder = window.WebVTT.StringDecoder();
  21442. decodeBytesToString = true;
  21443. }
  21444. const parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  21445. segmentInfo.cues = [];
  21446. segmentInfo.timestampmap = {
  21447. MPEGTS: 0,
  21448. LOCAL: 0
  21449. };
  21450. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  21451. parser.ontimestampmap = map => {
  21452. segmentInfo.timestampmap = map;
  21453. };
  21454. parser.onparsingerror = error => {
  21455. videojs__default["default"].log.warn('Error encountered when parsing cues: ' + error.message);
  21456. };
  21457. if (segmentInfo.segment.map) {
  21458. let mapData = segmentInfo.segment.map.bytes;
  21459. if (decodeBytesToString) {
  21460. mapData = uint8ToUtf8(mapData);
  21461. }
  21462. parser.parse(mapData);
  21463. }
  21464. let segmentData = segmentInfo.bytes;
  21465. if (decodeBytesToString) {
  21466. segmentData = uint8ToUtf8(segmentData);
  21467. }
  21468. parser.parse(segmentData);
  21469. parser.flush();
  21470. }
  21471. /**
  21472. * Updates the start and end times of any cues parsed by the WebVTT parser using
  21473. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  21474. * from the SyncController
  21475. *
  21476. * @param {Object} segmentInfo
  21477. * a segment info object that describes the current segment
  21478. * @param {Object} mappingObj
  21479. * object containing a mapping from TS to media time
  21480. * @param {Object} playlist
  21481. * the playlist object containing the segment
  21482. * @private
  21483. */
  21484. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  21485. const segment = segmentInfo.segment;
  21486. if (!mappingObj) {
  21487. // If the sync controller does not have a mapping of TS to Media Time for the
  21488. // timeline, then we don't have enough information to update the cue
  21489. // start/end times
  21490. return;
  21491. }
  21492. if (!segmentInfo.cues.length) {
  21493. // If there are no cues, we also do not have enough information to figure out
  21494. // segment timing. Mark that the segment contains no cues so we don't re-request
  21495. // an empty segment.
  21496. segment.empty = true;
  21497. return;
  21498. }
  21499. const timestampmap = segmentInfo.timestampmap;
  21500. const diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  21501. segmentInfo.cues.forEach(cue => {
  21502. // First convert cue time to TS time using the timestamp-map provided within the vtt
  21503. cue.startTime += diff;
  21504. cue.endTime += diff;
  21505. });
  21506. if (!playlist.syncInfo) {
  21507. const firstStart = segmentInfo.cues[0].startTime;
  21508. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  21509. playlist.syncInfo = {
  21510. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  21511. time: Math.min(firstStart, lastStart - segment.duration)
  21512. };
  21513. }
  21514. }
  21515. }
  21516. /**
  21517. * @file ad-cue-tags.js
  21518. */
  21519. /**
  21520. * Searches for an ad cue that overlaps with the given mediaTime
  21521. *
  21522. * @param {Object} track
  21523. * the track to find the cue for
  21524. *
  21525. * @param {number} mediaTime
  21526. * the time to find the cue at
  21527. *
  21528. * @return {Object|null}
  21529. * the found cue or null
  21530. */
  21531. const findAdCue = function (track, mediaTime) {
  21532. const cues = track.cues;
  21533. for (let i = 0; i < cues.length; i++) {
  21534. const cue = cues[i];
  21535. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  21536. return cue;
  21537. }
  21538. }
  21539. return null;
  21540. };
  21541. const updateAdCues = function (media, track, offset = 0) {
  21542. if (!media.segments) {
  21543. return;
  21544. }
  21545. let mediaTime = offset;
  21546. let cue;
  21547. for (let i = 0; i < media.segments.length; i++) {
  21548. const segment = media.segments[i];
  21549. if (!cue) {
  21550. // Since the cues will span for at least the segment duration, adding a fudge
  21551. // factor of half segment duration will prevent duplicate cues from being
  21552. // created when timing info is not exact (e.g. cue start time initialized
  21553. // at 10.006677, but next call mediaTime is 10.003332 )
  21554. cue = findAdCue(track, mediaTime + segment.duration / 2);
  21555. }
  21556. if (cue) {
  21557. if ('cueIn' in segment) {
  21558. // Found a CUE-IN so end the cue
  21559. cue.endTime = mediaTime;
  21560. cue.adEndTime = mediaTime;
  21561. mediaTime += segment.duration;
  21562. cue = null;
  21563. continue;
  21564. }
  21565. if (mediaTime < cue.endTime) {
  21566. // Already processed this mediaTime for this cue
  21567. mediaTime += segment.duration;
  21568. continue;
  21569. } // otherwise extend cue until a CUE-IN is found
  21570. cue.endTime += segment.duration;
  21571. } else {
  21572. if ('cueOut' in segment) {
  21573. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  21574. cue.adStartTime = mediaTime; // Assumes tag format to be
  21575. // #EXT-X-CUE-OUT:30
  21576. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  21577. track.addCue(cue);
  21578. }
  21579. if ('cueOutCont' in segment) {
  21580. // Entered into the middle of an ad cue
  21581. // Assumes tag formate to be
  21582. // #EXT-X-CUE-OUT-CONT:10/30
  21583. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  21584. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  21585. cue.adStartTime = mediaTime - adOffset;
  21586. cue.adEndTime = cue.adStartTime + adTotal;
  21587. track.addCue(cue);
  21588. }
  21589. }
  21590. mediaTime += segment.duration;
  21591. }
  21592. };
  21593. /**
  21594. * @file sync-controller.js
  21595. */
  21596. // synchronize expired playlist segments.
  21597. // the max media sequence diff is 48 hours of live stream
  21598. // content with two second segments. Anything larger than that
  21599. // will likely be invalid.
  21600. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  21601. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  21602. // the equivalence display-time 0 === segment-index 0
  21603. {
  21604. name: 'VOD',
  21605. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21606. if (duration !== Infinity) {
  21607. const syncPoint = {
  21608. time: 0,
  21609. segmentIndex: 0,
  21610. partIndex: null
  21611. };
  21612. return syncPoint;
  21613. }
  21614. return null;
  21615. }
  21616. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  21617. {
  21618. name: 'ProgramDateTime',
  21619. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21620. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  21621. return null;
  21622. }
  21623. let syncPoint = null;
  21624. let lastDistance = null;
  21625. const partsAndSegments = getPartsAndSegments(playlist);
  21626. currentTime = currentTime || 0;
  21627. for (let i = 0; i < partsAndSegments.length; i++) {
  21628. // start from the end and loop backwards for live
  21629. // or start from the front and loop forwards for non-live
  21630. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  21631. const partAndSegment = partsAndSegments[index];
  21632. const segment = partAndSegment.segment;
  21633. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  21634. if (!datetimeMapping || !segment.dateTimeObject) {
  21635. continue;
  21636. }
  21637. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  21638. let start = segmentTime + datetimeMapping; // take part duration into account.
  21639. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  21640. for (let z = 0; z < partAndSegment.partIndex; z++) {
  21641. start += segment.parts[z].duration;
  21642. }
  21643. }
  21644. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  21645. // currentTime and can stop looking for better candidates
  21646. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  21647. break;
  21648. }
  21649. lastDistance = distance;
  21650. syncPoint = {
  21651. time: start,
  21652. segmentIndex: partAndSegment.segmentIndex,
  21653. partIndex: partAndSegment.partIndex
  21654. };
  21655. }
  21656. return syncPoint;
  21657. }
  21658. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  21659. // segment in the current timeline with timing data
  21660. {
  21661. name: 'Segment',
  21662. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21663. let syncPoint = null;
  21664. let lastDistance = null;
  21665. currentTime = currentTime || 0;
  21666. const partsAndSegments = getPartsAndSegments(playlist);
  21667. for (let i = 0; i < partsAndSegments.length; i++) {
  21668. // start from the end and loop backwards for live
  21669. // or start from the front and loop forwards for non-live
  21670. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  21671. const partAndSegment = partsAndSegments[index];
  21672. const segment = partAndSegment.segment;
  21673. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  21674. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  21675. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  21676. // currentTime and can stop looking for better candidates
  21677. if (lastDistance !== null && lastDistance < distance) {
  21678. break;
  21679. }
  21680. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  21681. lastDistance = distance;
  21682. syncPoint = {
  21683. time: start,
  21684. segmentIndex: partAndSegment.segmentIndex,
  21685. partIndex: partAndSegment.partIndex
  21686. };
  21687. }
  21688. }
  21689. }
  21690. return syncPoint;
  21691. }
  21692. }, // Stategy "Discontinuity": We have a discontinuity with a known
  21693. // display-time
  21694. {
  21695. name: 'Discontinuity',
  21696. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21697. let syncPoint = null;
  21698. currentTime = currentTime || 0;
  21699. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  21700. let lastDistance = null;
  21701. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  21702. const segmentIndex = playlist.discontinuityStarts[i];
  21703. const discontinuity = playlist.discontinuitySequence + i + 1;
  21704. const discontinuitySync = syncController.discontinuities[discontinuity];
  21705. if (discontinuitySync) {
  21706. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  21707. // currentTime and can stop looking for better candidates
  21708. if (lastDistance !== null && lastDistance < distance) {
  21709. break;
  21710. }
  21711. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  21712. lastDistance = distance;
  21713. syncPoint = {
  21714. time: discontinuitySync.time,
  21715. segmentIndex,
  21716. partIndex: null
  21717. };
  21718. }
  21719. }
  21720. }
  21721. }
  21722. return syncPoint;
  21723. }
  21724. }, // Stategy "Playlist": We have a playlist with a known mapping of
  21725. // segment index to display time
  21726. {
  21727. name: 'Playlist',
  21728. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21729. if (playlist.syncInfo) {
  21730. const syncPoint = {
  21731. time: playlist.syncInfo.time,
  21732. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  21733. partIndex: null
  21734. };
  21735. return syncPoint;
  21736. }
  21737. return null;
  21738. }
  21739. }];
  21740. class SyncController extends videojs__default["default"].EventTarget {
  21741. constructor(options = {}) {
  21742. super(); // ...for synching across variants
  21743. this.timelines = [];
  21744. this.discontinuities = [];
  21745. this.timelineToDatetimeMappings = {};
  21746. this.logger_ = logger('SyncController');
  21747. }
  21748. /**
  21749. * Find a sync-point for the playlist specified
  21750. *
  21751. * A sync-point is defined as a known mapping from display-time to
  21752. * a segment-index in the current playlist.
  21753. *
  21754. * @param {Playlist} playlist
  21755. * The playlist that needs a sync-point
  21756. * @param {number} duration
  21757. * Duration of the MediaSource (Infinite if playing a live source)
  21758. * @param {number} currentTimeline
  21759. * The last timeline from which a segment was loaded
  21760. * @return {Object}
  21761. * A sync-point object
  21762. */
  21763. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  21764. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  21765. if (!syncPoints.length) {
  21766. // Signal that we need to attempt to get a sync-point manually
  21767. // by fetching a segment in the playlist and constructing
  21768. // a sync-point from that information
  21769. return null;
  21770. } // Now find the sync-point that is closest to the currentTime because
  21771. // that should result in the most accurate guess about which segment
  21772. // to fetch
  21773. return this.selectSyncPoint_(syncPoints, {
  21774. key: 'time',
  21775. value: currentTime
  21776. });
  21777. }
  21778. /**
  21779. * Calculate the amount of time that has expired off the playlist during playback
  21780. *
  21781. * @param {Playlist} playlist
  21782. * Playlist object to calculate expired from
  21783. * @param {number} duration
  21784. * Duration of the MediaSource (Infinity if playling a live source)
  21785. * @return {number|null}
  21786. * The amount of time that has expired off the playlist during playback. Null
  21787. * if no sync-points for the playlist can be found.
  21788. */
  21789. getExpiredTime(playlist, duration) {
  21790. if (!playlist || !playlist.segments) {
  21791. return null;
  21792. }
  21793. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  21794. if (!syncPoints.length) {
  21795. return null;
  21796. }
  21797. const syncPoint = this.selectSyncPoint_(syncPoints, {
  21798. key: 'segmentIndex',
  21799. value: 0
  21800. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  21801. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  21802. if (syncPoint.segmentIndex > 0) {
  21803. syncPoint.time *= -1;
  21804. }
  21805. return Math.abs(syncPoint.time + sumDurations({
  21806. defaultDuration: playlist.targetDuration,
  21807. durationList: playlist.segments,
  21808. startIndex: syncPoint.segmentIndex,
  21809. endIndex: 0
  21810. }));
  21811. }
  21812. /**
  21813. * Runs each sync-point strategy and returns a list of sync-points returned by the
  21814. * strategies
  21815. *
  21816. * @private
  21817. * @param {Playlist} playlist
  21818. * The playlist that needs a sync-point
  21819. * @param {number} duration
  21820. * Duration of the MediaSource (Infinity if playing a live source)
  21821. * @param {number} currentTimeline
  21822. * The last timeline from which a segment was loaded
  21823. * @return {Array}
  21824. * A list of sync-point objects
  21825. */
  21826. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  21827. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  21828. for (let i = 0; i < syncPointStrategies.length; i++) {
  21829. const strategy = syncPointStrategies[i];
  21830. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  21831. if (syncPoint) {
  21832. syncPoint.strategy = strategy.name;
  21833. syncPoints.push({
  21834. strategy: strategy.name,
  21835. syncPoint
  21836. });
  21837. }
  21838. }
  21839. return syncPoints;
  21840. }
  21841. /**
  21842. * Selects the sync-point nearest the specified target
  21843. *
  21844. * @private
  21845. * @param {Array} syncPoints
  21846. * List of sync-points to select from
  21847. * @param {Object} target
  21848. * Object specifying the property and value we are targeting
  21849. * @param {string} target.key
  21850. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  21851. * @param {number} target.value
  21852. * The value to target for the specified key.
  21853. * @return {Object}
  21854. * The sync-point nearest the target
  21855. */
  21856. selectSyncPoint_(syncPoints, target) {
  21857. let bestSyncPoint = syncPoints[0].syncPoint;
  21858. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  21859. let bestStrategy = syncPoints[0].strategy;
  21860. for (let i = 1; i < syncPoints.length; i++) {
  21861. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  21862. if (newDistance < bestDistance) {
  21863. bestDistance = newDistance;
  21864. bestSyncPoint = syncPoints[i].syncPoint;
  21865. bestStrategy = syncPoints[i].strategy;
  21866. }
  21867. }
  21868. this.logger_(`syncPoint for [${target.key}: ${target.value}] chosen with strategy` + ` [${bestStrategy}]: [time:${bestSyncPoint.time},` + ` segmentIndex:${bestSyncPoint.segmentIndex}` + (typeof bestSyncPoint.partIndex === 'number' ? `,partIndex:${bestSyncPoint.partIndex}` : '') + ']');
  21869. return bestSyncPoint;
  21870. }
  21871. /**
  21872. * Save any meta-data present on the segments when segments leave
  21873. * the live window to the playlist to allow for synchronization at the
  21874. * playlist level later.
  21875. *
  21876. * @param {Playlist} oldPlaylist - The previous active playlist
  21877. * @param {Playlist} newPlaylist - The updated and most current playlist
  21878. */
  21879. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  21880. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  21881. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  21882. videojs__default["default"].log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  21883. return;
  21884. } // When a segment expires from the playlist and it has a start time
  21885. // save that information as a possible sync-point reference in future
  21886. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  21887. const lastRemovedSegment = oldPlaylist.segments[i];
  21888. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  21889. newPlaylist.syncInfo = {
  21890. mediaSequence: oldPlaylist.mediaSequence + i,
  21891. time: lastRemovedSegment.start
  21892. };
  21893. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  21894. this.trigger('syncinfoupdate');
  21895. break;
  21896. }
  21897. }
  21898. }
  21899. /**
  21900. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  21901. * before segments start to load.
  21902. *
  21903. * @param {Playlist} playlist - The currently active playlist
  21904. */
  21905. setDateTimeMappingForStart(playlist) {
  21906. // It's possible for the playlist to be updated before playback starts, meaning time
  21907. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  21908. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  21909. // unless the mappings are cleared.
  21910. this.timelineToDatetimeMappings = {};
  21911. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  21912. const firstSegment = playlist.segments[0];
  21913. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  21914. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  21915. }
  21916. }
  21917. /**
  21918. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  21919. * based on the latest timing information.
  21920. *
  21921. * @param {Object} options
  21922. * Options object
  21923. * @param {SegmentInfo} options.segmentInfo
  21924. * The current active request information
  21925. * @param {boolean} options.shouldSaveTimelineMapping
  21926. * If there's a timeline change, determines if the timeline mapping should be
  21927. * saved for timeline mapping and program date time mappings.
  21928. */
  21929. saveSegmentTimingInfo({
  21930. segmentInfo,
  21931. shouldSaveTimelineMapping
  21932. }) {
  21933. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  21934. const segment = segmentInfo.segment;
  21935. if (didCalculateSegmentTimeMapping) {
  21936. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  21937. // now with segment timing information
  21938. if (!segmentInfo.playlist.syncInfo) {
  21939. segmentInfo.playlist.syncInfo = {
  21940. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  21941. time: segment.start
  21942. };
  21943. }
  21944. }
  21945. const dateTime = segment.dateTimeObject;
  21946. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  21947. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  21948. }
  21949. }
  21950. timestampOffsetForTimeline(timeline) {
  21951. if (typeof this.timelines[timeline] === 'undefined') {
  21952. return null;
  21953. }
  21954. return this.timelines[timeline].time;
  21955. }
  21956. mappingForTimeline(timeline) {
  21957. if (typeof this.timelines[timeline] === 'undefined') {
  21958. return null;
  21959. }
  21960. return this.timelines[timeline].mapping;
  21961. }
  21962. /**
  21963. * Use the "media time" for a segment to generate a mapping to "display time" and
  21964. * save that display time to the segment.
  21965. *
  21966. * @private
  21967. * @param {SegmentInfo} segmentInfo
  21968. * The current active request information
  21969. * @param {Object} timingInfo
  21970. * The start and end time of the current segment in "media time"
  21971. * @param {boolean} shouldSaveTimelineMapping
  21972. * If there's a timeline change, determines if the timeline mapping should be
  21973. * saved in timelines.
  21974. * @return {boolean}
  21975. * Returns false if segment time mapping could not be calculated
  21976. */
  21977. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  21978. // TODO: remove side effects
  21979. const segment = segmentInfo.segment;
  21980. const part = segmentInfo.part;
  21981. let mappingObj = this.timelines[segmentInfo.timeline];
  21982. let start;
  21983. let end;
  21984. if (typeof segmentInfo.timestampOffset === 'number') {
  21985. mappingObj = {
  21986. time: segmentInfo.startOfSegment,
  21987. mapping: segmentInfo.startOfSegment - timingInfo.start
  21988. };
  21989. if (shouldSaveTimelineMapping) {
  21990. this.timelines[segmentInfo.timeline] = mappingObj;
  21991. this.trigger('timestampoffset');
  21992. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  21993. }
  21994. start = segmentInfo.startOfSegment;
  21995. end = timingInfo.end + mappingObj.mapping;
  21996. } else if (mappingObj) {
  21997. start = timingInfo.start + mappingObj.mapping;
  21998. end = timingInfo.end + mappingObj.mapping;
  21999. } else {
  22000. return false;
  22001. }
  22002. if (part) {
  22003. part.start = start;
  22004. part.end = end;
  22005. } // If we don't have a segment start yet or the start value we got
  22006. // is less than our current segment.start value, save a new start value.
  22007. // We have to do this because parts will have segment timing info saved
  22008. // multiple times and we want segment start to be the earliest part start
  22009. // value for that segment.
  22010. if (!segment.start || start < segment.start) {
  22011. segment.start = start;
  22012. }
  22013. segment.end = end;
  22014. return true;
  22015. }
  22016. /**
  22017. * Each time we have discontinuity in the playlist, attempt to calculate the location
  22018. * in display of the start of the discontinuity and save that. We also save an accuracy
  22019. * value so that we save values with the most accuracy (closest to 0.)
  22020. *
  22021. * @private
  22022. * @param {SegmentInfo} segmentInfo - The current active request information
  22023. */
  22024. saveDiscontinuitySyncInfo_(segmentInfo) {
  22025. const playlist = segmentInfo.playlist;
  22026. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  22027. // the start of the range and it's accuracy is 0 (greater accuracy values
  22028. // mean more approximation)
  22029. if (segment.discontinuity) {
  22030. this.discontinuities[segment.timeline] = {
  22031. time: segment.start,
  22032. accuracy: 0
  22033. };
  22034. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  22035. // Search for future discontinuities that we can provide better timing
  22036. // information for and save that information for sync purposes
  22037. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  22038. const segmentIndex = playlist.discontinuityStarts[i];
  22039. const discontinuity = playlist.discontinuitySequence + i + 1;
  22040. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  22041. const accuracy = Math.abs(mediaIndexDiff);
  22042. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  22043. let time;
  22044. if (mediaIndexDiff < 0) {
  22045. time = segment.start - sumDurations({
  22046. defaultDuration: playlist.targetDuration,
  22047. durationList: playlist.segments,
  22048. startIndex: segmentInfo.mediaIndex,
  22049. endIndex: segmentIndex
  22050. });
  22051. } else {
  22052. time = segment.end + sumDurations({
  22053. defaultDuration: playlist.targetDuration,
  22054. durationList: playlist.segments,
  22055. startIndex: segmentInfo.mediaIndex + 1,
  22056. endIndex: segmentIndex
  22057. });
  22058. }
  22059. this.discontinuities[discontinuity] = {
  22060. time,
  22061. accuracy
  22062. };
  22063. }
  22064. }
  22065. }
  22066. }
  22067. dispose() {
  22068. this.trigger('dispose');
  22069. this.off();
  22070. }
  22071. }
  22072. /**
  22073. * The TimelineChangeController acts as a source for segment loaders to listen for and
  22074. * keep track of latest and pending timeline changes. This is useful to ensure proper
  22075. * sync, as each loader may need to make a consideration for what timeline the other
  22076. * loader is on before making changes which could impact the other loader's media.
  22077. *
  22078. * @class TimelineChangeController
  22079. * @extends videojs.EventTarget
  22080. */
  22081. class TimelineChangeController extends videojs__default["default"].EventTarget {
  22082. constructor() {
  22083. super();
  22084. this.pendingTimelineChanges_ = {};
  22085. this.lastTimelineChanges_ = {};
  22086. }
  22087. clearPendingTimelineChange(type) {
  22088. this.pendingTimelineChanges_[type] = null;
  22089. this.trigger('pendingtimelinechange');
  22090. }
  22091. pendingTimelineChange({
  22092. type,
  22093. from,
  22094. to
  22095. }) {
  22096. if (typeof from === 'number' && typeof to === 'number') {
  22097. this.pendingTimelineChanges_[type] = {
  22098. type,
  22099. from,
  22100. to
  22101. };
  22102. this.trigger('pendingtimelinechange');
  22103. }
  22104. return this.pendingTimelineChanges_[type];
  22105. }
  22106. lastTimelineChange({
  22107. type,
  22108. from,
  22109. to
  22110. }) {
  22111. if (typeof from === 'number' && typeof to === 'number') {
  22112. this.lastTimelineChanges_[type] = {
  22113. type,
  22114. from,
  22115. to
  22116. };
  22117. delete this.pendingTimelineChanges_[type];
  22118. this.trigger('timelinechange');
  22119. }
  22120. return this.lastTimelineChanges_[type];
  22121. }
  22122. dispose() {
  22123. this.trigger('dispose');
  22124. this.pendingTimelineChanges_ = {};
  22125. this.lastTimelineChanges_ = {};
  22126. this.off();
  22127. }
  22128. }
  22129. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  22130. const workerCode = transform(getWorkerString(function () {
  22131. /**
  22132. * @file stream.js
  22133. */
  22134. /**
  22135. * A lightweight readable stream implemention that handles event dispatching.
  22136. *
  22137. * @class Stream
  22138. */
  22139. var Stream = /*#__PURE__*/function () {
  22140. function Stream() {
  22141. this.listeners = {};
  22142. }
  22143. /**
  22144. * Add a listener for a specified event type.
  22145. *
  22146. * @param {string} type the event name
  22147. * @param {Function} listener the callback to be invoked when an event of
  22148. * the specified type occurs
  22149. */
  22150. var _proto = Stream.prototype;
  22151. _proto.on = function on(type, listener) {
  22152. if (!this.listeners[type]) {
  22153. this.listeners[type] = [];
  22154. }
  22155. this.listeners[type].push(listener);
  22156. }
  22157. /**
  22158. * Remove a listener for a specified event type.
  22159. *
  22160. * @param {string} type the event name
  22161. * @param {Function} listener a function previously registered for this
  22162. * type of event through `on`
  22163. * @return {boolean} if we could turn it off or not
  22164. */
  22165. ;
  22166. _proto.off = function off(type, listener) {
  22167. if (!this.listeners[type]) {
  22168. return false;
  22169. }
  22170. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  22171. // In Video.js we slice listener functions
  22172. // on trigger so that it does not mess up the order
  22173. // while we loop through.
  22174. //
  22175. // Here we slice on off so that the loop in trigger
  22176. // can continue using it's old reference to loop without
  22177. // messing up the order.
  22178. this.listeners[type] = this.listeners[type].slice(0);
  22179. this.listeners[type].splice(index, 1);
  22180. return index > -1;
  22181. }
  22182. /**
  22183. * Trigger an event of the specified type on this stream. Any additional
  22184. * arguments to this function are passed as parameters to event listeners.
  22185. *
  22186. * @param {string} type the event name
  22187. */
  22188. ;
  22189. _proto.trigger = function trigger(type) {
  22190. var callbacks = this.listeners[type];
  22191. if (!callbacks) {
  22192. return;
  22193. } // Slicing the arguments on every invocation of this method
  22194. // can add a significant amount of overhead. Avoid the
  22195. // intermediate object creation for the common case of a
  22196. // single callback argument
  22197. if (arguments.length === 2) {
  22198. var length = callbacks.length;
  22199. for (var i = 0; i < length; ++i) {
  22200. callbacks[i].call(this, arguments[1]);
  22201. }
  22202. } else {
  22203. var args = Array.prototype.slice.call(arguments, 1);
  22204. var _length = callbacks.length;
  22205. for (var _i = 0; _i < _length; ++_i) {
  22206. callbacks[_i].apply(this, args);
  22207. }
  22208. }
  22209. }
  22210. /**
  22211. * Destroys the stream and cleans up.
  22212. */
  22213. ;
  22214. _proto.dispose = function dispose() {
  22215. this.listeners = {};
  22216. }
  22217. /**
  22218. * Forwards all `data` events on this stream to the destination stream. The
  22219. * destination stream should provide a method `push` to receive the data
  22220. * events as they arrive.
  22221. *
  22222. * @param {Stream} destination the stream that will receive all `data` events
  22223. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  22224. */
  22225. ;
  22226. _proto.pipe = function pipe(destination) {
  22227. this.on('data', function (data) {
  22228. destination.push(data);
  22229. });
  22230. };
  22231. return Stream;
  22232. }();
  22233. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  22234. /**
  22235. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  22236. *
  22237. * @param padded {Uint8Array} unencrypted bytes that have been padded
  22238. * @return {Uint8Array} the unpadded bytes
  22239. * @see http://tools.ietf.org/html/rfc5652
  22240. */
  22241. function unpad(padded) {
  22242. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  22243. }
  22244. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  22245. /**
  22246. * @file aes.js
  22247. *
  22248. * This file contains an adaptation of the AES decryption algorithm
  22249. * from the Standford Javascript Cryptography Library. That work is
  22250. * covered by the following copyright and permissions notice:
  22251. *
  22252. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  22253. * All rights reserved.
  22254. *
  22255. * Redistribution and use in source and binary forms, with or without
  22256. * modification, are permitted provided that the following conditions are
  22257. * met:
  22258. *
  22259. * 1. Redistributions of source code must retain the above copyright
  22260. * notice, this list of conditions and the following disclaimer.
  22261. *
  22262. * 2. Redistributions in binary form must reproduce the above
  22263. * copyright notice, this list of conditions and the following
  22264. * disclaimer in the documentation and/or other materials provided
  22265. * with the distribution.
  22266. *
  22267. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  22268. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22269. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22270. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  22271. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22272. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22273. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  22274. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  22275. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  22276. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  22277. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22278. *
  22279. * The views and conclusions contained in the software and documentation
  22280. * are those of the authors and should not be interpreted as representing
  22281. * official policies, either expressed or implied, of the authors.
  22282. */
  22283. /**
  22284. * Expand the S-box tables.
  22285. *
  22286. * @private
  22287. */
  22288. const precompute = function () {
  22289. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  22290. const encTable = tables[0];
  22291. const decTable = tables[1];
  22292. const sbox = encTable[4];
  22293. const sboxInv = decTable[4];
  22294. let i;
  22295. let x;
  22296. let xInv;
  22297. const d = [];
  22298. const th = [];
  22299. let x2;
  22300. let x4;
  22301. let x8;
  22302. let s;
  22303. let tEnc;
  22304. let tDec; // Compute double and third tables
  22305. for (i = 0; i < 256; i++) {
  22306. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  22307. }
  22308. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  22309. // Compute sbox
  22310. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  22311. s = s >> 8 ^ s & 255 ^ 99;
  22312. sbox[x] = s;
  22313. sboxInv[s] = x; // Compute MixColumns
  22314. x8 = d[x4 = d[x2 = d[x]]];
  22315. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  22316. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  22317. for (i = 0; i < 4; i++) {
  22318. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  22319. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  22320. }
  22321. } // Compactify. Considerable speedup on Firefox.
  22322. for (i = 0; i < 5; i++) {
  22323. encTable[i] = encTable[i].slice(0);
  22324. decTable[i] = decTable[i].slice(0);
  22325. }
  22326. return tables;
  22327. };
  22328. let aesTables = null;
  22329. /**
  22330. * Schedule out an AES key for both encryption and decryption. This
  22331. * is a low-level class. Use a cipher mode to do bulk encryption.
  22332. *
  22333. * @class AES
  22334. * @param key {Array} The key as an array of 4, 6 or 8 words.
  22335. */
  22336. class AES {
  22337. constructor(key) {
  22338. /**
  22339. * The expanded S-box and inverse S-box tables. These will be computed
  22340. * on the client so that we don't have to send them down the wire.
  22341. *
  22342. * There are two tables, _tables[0] is for encryption and
  22343. * _tables[1] is for decryption.
  22344. *
  22345. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  22346. * last (_tables[01][4]) is the S-box itself.
  22347. *
  22348. * @private
  22349. */
  22350. // if we have yet to precompute the S-box tables
  22351. // do so now
  22352. if (!aesTables) {
  22353. aesTables = precompute();
  22354. } // then make a copy of that object for use
  22355. this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
  22356. let i;
  22357. let j;
  22358. let tmp;
  22359. const sbox = this._tables[0][4];
  22360. const decTable = this._tables[1];
  22361. const keyLen = key.length;
  22362. let rcon = 1;
  22363. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  22364. throw new Error('Invalid aes key size');
  22365. }
  22366. const encKey = key.slice(0);
  22367. const decKey = [];
  22368. this._key = [encKey, decKey]; // schedule encryption keys
  22369. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  22370. tmp = encKey[i - 1]; // apply sbox
  22371. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  22372. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  22373. if (i % keyLen === 0) {
  22374. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  22375. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  22376. }
  22377. }
  22378. encKey[i] = encKey[i - keyLen] ^ tmp;
  22379. } // schedule decryption keys
  22380. for (j = 0; i; j++, i--) {
  22381. tmp = encKey[j & 3 ? i : i - 4];
  22382. if (i <= 4 || j < 4) {
  22383. decKey[j] = tmp;
  22384. } else {
  22385. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  22386. }
  22387. }
  22388. }
  22389. /**
  22390. * Decrypt 16 bytes, specified as four 32-bit words.
  22391. *
  22392. * @param {number} encrypted0 the first word to decrypt
  22393. * @param {number} encrypted1 the second word to decrypt
  22394. * @param {number} encrypted2 the third word to decrypt
  22395. * @param {number} encrypted3 the fourth word to decrypt
  22396. * @param {Int32Array} out the array to write the decrypted words
  22397. * into
  22398. * @param {number} offset the offset into the output array to start
  22399. * writing results
  22400. * @return {Array} The plaintext.
  22401. */
  22402. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  22403. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  22404. let a = encrypted0 ^ key[0];
  22405. let b = encrypted3 ^ key[1];
  22406. let c = encrypted2 ^ key[2];
  22407. let d = encrypted1 ^ key[3];
  22408. let a2;
  22409. let b2;
  22410. let c2; // key.length === 2 ?
  22411. const nInnerRounds = key.length / 4 - 2;
  22412. let i;
  22413. let kIndex = 4;
  22414. const table = this._tables[1]; // load up the tables
  22415. const table0 = table[0];
  22416. const table1 = table[1];
  22417. const table2 = table[2];
  22418. const table3 = table[3];
  22419. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  22420. for (i = 0; i < nInnerRounds; i++) {
  22421. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  22422. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  22423. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  22424. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  22425. kIndex += 4;
  22426. a = a2;
  22427. b = b2;
  22428. c = c2;
  22429. } // Last round.
  22430. for (i = 0; i < 4; i++) {
  22431. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  22432. a2 = a;
  22433. a = b;
  22434. b = c;
  22435. c = d;
  22436. d = a2;
  22437. }
  22438. }
  22439. }
  22440. /**
  22441. * @file async-stream.js
  22442. */
  22443. /**
  22444. * A wrapper around the Stream class to use setTimeout
  22445. * and run stream "jobs" Asynchronously
  22446. *
  22447. * @class AsyncStream
  22448. * @extends Stream
  22449. */
  22450. class AsyncStream extends Stream {
  22451. constructor() {
  22452. super(Stream);
  22453. this.jobs = [];
  22454. this.delay = 1;
  22455. this.timeout_ = null;
  22456. }
  22457. /**
  22458. * process an async job
  22459. *
  22460. * @private
  22461. */
  22462. processJob_() {
  22463. this.jobs.shift()();
  22464. if (this.jobs.length) {
  22465. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  22466. } else {
  22467. this.timeout_ = null;
  22468. }
  22469. }
  22470. /**
  22471. * push a job into the stream
  22472. *
  22473. * @param {Function} job the job to push into the stream
  22474. */
  22475. push(job) {
  22476. this.jobs.push(job);
  22477. if (!this.timeout_) {
  22478. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  22479. }
  22480. }
  22481. }
  22482. /**
  22483. * @file decrypter.js
  22484. *
  22485. * An asynchronous implementation of AES-128 CBC decryption with
  22486. * PKCS#7 padding.
  22487. */
  22488. /**
  22489. * Convert network-order (big-endian) bytes into their little-endian
  22490. * representation.
  22491. */
  22492. const ntoh = function (word) {
  22493. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  22494. };
  22495. /**
  22496. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  22497. *
  22498. * @param {Uint8Array} encrypted the encrypted bytes
  22499. * @param {Uint32Array} key the bytes of the decryption key
  22500. * @param {Uint32Array} initVector the initialization vector (IV) to
  22501. * use for the first round of CBC.
  22502. * @return {Uint8Array} the decrypted bytes
  22503. *
  22504. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  22505. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  22506. * @see https://tools.ietf.org/html/rfc2315
  22507. */
  22508. const decrypt = function (encrypted, key, initVector) {
  22509. // word-level access to the encrypted bytes
  22510. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  22511. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  22512. const decrypted = new Uint8Array(encrypted.byteLength);
  22513. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  22514. // decrypted data
  22515. let init0;
  22516. let init1;
  22517. let init2;
  22518. let init3;
  22519. let encrypted0;
  22520. let encrypted1;
  22521. let encrypted2;
  22522. let encrypted3; // iteration variable
  22523. let wordIx; // pull out the words of the IV to ensure we don't modify the
  22524. // passed-in reference and easier access
  22525. init0 = initVector[0];
  22526. init1 = initVector[1];
  22527. init2 = initVector[2];
  22528. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  22529. // to each decrypted block
  22530. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  22531. // convert big-endian (network order) words into little-endian
  22532. // (javascript order)
  22533. encrypted0 = ntoh(encrypted32[wordIx]);
  22534. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  22535. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  22536. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  22537. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  22538. // plaintext
  22539. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  22540. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  22541. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  22542. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  22543. init0 = encrypted0;
  22544. init1 = encrypted1;
  22545. init2 = encrypted2;
  22546. init3 = encrypted3;
  22547. }
  22548. return decrypted;
  22549. };
  22550. /**
  22551. * The `Decrypter` class that manages decryption of AES
  22552. * data through `AsyncStream` objects and the `decrypt`
  22553. * function
  22554. *
  22555. * @param {Uint8Array} encrypted the encrypted bytes
  22556. * @param {Uint32Array} key the bytes of the decryption key
  22557. * @param {Uint32Array} initVector the initialization vector (IV) to
  22558. * @param {Function} done the function to run when done
  22559. * @class Decrypter
  22560. */
  22561. class Decrypter {
  22562. constructor(encrypted, key, initVector, done) {
  22563. const step = Decrypter.STEP;
  22564. const encrypted32 = new Int32Array(encrypted.buffer);
  22565. const decrypted = new Uint8Array(encrypted.byteLength);
  22566. let i = 0;
  22567. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  22568. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  22569. for (i = step; i < encrypted32.length; i += step) {
  22570. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  22571. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  22572. } // invoke the done() callback when everything is finished
  22573. this.asyncStream_.push(function () {
  22574. // remove pkcs#7 padding from the decrypted bytes
  22575. done(null, unpad(decrypted));
  22576. });
  22577. }
  22578. /**
  22579. * a getter for step the maximum number of bytes to process at one time
  22580. *
  22581. * @return {number} the value of step 32000
  22582. */
  22583. static get STEP() {
  22584. // 4 * 8000;
  22585. return 32000;
  22586. }
  22587. /**
  22588. * @private
  22589. */
  22590. decryptChunk_(encrypted, key, initVector, decrypted) {
  22591. return function () {
  22592. const bytes = decrypt(encrypted, key, initVector);
  22593. decrypted.set(bytes, encrypted.byteOffset);
  22594. };
  22595. }
  22596. }
  22597. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  22598. var win;
  22599. if (typeof window !== "undefined") {
  22600. win = window;
  22601. } else if (typeof commonjsGlobal !== "undefined") {
  22602. win = commonjsGlobal;
  22603. } else if (typeof self !== "undefined") {
  22604. win = self;
  22605. } else {
  22606. win = {};
  22607. }
  22608. var window_1 = win;
  22609. var isArrayBufferView = function isArrayBufferView(obj) {
  22610. if (ArrayBuffer.isView === 'function') {
  22611. return ArrayBuffer.isView(obj);
  22612. }
  22613. return obj && obj.buffer instanceof ArrayBuffer;
  22614. };
  22615. var BigInt = window_1.BigInt || Number;
  22616. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  22617. (function () {
  22618. var a = new Uint16Array([0xFFCC]);
  22619. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  22620. if (b[0] === 0xFF) {
  22621. return 'big';
  22622. }
  22623. if (b[0] === 0xCC) {
  22624. return 'little';
  22625. }
  22626. return 'unknown';
  22627. })();
  22628. /**
  22629. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  22630. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  22631. *
  22632. * @param {Object} message
  22633. * Object of properties and values to send to the web worker
  22634. * @return {Object}
  22635. * Modified message with TypedArray values expanded
  22636. * @function createTransferableMessage
  22637. */
  22638. const createTransferableMessage = function (message) {
  22639. const transferable = {};
  22640. Object.keys(message).forEach(key => {
  22641. const value = message[key];
  22642. if (isArrayBufferView(value)) {
  22643. transferable[key] = {
  22644. bytes: value.buffer,
  22645. byteOffset: value.byteOffset,
  22646. byteLength: value.byteLength
  22647. };
  22648. } else {
  22649. transferable[key] = value;
  22650. }
  22651. });
  22652. return transferable;
  22653. };
  22654. /* global self */
  22655. /**
  22656. * Our web worker interface so that things can talk to aes-decrypter
  22657. * that will be running in a web worker. the scope is passed to this by
  22658. * webworkify.
  22659. */
  22660. self.onmessage = function (event) {
  22661. const data = event.data;
  22662. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  22663. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  22664. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  22665. /* eslint-disable no-new, handle-callback-err */
  22666. new Decrypter(encrypted, key, iv, function (err, bytes) {
  22667. self.postMessage(createTransferableMessage({
  22668. source: data.source,
  22669. decrypted: bytes
  22670. }), [bytes.buffer]);
  22671. });
  22672. /* eslint-enable */
  22673. };
  22674. }));
  22675. var Decrypter = factory(workerCode);
  22676. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  22677. /**
  22678. * Convert the properties of an HLS track into an audioTrackKind.
  22679. *
  22680. * @private
  22681. */
  22682. const audioTrackKind_ = properties => {
  22683. let kind = properties.default ? 'main' : 'alternative';
  22684. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  22685. kind = 'main-desc';
  22686. }
  22687. return kind;
  22688. };
  22689. /**
  22690. * Pause provided segment loader and playlist loader if active
  22691. *
  22692. * @param {SegmentLoader} segmentLoader
  22693. * SegmentLoader to pause
  22694. * @param {Object} mediaType
  22695. * Active media type
  22696. * @function stopLoaders
  22697. */
  22698. const stopLoaders = (segmentLoader, mediaType) => {
  22699. segmentLoader.abort();
  22700. segmentLoader.pause();
  22701. if (mediaType && mediaType.activePlaylistLoader) {
  22702. mediaType.activePlaylistLoader.pause();
  22703. mediaType.activePlaylistLoader = null;
  22704. }
  22705. };
  22706. /**
  22707. * Start loading provided segment loader and playlist loader
  22708. *
  22709. * @param {PlaylistLoader} playlistLoader
  22710. * PlaylistLoader to start loading
  22711. * @param {Object} mediaType
  22712. * Active media type
  22713. * @function startLoaders
  22714. */
  22715. const startLoaders = (playlistLoader, mediaType) => {
  22716. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  22717. // playlist loader
  22718. mediaType.activePlaylistLoader = playlistLoader;
  22719. playlistLoader.load();
  22720. };
  22721. /**
  22722. * Returns a function to be called when the media group changes. It performs a
  22723. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  22724. * change of group is merely a rendition switch of the same content at another encoding,
  22725. * rather than a change of content, such as switching audio from English to Spanish.
  22726. *
  22727. * @param {string} type
  22728. * MediaGroup type
  22729. * @param {Object} settings
  22730. * Object containing required information for media groups
  22731. * @return {Function}
  22732. * Handler for a non-destructive resync of SegmentLoader when the active media
  22733. * group changes.
  22734. * @function onGroupChanged
  22735. */
  22736. const onGroupChanged = (type, settings) => () => {
  22737. const {
  22738. segmentLoaders: {
  22739. [type]: segmentLoader,
  22740. main: mainSegmentLoader
  22741. },
  22742. mediaTypes: {
  22743. [type]: mediaType
  22744. }
  22745. } = settings;
  22746. const activeTrack = mediaType.activeTrack();
  22747. const activeGroup = mediaType.getActiveGroup();
  22748. const previousActiveLoader = mediaType.activePlaylistLoader;
  22749. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  22750. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  22751. return;
  22752. }
  22753. mediaType.lastGroup_ = activeGroup;
  22754. mediaType.lastTrack_ = activeTrack;
  22755. stopLoaders(segmentLoader, mediaType);
  22756. if (!activeGroup || activeGroup.isMainPlaylist) {
  22757. // there is no group active or active group is a main playlist and won't change
  22758. return;
  22759. }
  22760. if (!activeGroup.playlistLoader) {
  22761. if (previousActiveLoader) {
  22762. // The previous group had a playlist loader but the new active group does not
  22763. // this means we are switching from demuxed to muxed audio. In this case we want to
  22764. // do a destructive reset of the main segment loader and not restart the audio
  22765. // loaders.
  22766. mainSegmentLoader.resetEverything();
  22767. }
  22768. return;
  22769. } // Non-destructive resync
  22770. segmentLoader.resyncLoader();
  22771. startLoaders(activeGroup.playlistLoader, mediaType);
  22772. };
  22773. const onGroupChanging = (type, settings) => () => {
  22774. const {
  22775. segmentLoaders: {
  22776. [type]: segmentLoader
  22777. },
  22778. mediaTypes: {
  22779. [type]: mediaType
  22780. }
  22781. } = settings;
  22782. mediaType.lastGroup_ = null;
  22783. segmentLoader.abort();
  22784. segmentLoader.pause();
  22785. };
  22786. /**
  22787. * Returns a function to be called when the media track changes. It performs a
  22788. * destructive reset of the SegmentLoader to ensure we start loading as close to
  22789. * currentTime as possible.
  22790. *
  22791. * @param {string} type
  22792. * MediaGroup type
  22793. * @param {Object} settings
  22794. * Object containing required information for media groups
  22795. * @return {Function}
  22796. * Handler for a destructive reset of SegmentLoader when the active media
  22797. * track changes.
  22798. * @function onTrackChanged
  22799. */
  22800. const onTrackChanged = (type, settings) => () => {
  22801. const {
  22802. mainPlaylistLoader,
  22803. segmentLoaders: {
  22804. [type]: segmentLoader,
  22805. main: mainSegmentLoader
  22806. },
  22807. mediaTypes: {
  22808. [type]: mediaType
  22809. }
  22810. } = settings;
  22811. const activeTrack = mediaType.activeTrack();
  22812. const activeGroup = mediaType.getActiveGroup();
  22813. const previousActiveLoader = mediaType.activePlaylistLoader;
  22814. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  22815. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  22816. return;
  22817. }
  22818. mediaType.lastGroup_ = activeGroup;
  22819. mediaType.lastTrack_ = activeTrack;
  22820. stopLoaders(segmentLoader, mediaType);
  22821. if (!activeGroup) {
  22822. // there is no group active so we do not want to restart loaders
  22823. return;
  22824. }
  22825. if (activeGroup.isMainPlaylist) {
  22826. // track did not change, do nothing
  22827. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  22828. return;
  22829. }
  22830. const pc = settings.vhs.playlistController_;
  22831. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  22832. if (pc.media() === newPlaylist) {
  22833. return;
  22834. }
  22835. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  22836. mainPlaylistLoader.pause();
  22837. mainSegmentLoader.resetEverything();
  22838. pc.fastQualityChange_(newPlaylist);
  22839. return;
  22840. }
  22841. if (type === 'AUDIO') {
  22842. if (!activeGroup.playlistLoader) {
  22843. // when switching from demuxed audio/video to muxed audio/video (noted by no
  22844. // playlist loader for the audio group), we want to do a destructive reset of the
  22845. // main segment loader and not restart the audio loaders
  22846. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  22847. // it should be stopped
  22848. mainSegmentLoader.resetEverything();
  22849. return;
  22850. } // although the segment loader is an audio segment loader, call the setAudio
  22851. // function to ensure it is prepared to re-append the init segment (or handle other
  22852. // config changes)
  22853. segmentLoader.setAudio(true);
  22854. mainSegmentLoader.setAudio(false);
  22855. }
  22856. if (previousActiveLoader === activeGroup.playlistLoader) {
  22857. // Nothing has actually changed. This can happen because track change events can fire
  22858. // multiple times for a "single" change. One for enabling the new active track, and
  22859. // one for disabling the track that was active
  22860. startLoaders(activeGroup.playlistLoader, mediaType);
  22861. return;
  22862. }
  22863. if (segmentLoader.track) {
  22864. // For WebVTT, set the new text track in the segmentloader
  22865. segmentLoader.track(activeTrack);
  22866. } // destructive reset
  22867. segmentLoader.resetEverything();
  22868. startLoaders(activeGroup.playlistLoader, mediaType);
  22869. };
  22870. const onError = {
  22871. /**
  22872. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  22873. * an error.
  22874. *
  22875. * @param {string} type
  22876. * MediaGroup type
  22877. * @param {Object} settings
  22878. * Object containing required information for media groups
  22879. * @return {Function}
  22880. * Error handler. Logs warning (or error if the playlist is excluded) to
  22881. * console and switches back to default audio track.
  22882. * @function onError.AUDIO
  22883. */
  22884. AUDIO: (type, settings) => () => {
  22885. const {
  22886. segmentLoaders: {
  22887. [type]: segmentLoader
  22888. },
  22889. mediaTypes: {
  22890. [type]: mediaType
  22891. },
  22892. excludePlaylist
  22893. } = settings;
  22894. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  22895. const activeTrack = mediaType.activeTrack();
  22896. const activeGroup = mediaType.activeGroup();
  22897. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  22898. const defaultTrack = mediaType.tracks[id];
  22899. if (activeTrack === defaultTrack) {
  22900. // Default track encountered an error. All we can do now is exclude the current
  22901. // rendition and hope another will switch audio groups
  22902. excludePlaylist({
  22903. error: {
  22904. message: 'Problem encountered loading the default audio track.'
  22905. }
  22906. });
  22907. return;
  22908. }
  22909. videojs__default["default"].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  22910. for (const trackId in mediaType.tracks) {
  22911. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  22912. }
  22913. mediaType.onTrackChanged();
  22914. },
  22915. /**
  22916. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  22917. * an error.
  22918. *
  22919. * @param {string} type
  22920. * MediaGroup type
  22921. * @param {Object} settings
  22922. * Object containing required information for media groups
  22923. * @return {Function}
  22924. * Error handler. Logs warning to console and disables the active subtitle track
  22925. * @function onError.SUBTITLES
  22926. */
  22927. SUBTITLES: (type, settings) => () => {
  22928. const {
  22929. segmentLoaders: {
  22930. [type]: segmentLoader
  22931. },
  22932. mediaTypes: {
  22933. [type]: mediaType
  22934. }
  22935. } = settings;
  22936. videojs__default["default"].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  22937. stopLoaders(segmentLoader, mediaType);
  22938. const track = mediaType.activeTrack();
  22939. if (track) {
  22940. track.mode = 'disabled';
  22941. }
  22942. mediaType.onTrackChanged();
  22943. }
  22944. };
  22945. const setupListeners = {
  22946. /**
  22947. * Setup event listeners for audio playlist loader
  22948. *
  22949. * @param {string} type
  22950. * MediaGroup type
  22951. * @param {PlaylistLoader|null} playlistLoader
  22952. * PlaylistLoader to register listeners on
  22953. * @param {Object} settings
  22954. * Object containing required information for media groups
  22955. * @function setupListeners.AUDIO
  22956. */
  22957. AUDIO: (type, playlistLoader, settings) => {
  22958. if (!playlistLoader) {
  22959. // no playlist loader means audio will be muxed with the video
  22960. return;
  22961. }
  22962. const {
  22963. tech,
  22964. requestOptions,
  22965. segmentLoaders: {
  22966. [type]: segmentLoader
  22967. }
  22968. } = settings;
  22969. playlistLoader.on('loadedmetadata', () => {
  22970. const media = playlistLoader.media();
  22971. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  22972. // permits, start downloading segments
  22973. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  22974. segmentLoader.load();
  22975. }
  22976. });
  22977. playlistLoader.on('loadedplaylist', () => {
  22978. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  22979. if (!tech.paused()) {
  22980. segmentLoader.load();
  22981. }
  22982. });
  22983. playlistLoader.on('error', onError[type](type, settings));
  22984. },
  22985. /**
  22986. * Setup event listeners for subtitle playlist loader
  22987. *
  22988. * @param {string} type
  22989. * MediaGroup type
  22990. * @param {PlaylistLoader|null} playlistLoader
  22991. * PlaylistLoader to register listeners on
  22992. * @param {Object} settings
  22993. * Object containing required information for media groups
  22994. * @function setupListeners.SUBTITLES
  22995. */
  22996. SUBTITLES: (type, playlistLoader, settings) => {
  22997. const {
  22998. tech,
  22999. requestOptions,
  23000. segmentLoaders: {
  23001. [type]: segmentLoader
  23002. },
  23003. mediaTypes: {
  23004. [type]: mediaType
  23005. }
  23006. } = settings;
  23007. playlistLoader.on('loadedmetadata', () => {
  23008. const media = playlistLoader.media();
  23009. segmentLoader.playlist(media, requestOptions);
  23010. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  23011. // permits, start downloading segments
  23012. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  23013. segmentLoader.load();
  23014. }
  23015. });
  23016. playlistLoader.on('loadedplaylist', () => {
  23017. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  23018. if (!tech.paused()) {
  23019. segmentLoader.load();
  23020. }
  23021. });
  23022. playlistLoader.on('error', onError[type](type, settings));
  23023. }
  23024. };
  23025. const initialize = {
  23026. /**
  23027. * Setup PlaylistLoaders and AudioTracks for the audio groups
  23028. *
  23029. * @param {string} type
  23030. * MediaGroup type
  23031. * @param {Object} settings
  23032. * Object containing required information for media groups
  23033. * @function initialize.AUDIO
  23034. */
  23035. 'AUDIO': (type, settings) => {
  23036. const {
  23037. vhs,
  23038. sourceType,
  23039. segmentLoaders: {
  23040. [type]: segmentLoader
  23041. },
  23042. requestOptions,
  23043. main: {
  23044. mediaGroups
  23045. },
  23046. mediaTypes: {
  23047. [type]: {
  23048. groups,
  23049. tracks,
  23050. logger_
  23051. }
  23052. },
  23053. mainPlaylistLoader
  23054. } = settings;
  23055. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  23056. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  23057. mediaGroups[type] = {
  23058. main: {
  23059. default: {
  23060. default: true
  23061. }
  23062. }
  23063. };
  23064. if (audioOnlyMain) {
  23065. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  23066. }
  23067. }
  23068. for (const groupId in mediaGroups[type]) {
  23069. if (!groups[groupId]) {
  23070. groups[groupId] = [];
  23071. }
  23072. for (const variantLabel in mediaGroups[type][groupId]) {
  23073. let properties = mediaGroups[type][groupId][variantLabel];
  23074. let playlistLoader;
  23075. if (audioOnlyMain) {
  23076. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  23077. properties.isMainPlaylist = true;
  23078. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  23079. // use the resolved media playlist object
  23080. } else if (sourceType === 'vhs-json' && properties.playlists) {
  23081. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  23082. } else if (properties.resolvedUri) {
  23083. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  23084. // should we even have properties.playlists in this check.
  23085. } else if (properties.playlists && sourceType === 'dash') {
  23086. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  23087. } else {
  23088. // no resolvedUri means the audio is muxed with the video when using this
  23089. // audio track
  23090. playlistLoader = null;
  23091. }
  23092. properties = merge$1({
  23093. id: variantLabel,
  23094. playlistLoader
  23095. }, properties);
  23096. setupListeners[type](type, properties.playlistLoader, settings);
  23097. groups[groupId].push(properties);
  23098. if (typeof tracks[variantLabel] === 'undefined') {
  23099. const track = new videojs__default["default"].AudioTrack({
  23100. id: variantLabel,
  23101. kind: audioTrackKind_(properties),
  23102. enabled: false,
  23103. language: properties.language,
  23104. default: properties.default,
  23105. label: variantLabel
  23106. });
  23107. tracks[variantLabel] = track;
  23108. }
  23109. }
  23110. } // setup single error event handler for the segment loader
  23111. segmentLoader.on('error', onError[type](type, settings));
  23112. },
  23113. /**
  23114. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  23115. *
  23116. * @param {string} type
  23117. * MediaGroup type
  23118. * @param {Object} settings
  23119. * Object containing required information for media groups
  23120. * @function initialize.SUBTITLES
  23121. */
  23122. 'SUBTITLES': (type, settings) => {
  23123. const {
  23124. tech,
  23125. vhs,
  23126. sourceType,
  23127. segmentLoaders: {
  23128. [type]: segmentLoader
  23129. },
  23130. requestOptions,
  23131. main: {
  23132. mediaGroups
  23133. },
  23134. mediaTypes: {
  23135. [type]: {
  23136. groups,
  23137. tracks
  23138. }
  23139. },
  23140. mainPlaylistLoader
  23141. } = settings;
  23142. for (const groupId in mediaGroups[type]) {
  23143. if (!groups[groupId]) {
  23144. groups[groupId] = [];
  23145. }
  23146. for (const variantLabel in mediaGroups[type][groupId]) {
  23147. if (mediaGroups[type][groupId][variantLabel].forced) {
  23148. // Subtitle playlists with the forced attribute are not selectable in Safari.
  23149. // According to Apple's HLS Authoring Specification:
  23150. // If content has forced subtitles and regular subtitles in a given language,
  23151. // the regular subtitles track in that language MUST contain both the forced
  23152. // subtitles and the regular subtitles for that language.
  23153. // Because of this requirement and that Safari does not add forced subtitles,
  23154. // forced subtitles are skipped here to maintain consistent experience across
  23155. // all platforms
  23156. continue;
  23157. }
  23158. let properties = mediaGroups[type][groupId][variantLabel];
  23159. let playlistLoader;
  23160. if (sourceType === 'hls') {
  23161. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  23162. } else if (sourceType === 'dash') {
  23163. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  23164. if (!playlists.length) {
  23165. return;
  23166. }
  23167. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  23168. } else if (sourceType === 'vhs-json') {
  23169. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  23170. // as provided, otherwise use the resolved URI to load the playlist
  23171. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  23172. }
  23173. properties = merge$1({
  23174. id: variantLabel,
  23175. playlistLoader
  23176. }, properties);
  23177. setupListeners[type](type, properties.playlistLoader, settings);
  23178. groups[groupId].push(properties);
  23179. if (typeof tracks[variantLabel] === 'undefined') {
  23180. const track = tech.addRemoteTextTrack({
  23181. id: variantLabel,
  23182. kind: 'subtitles',
  23183. default: properties.default && properties.autoselect,
  23184. language: properties.language,
  23185. label: variantLabel
  23186. }, false).track;
  23187. tracks[variantLabel] = track;
  23188. }
  23189. }
  23190. } // setup single error event handler for the segment loader
  23191. segmentLoader.on('error', onError[type](type, settings));
  23192. },
  23193. /**
  23194. * Setup TextTracks for the closed-caption groups
  23195. *
  23196. * @param {String} type
  23197. * MediaGroup type
  23198. * @param {Object} settings
  23199. * Object containing required information for media groups
  23200. * @function initialize['CLOSED-CAPTIONS']
  23201. */
  23202. 'CLOSED-CAPTIONS': (type, settings) => {
  23203. const {
  23204. tech,
  23205. main: {
  23206. mediaGroups
  23207. },
  23208. mediaTypes: {
  23209. [type]: {
  23210. groups,
  23211. tracks
  23212. }
  23213. }
  23214. } = settings;
  23215. for (const groupId in mediaGroups[type]) {
  23216. if (!groups[groupId]) {
  23217. groups[groupId] = [];
  23218. }
  23219. for (const variantLabel in mediaGroups[type][groupId]) {
  23220. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  23221. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  23222. continue;
  23223. }
  23224. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  23225. let newProps = {
  23226. label: variantLabel,
  23227. language: properties.language,
  23228. instreamId: properties.instreamId,
  23229. default: properties.default && properties.autoselect
  23230. };
  23231. if (captionServices[newProps.instreamId]) {
  23232. newProps = merge$1(newProps, captionServices[newProps.instreamId]);
  23233. }
  23234. if (newProps.default === undefined) {
  23235. delete newProps.default;
  23236. } // No PlaylistLoader is required for Closed-Captions because the captions are
  23237. // embedded within the video stream
  23238. groups[groupId].push(merge$1({
  23239. id: variantLabel
  23240. }, properties));
  23241. if (typeof tracks[variantLabel] === 'undefined') {
  23242. const track = tech.addRemoteTextTrack({
  23243. id: newProps.instreamId,
  23244. kind: 'captions',
  23245. default: newProps.default,
  23246. language: newProps.language,
  23247. label: newProps.label
  23248. }, false).track;
  23249. tracks[variantLabel] = track;
  23250. }
  23251. }
  23252. }
  23253. }
  23254. };
  23255. const groupMatch = (list, media) => {
  23256. for (let i = 0; i < list.length; i++) {
  23257. if (playlistMatch(media, list[i])) {
  23258. return true;
  23259. }
  23260. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  23261. return true;
  23262. }
  23263. }
  23264. return false;
  23265. };
  23266. /**
  23267. * Returns a function used to get the active group of the provided type
  23268. *
  23269. * @param {string} type
  23270. * MediaGroup type
  23271. * @param {Object} settings
  23272. * Object containing required information for media groups
  23273. * @return {Function}
  23274. * Function that returns the active media group for the provided type. Takes an
  23275. * optional parameter {TextTrack} track. If no track is provided, a list of all
  23276. * variants in the group, otherwise the variant corresponding to the provided
  23277. * track is returned.
  23278. * @function activeGroup
  23279. */
  23280. const activeGroup = (type, settings) => track => {
  23281. const {
  23282. mainPlaylistLoader,
  23283. mediaTypes: {
  23284. [type]: {
  23285. groups
  23286. }
  23287. }
  23288. } = settings;
  23289. const media = mainPlaylistLoader.media();
  23290. if (!media) {
  23291. return null;
  23292. }
  23293. let variants = null; // set to variants to main media active group
  23294. if (media.attributes[type]) {
  23295. variants = groups[media.attributes[type]];
  23296. }
  23297. const groupKeys = Object.keys(groups);
  23298. if (!variants) {
  23299. // find the mainPlaylistLoader media
  23300. // that is in a media group if we are dealing
  23301. // with audio only
  23302. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  23303. for (let i = 0; i < groupKeys.length; i++) {
  23304. const groupPropertyList = groups[groupKeys[i]];
  23305. if (groupMatch(groupPropertyList, media)) {
  23306. variants = groupPropertyList;
  23307. break;
  23308. }
  23309. } // use the main group if it exists
  23310. } else if (groups.main) {
  23311. variants = groups.main; // only one group, use that one
  23312. } else if (groupKeys.length === 1) {
  23313. variants = groups[groupKeys[0]];
  23314. }
  23315. }
  23316. if (typeof track === 'undefined') {
  23317. return variants;
  23318. }
  23319. if (track === null || !variants) {
  23320. // An active track was specified so a corresponding group is expected. track === null
  23321. // means no track is currently active so there is no corresponding group
  23322. return null;
  23323. }
  23324. return variants.filter(props => props.id === track.id)[0] || null;
  23325. };
  23326. const activeTrack = {
  23327. /**
  23328. * Returns a function used to get the active track of type provided
  23329. *
  23330. * @param {string} type
  23331. * MediaGroup type
  23332. * @param {Object} settings
  23333. * Object containing required information for media groups
  23334. * @return {Function}
  23335. * Function that returns the active media track for the provided type. Returns
  23336. * null if no track is active
  23337. * @function activeTrack.AUDIO
  23338. */
  23339. AUDIO: (type, settings) => () => {
  23340. const {
  23341. mediaTypes: {
  23342. [type]: {
  23343. tracks
  23344. }
  23345. }
  23346. } = settings;
  23347. for (const id in tracks) {
  23348. if (tracks[id].enabled) {
  23349. return tracks[id];
  23350. }
  23351. }
  23352. return null;
  23353. },
  23354. /**
  23355. * Returns a function used to get the active track of type provided
  23356. *
  23357. * @param {string} type
  23358. * MediaGroup type
  23359. * @param {Object} settings
  23360. * Object containing required information for media groups
  23361. * @return {Function}
  23362. * Function that returns the active media track for the provided type. Returns
  23363. * null if no track is active
  23364. * @function activeTrack.SUBTITLES
  23365. */
  23366. SUBTITLES: (type, settings) => () => {
  23367. const {
  23368. mediaTypes: {
  23369. [type]: {
  23370. tracks
  23371. }
  23372. }
  23373. } = settings;
  23374. for (const id in tracks) {
  23375. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  23376. return tracks[id];
  23377. }
  23378. }
  23379. return null;
  23380. }
  23381. };
  23382. const getActiveGroup = (type, {
  23383. mediaTypes
  23384. }) => () => {
  23385. const activeTrack_ = mediaTypes[type].activeTrack();
  23386. if (!activeTrack_) {
  23387. return null;
  23388. }
  23389. return mediaTypes[type].activeGroup(activeTrack_);
  23390. };
  23391. /**
  23392. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  23393. * Closed-Captions) specified in the main manifest.
  23394. *
  23395. * @param {Object} settings
  23396. * Object containing required information for setting up the media groups
  23397. * @param {Tech} settings.tech
  23398. * The tech of the player
  23399. * @param {Object} settings.requestOptions
  23400. * XHR request options used by the segment loaders
  23401. * @param {PlaylistLoader} settings.mainPlaylistLoader
  23402. * PlaylistLoader for the main source
  23403. * @param {VhsHandler} settings.vhs
  23404. * VHS SourceHandler
  23405. * @param {Object} settings.main
  23406. * The parsed main manifest
  23407. * @param {Object} settings.mediaTypes
  23408. * Object to store the loaders, tracks, and utility methods for each media type
  23409. * @param {Function} settings.excludePlaylist
  23410. * Excludes the current rendition and forces a rendition switch.
  23411. * @function setupMediaGroups
  23412. */
  23413. const setupMediaGroups = settings => {
  23414. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  23415. initialize[type](type, settings);
  23416. });
  23417. const {
  23418. mediaTypes,
  23419. mainPlaylistLoader,
  23420. tech,
  23421. vhs,
  23422. segmentLoaders: {
  23423. ['AUDIO']: audioSegmentLoader,
  23424. main: mainSegmentLoader
  23425. }
  23426. } = settings; // setup active group and track getters and change event handlers
  23427. ['AUDIO', 'SUBTITLES'].forEach(type => {
  23428. mediaTypes[type].activeGroup = activeGroup(type, settings);
  23429. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  23430. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  23431. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  23432. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  23433. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  23434. }); // DO NOT enable the default subtitle or caption track.
  23435. // DO enable the default audio track
  23436. const audioGroup = mediaTypes.AUDIO.activeGroup();
  23437. if (audioGroup) {
  23438. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  23439. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  23440. mediaTypes.AUDIO.onGroupChanged();
  23441. mediaTypes.AUDIO.onTrackChanged();
  23442. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  23443. // track is changed, but needs to be handled here since the track may not be considered
  23444. // changed on the first call to onTrackChanged
  23445. if (!activeAudioGroup.playlistLoader) {
  23446. // either audio is muxed with video or the stream is audio only
  23447. mainSegmentLoader.setAudio(true);
  23448. } else {
  23449. // audio is demuxed
  23450. mainSegmentLoader.setAudio(false);
  23451. audioSegmentLoader.setAudio(true);
  23452. }
  23453. }
  23454. mainPlaylistLoader.on('mediachange', () => {
  23455. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  23456. });
  23457. mainPlaylistLoader.on('mediachanging', () => {
  23458. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  23459. }); // custom audio track change event handler for usage event
  23460. const onAudioTrackChanged = () => {
  23461. mediaTypes.AUDIO.onTrackChanged();
  23462. tech.trigger({
  23463. type: 'usage',
  23464. name: 'vhs-audio-change'
  23465. });
  23466. };
  23467. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  23468. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  23469. vhs.on('dispose', () => {
  23470. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  23471. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  23472. }); // clear existing audio tracks and add the ones we just created
  23473. tech.clearTracks('audio');
  23474. for (const id in mediaTypes.AUDIO.tracks) {
  23475. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  23476. }
  23477. };
  23478. /**
  23479. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  23480. * media type
  23481. *
  23482. * @return {Object}
  23483. * Object to store the loaders, tracks, and utility methods for each media type
  23484. * @function createMediaTypes
  23485. */
  23486. const createMediaTypes = () => {
  23487. const mediaTypes = {};
  23488. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  23489. mediaTypes[type] = {
  23490. groups: {},
  23491. tracks: {},
  23492. activePlaylistLoader: null,
  23493. activeGroup: noop,
  23494. activeTrack: noop,
  23495. getActiveGroup: noop,
  23496. onGroupChanged: noop,
  23497. onTrackChanged: noop,
  23498. lastTrack_: null,
  23499. logger_: logger(`MediaGroups[${type}]`)
  23500. };
  23501. });
  23502. return mediaTypes;
  23503. };
  23504. /**
  23505. * @file playlist-controller.js
  23506. */
  23507. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  23508. let Vhs$1; // SegmentLoader stats that need to have each loader's
  23509. // values summed to calculate the final value
  23510. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  23511. const sumLoaderStat = function (stat) {
  23512. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  23513. };
  23514. const shouldSwitchToMedia = function ({
  23515. currentPlaylist,
  23516. buffered,
  23517. currentTime,
  23518. nextPlaylist,
  23519. bufferLowWaterLine,
  23520. bufferHighWaterLine,
  23521. duration,
  23522. bufferBasedABR,
  23523. log
  23524. }) {
  23525. // we have no other playlist to switch to
  23526. if (!nextPlaylist) {
  23527. videojs__default["default"].log.warn('We received no playlist to switch to. Please check your stream.');
  23528. return false;
  23529. }
  23530. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  23531. if (!currentPlaylist) {
  23532. log(`${sharedLogLine} as current playlist is not set`);
  23533. return true;
  23534. } // no need to switch if playlist is the same
  23535. if (nextPlaylist.id === currentPlaylist.id) {
  23536. return false;
  23537. } // determine if current time is in a buffered range.
  23538. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  23539. // This is because in LIVE, the player plays 3 segments from the end of the
  23540. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  23541. // in those segments, a viewer will never experience a rendition upswitch.
  23542. if (!currentPlaylist.endList) {
  23543. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  23544. // doubles the time to first playback.
  23545. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  23546. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  23547. return false;
  23548. }
  23549. log(`${sharedLogLine} as current playlist is live`);
  23550. return true;
  23551. }
  23552. const forwardBuffer = timeAheadOf(buffered, currentTime);
  23553. const maxBufferLowWaterLine = bufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
  23554. // duration is below the max potential low water line
  23555. if (duration < maxBufferLowWaterLine) {
  23556. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  23557. return true;
  23558. }
  23559. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  23560. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  23561. // we can switch down
  23562. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  23563. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  23564. if (bufferBasedABR) {
  23565. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  23566. }
  23567. log(logLine);
  23568. return true;
  23569. } // and if our buffer is higher than the low water line,
  23570. // we can switch up
  23571. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  23572. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  23573. if (bufferBasedABR) {
  23574. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  23575. }
  23576. log(logLine);
  23577. return true;
  23578. }
  23579. log(`not ${sharedLogLine} as no switching criteria met`);
  23580. return false;
  23581. };
  23582. /**
  23583. * the main playlist controller controller all interactons
  23584. * between playlists and segmentloaders. At this time this mainly
  23585. * involves a main playlist and a series of audio playlists
  23586. * if they are available
  23587. *
  23588. * @class PlaylistController
  23589. * @extends videojs.EventTarget
  23590. */
  23591. class PlaylistController extends videojs__default["default"].EventTarget {
  23592. constructor(options) {
  23593. super();
  23594. const {
  23595. src,
  23596. withCredentials,
  23597. tech,
  23598. bandwidth,
  23599. externVhs,
  23600. useCueTags,
  23601. playlistExclusionDuration,
  23602. enableLowInitialPlaylist,
  23603. sourceType,
  23604. cacheEncryptionKeys,
  23605. bufferBasedABR,
  23606. leastPixelDiffSelector,
  23607. captionServices
  23608. } = options;
  23609. if (!src) {
  23610. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  23611. }
  23612. let {
  23613. maxPlaylistRetries
  23614. } = options;
  23615. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  23616. maxPlaylistRetries = Infinity;
  23617. }
  23618. Vhs$1 = externVhs;
  23619. this.bufferBasedABR = Boolean(bufferBasedABR);
  23620. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  23621. this.withCredentials = withCredentials;
  23622. this.tech_ = tech;
  23623. this.vhs_ = tech.vhs;
  23624. this.sourceType_ = sourceType;
  23625. this.useCueTags_ = useCueTags;
  23626. this.playlistExclusionDuration = playlistExclusionDuration;
  23627. this.maxPlaylistRetries = maxPlaylistRetries;
  23628. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  23629. if (this.useCueTags_) {
  23630. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  23631. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  23632. }
  23633. this.requestOptions_ = {
  23634. withCredentials,
  23635. maxPlaylistRetries,
  23636. timeout: null
  23637. };
  23638. this.on('error', this.pauseLoading);
  23639. this.mediaTypes_ = createMediaTypes();
  23640. this.mediaSource = new window.MediaSource();
  23641. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  23642. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  23643. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  23644. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  23645. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  23646. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  23647. // everything, and the MediaSource should not be detached without a proper disposal
  23648. this.seekable_ = createTimeRanges();
  23649. this.hasPlayed_ = false;
  23650. this.syncController_ = new SyncController(options);
  23651. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  23652. kind: 'metadata',
  23653. label: 'segment-metadata'
  23654. }, false).track;
  23655. this.decrypter_ = new Decrypter();
  23656. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  23657. this.inbandTextTracks_ = {};
  23658. this.timelineChangeController_ = new TimelineChangeController();
  23659. const segmentLoaderSettings = {
  23660. vhs: this.vhs_,
  23661. parse708captions: options.parse708captions,
  23662. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  23663. captionServices,
  23664. mediaSource: this.mediaSource,
  23665. currentTime: this.tech_.currentTime.bind(this.tech_),
  23666. seekable: () => this.seekable(),
  23667. seeking: () => this.tech_.seeking(),
  23668. duration: () => this.duration(),
  23669. hasPlayed: () => this.hasPlayed_,
  23670. goalBufferLength: () => this.goalBufferLength(),
  23671. bandwidth,
  23672. syncController: this.syncController_,
  23673. decrypter: this.decrypter_,
  23674. sourceType: this.sourceType_,
  23675. inbandTextTracks: this.inbandTextTracks_,
  23676. cacheEncryptionKeys,
  23677. sourceUpdater: this.sourceUpdater_,
  23678. timelineChangeController: this.timelineChangeController_,
  23679. exactManifestTimings: options.exactManifestTimings
  23680. }; // The source type check not only determines whether a special DASH playlist loader
  23681. // should be used, but also covers the case where the provided src is a vhs-json
  23682. // manifest object (instead of a URL). In the case of vhs-json, the default
  23683. // PlaylistLoader should be used.
  23684. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  23685. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  23686. // combined audio/video or just video when alternate audio track is selected
  23687. this.mainSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  23688. segmentMetadataTrack: this.segmentMetadataTrack_,
  23689. loaderType: 'main'
  23690. }), options); // alternate audio track
  23691. this.audioSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  23692. loaderType: 'audio'
  23693. }), options);
  23694. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge$1(segmentLoaderSettings, {
  23695. loaderType: 'vtt',
  23696. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  23697. loadVttJs: () => new Promise((resolve, reject) => {
  23698. function onLoad() {
  23699. tech.off('vttjserror', onError);
  23700. resolve();
  23701. }
  23702. function onError() {
  23703. tech.off('vttjsloaded', onLoad);
  23704. reject();
  23705. }
  23706. tech.one('vttjsloaded', onLoad);
  23707. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  23708. tech.addWebVttScript_();
  23709. })
  23710. }), options);
  23711. this.setupSegmentLoaderListeners_();
  23712. if (this.bufferBasedABR) {
  23713. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  23714. this.tech_.on('pause', () => this.stopABRTimer_());
  23715. this.tech_.on('play', () => this.startABRTimer_());
  23716. } // Create SegmentLoader stat-getters
  23717. // mediaRequests_
  23718. // mediaRequestsAborted_
  23719. // mediaRequestsTimedout_
  23720. // mediaRequestsErrored_
  23721. // mediaTransferDuration_
  23722. // mediaBytesTransferred_
  23723. // mediaAppends_
  23724. loaderStats.forEach(stat => {
  23725. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  23726. });
  23727. this.logger_ = logger('pc');
  23728. this.triggeredFmp4Usage = false;
  23729. if (this.tech_.preload() === 'none') {
  23730. this.loadOnPlay_ = () => {
  23731. this.loadOnPlay_ = null;
  23732. this.mainPlaylistLoader_.load();
  23733. };
  23734. this.tech_.one('play', this.loadOnPlay_);
  23735. } else {
  23736. this.mainPlaylistLoader_.load();
  23737. }
  23738. this.timeToLoadedData__ = -1;
  23739. this.mainAppendsToLoadedData__ = -1;
  23740. this.audioAppendsToLoadedData__ = -1;
  23741. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  23742. this.tech_.one(event, () => {
  23743. const timeToLoadedDataStart = Date.now();
  23744. this.tech_.one('loadeddata', () => {
  23745. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  23746. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  23747. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  23748. });
  23749. });
  23750. }
  23751. mainAppendsToLoadedData_() {
  23752. return this.mainAppendsToLoadedData__;
  23753. }
  23754. audioAppendsToLoadedData_() {
  23755. return this.audioAppendsToLoadedData__;
  23756. }
  23757. appendsToLoadedData_() {
  23758. const main = this.mainAppendsToLoadedData_();
  23759. const audio = this.audioAppendsToLoadedData_();
  23760. if (main === -1 || audio === -1) {
  23761. return -1;
  23762. }
  23763. return main + audio;
  23764. }
  23765. timeToLoadedData_() {
  23766. return this.timeToLoadedData__;
  23767. }
  23768. /**
  23769. * Run selectPlaylist and switch to the new playlist if we should
  23770. *
  23771. * @param {string} [reason=abr] a reason for why the ABR check is made
  23772. * @private
  23773. */
  23774. checkABR_(reason = 'abr') {
  23775. const nextPlaylist = this.selectPlaylist();
  23776. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  23777. this.switchMedia_(nextPlaylist, reason);
  23778. }
  23779. }
  23780. switchMedia_(playlist, cause, delay) {
  23781. const oldMedia = this.media();
  23782. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  23783. const newId = playlist.id || playlist.uri;
  23784. if (oldId && oldId !== newId) {
  23785. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  23786. this.tech_.trigger({
  23787. type: 'usage',
  23788. name: `vhs-rendition-change-${cause}`
  23789. });
  23790. }
  23791. this.mainPlaylistLoader_.media(playlist, delay);
  23792. }
  23793. /**
  23794. * Start a timer that periodically calls checkABR_
  23795. *
  23796. * @private
  23797. */
  23798. startABRTimer_() {
  23799. this.stopABRTimer_();
  23800. this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
  23801. }
  23802. /**
  23803. * Stop the timer that periodically calls checkABR_
  23804. *
  23805. * @private
  23806. */
  23807. stopABRTimer_() {
  23808. // if we're scrubbing, we don't need to pause.
  23809. // This getter will be added to Video.js in version 7.11.
  23810. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  23811. return;
  23812. }
  23813. window.clearInterval(this.abrTimer_);
  23814. this.abrTimer_ = null;
  23815. }
  23816. /**
  23817. * Get a list of playlists for the currently selected audio playlist
  23818. *
  23819. * @return {Array} the array of audio playlists
  23820. */
  23821. getAudioTrackPlaylists_() {
  23822. const main = this.main();
  23823. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  23824. // assume that the audio tracks are contained in main
  23825. // playlist array, use that or an empty array.
  23826. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  23827. return defaultPlaylists;
  23828. }
  23829. const AUDIO = main.mediaGroups.AUDIO;
  23830. const groupKeys = Object.keys(AUDIO);
  23831. let track; // get the current active track
  23832. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  23833. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  23834. } else {
  23835. // default group is `main` or just the first group.
  23836. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  23837. for (const label in defaultGroup) {
  23838. if (defaultGroup[label].default) {
  23839. track = {
  23840. label
  23841. };
  23842. break;
  23843. }
  23844. }
  23845. } // no active track no playlists.
  23846. if (!track) {
  23847. return defaultPlaylists;
  23848. }
  23849. const playlists = []; // get all of the playlists that are possible for the
  23850. // active track.
  23851. for (const group in AUDIO) {
  23852. if (AUDIO[group][track.label]) {
  23853. const properties = AUDIO[group][track.label];
  23854. if (properties.playlists && properties.playlists.length) {
  23855. playlists.push.apply(playlists, properties.playlists);
  23856. } else if (properties.uri) {
  23857. playlists.push(properties);
  23858. } else if (main.playlists.length) {
  23859. // if an audio group does not have a uri
  23860. // see if we have main playlists that use it as a group.
  23861. // if we do then add those to the playlists list.
  23862. for (let i = 0; i < main.playlists.length; i++) {
  23863. const playlist = main.playlists[i];
  23864. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  23865. playlists.push(playlist);
  23866. }
  23867. }
  23868. }
  23869. }
  23870. }
  23871. if (!playlists.length) {
  23872. return defaultPlaylists;
  23873. }
  23874. return playlists;
  23875. }
  23876. /**
  23877. * Register event handlers on the main playlist loader. A helper
  23878. * function for construction time.
  23879. *
  23880. * @private
  23881. */
  23882. setupMainPlaylistLoaderListeners_() {
  23883. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  23884. const media = this.mainPlaylistLoader_.media();
  23885. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  23886. // timeout the request.
  23887. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  23888. this.requestOptions_.timeout = 0;
  23889. } else {
  23890. this.requestOptions_.timeout = requestTimeout;
  23891. } // if this isn't a live video and preload permits, start
  23892. // downloading segments
  23893. if (media.endList && this.tech_.preload() !== 'none') {
  23894. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  23895. this.mainSegmentLoader_.load();
  23896. }
  23897. setupMediaGroups({
  23898. sourceType: this.sourceType_,
  23899. segmentLoaders: {
  23900. AUDIO: this.audioSegmentLoader_,
  23901. SUBTITLES: this.subtitleSegmentLoader_,
  23902. main: this.mainSegmentLoader_
  23903. },
  23904. tech: this.tech_,
  23905. requestOptions: this.requestOptions_,
  23906. mainPlaylistLoader: this.mainPlaylistLoader_,
  23907. vhs: this.vhs_,
  23908. main: this.main(),
  23909. mediaTypes: this.mediaTypes_,
  23910. excludePlaylist: this.excludePlaylist.bind(this)
  23911. });
  23912. this.triggerPresenceUsage_(this.main(), media);
  23913. this.setupFirstPlay();
  23914. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  23915. this.trigger('selectedinitialmedia');
  23916. } else {
  23917. // We must wait for the active audio playlist loader to
  23918. // finish setting up before triggering this event so the
  23919. // representations API and EME setup is correct
  23920. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  23921. this.trigger('selectedinitialmedia');
  23922. });
  23923. }
  23924. });
  23925. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  23926. if (this.loadOnPlay_) {
  23927. this.tech_.off('play', this.loadOnPlay_);
  23928. }
  23929. let updatedPlaylist = this.mainPlaylistLoader_.media();
  23930. if (!updatedPlaylist) {
  23931. // exclude any variants that are not supported by the browser before selecting
  23932. // an initial media as the playlist selectors do not consider browser support
  23933. this.excludeUnsupportedVariants_();
  23934. let selectedMedia;
  23935. if (this.enableLowInitialPlaylist) {
  23936. selectedMedia = this.selectInitialPlaylist();
  23937. }
  23938. if (!selectedMedia) {
  23939. selectedMedia = this.selectPlaylist();
  23940. }
  23941. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  23942. return;
  23943. }
  23944. this.initialMedia_ = selectedMedia;
  23945. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  23946. // fire again since the playlist will be requested. In the case of vhs-json
  23947. // (where the manifest object is provided as the source), when the media
  23948. // playlist's `segments` list is already available, a media playlist won't be
  23949. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  23950. // called on its own here.
  23951. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  23952. if (!haveJsonSource) {
  23953. return;
  23954. }
  23955. updatedPlaylist = this.initialMedia_;
  23956. }
  23957. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  23958. });
  23959. this.mainPlaylistLoader_.on('error', () => {
  23960. const error = this.mainPlaylistLoader_.error;
  23961. this.excludePlaylist({
  23962. playlistToExclude: error.playlist,
  23963. error
  23964. });
  23965. });
  23966. this.mainPlaylistLoader_.on('mediachanging', () => {
  23967. this.mainSegmentLoader_.abort();
  23968. this.mainSegmentLoader_.pause();
  23969. });
  23970. this.mainPlaylistLoader_.on('mediachange', () => {
  23971. const media = this.mainPlaylistLoader_.media();
  23972. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  23973. // timeout the request.
  23974. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  23975. this.requestOptions_.timeout = 0;
  23976. } else {
  23977. this.requestOptions_.timeout = requestTimeout;
  23978. }
  23979. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  23980. // that the segments have changed in some way and use that to
  23981. // update the SegmentLoader instead of doing it twice here and
  23982. // on `loadedplaylist`
  23983. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  23984. this.mainSegmentLoader_.load();
  23985. this.tech_.trigger({
  23986. type: 'mediachange',
  23987. bubbles: true
  23988. });
  23989. });
  23990. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  23991. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  23992. // excluded for not-changing. We likely just have a really slowly updating
  23993. // playlist.
  23994. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  23995. return;
  23996. }
  23997. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  23998. if (playlistOutdated) {
  23999. // Playlist has stopped updating and we're stuck at its end. Try to
  24000. // exclude it and switch to another playlist in the hope that that
  24001. // one is updating (and give the player a chance to re-adjust to the
  24002. // safe live point).
  24003. this.excludePlaylist({
  24004. error: {
  24005. message: 'Playlist no longer updating.',
  24006. reason: 'playlist-unchanged'
  24007. }
  24008. }); // useful for monitoring QoS
  24009. this.tech_.trigger('playliststuck');
  24010. }
  24011. });
  24012. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  24013. this.tech_.trigger({
  24014. type: 'usage',
  24015. name: 'vhs-rendition-disabled'
  24016. });
  24017. });
  24018. this.mainPlaylistLoader_.on('renditionenabled', () => {
  24019. this.tech_.trigger({
  24020. type: 'usage',
  24021. name: 'vhs-rendition-enabled'
  24022. });
  24023. });
  24024. }
  24025. /**
  24026. * Given an updated media playlist (whether it was loaded for the first time, or
  24027. * refreshed for live playlists), update any relevant properties and state to reflect
  24028. * changes in the media that should be accounted for (e.g., cues and duration).
  24029. *
  24030. * @param {Object} updatedPlaylist the updated media playlist object
  24031. *
  24032. * @private
  24033. */
  24034. handleUpdatedMediaPlaylist(updatedPlaylist) {
  24035. if (this.useCueTags_) {
  24036. this.updateAdCues_(updatedPlaylist);
  24037. } // TODO: Create a new event on the PlaylistLoader that signals
  24038. // that the segments have changed in some way and use that to
  24039. // update the SegmentLoader instead of doing it twice here and
  24040. // on `mediachange`
  24041. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  24042. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  24043. // as it is possible that it was temporarily stopped while waiting for
  24044. // a playlist (e.g., in case the playlist errored and we re-requested it).
  24045. if (!this.tech_.paused()) {
  24046. this.mainSegmentLoader_.load();
  24047. if (this.audioSegmentLoader_) {
  24048. this.audioSegmentLoader_.load();
  24049. }
  24050. }
  24051. }
  24052. /**
  24053. * A helper function for triggerring presence usage events once per source
  24054. *
  24055. * @private
  24056. */
  24057. triggerPresenceUsage_(main, media) {
  24058. const mediaGroups = main.mediaGroups || {};
  24059. let defaultDemuxed = true;
  24060. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  24061. for (const mediaGroup in mediaGroups.AUDIO) {
  24062. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  24063. const properties = mediaGroups.AUDIO[mediaGroup][label];
  24064. if (!properties.uri) {
  24065. defaultDemuxed = false;
  24066. }
  24067. }
  24068. }
  24069. if (defaultDemuxed) {
  24070. this.tech_.trigger({
  24071. type: 'usage',
  24072. name: 'vhs-demuxed'
  24073. });
  24074. }
  24075. if (Object.keys(mediaGroups.SUBTITLES).length) {
  24076. this.tech_.trigger({
  24077. type: 'usage',
  24078. name: 'vhs-webvtt'
  24079. });
  24080. }
  24081. if (Vhs$1.Playlist.isAes(media)) {
  24082. this.tech_.trigger({
  24083. type: 'usage',
  24084. name: 'vhs-aes'
  24085. });
  24086. }
  24087. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  24088. this.tech_.trigger({
  24089. type: 'usage',
  24090. name: 'vhs-alternate-audio'
  24091. });
  24092. }
  24093. if (this.useCueTags_) {
  24094. this.tech_.trigger({
  24095. type: 'usage',
  24096. name: 'vhs-playlist-cue-tags'
  24097. });
  24098. }
  24099. }
  24100. shouldSwitchToMedia_(nextPlaylist) {
  24101. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  24102. const currentTime = this.tech_.currentTime();
  24103. const bufferLowWaterLine = this.bufferLowWaterLine();
  24104. const bufferHighWaterLine = this.bufferHighWaterLine();
  24105. const buffered = this.tech_.buffered();
  24106. return shouldSwitchToMedia({
  24107. buffered,
  24108. currentTime,
  24109. currentPlaylist,
  24110. nextPlaylist,
  24111. bufferLowWaterLine,
  24112. bufferHighWaterLine,
  24113. duration: this.duration(),
  24114. bufferBasedABR: this.bufferBasedABR,
  24115. log: this.logger_
  24116. });
  24117. }
  24118. /**
  24119. * Register event handlers on the segment loaders. A helper function
  24120. * for construction time.
  24121. *
  24122. * @private
  24123. */
  24124. setupSegmentLoaderListeners_() {
  24125. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  24126. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  24127. // useful to check to see if a rendition switch should be made.
  24128. this.checkABR_('bandwidthupdate');
  24129. this.tech_.trigger('bandwidthupdate');
  24130. });
  24131. this.mainSegmentLoader_.on('timeout', () => {
  24132. if (this.bufferBasedABR) {
  24133. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  24134. // Here the only consideration is that for buffer based ABR there's no guarantee
  24135. // of an immediate switch (since the bandwidth is averaged with a timeout
  24136. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  24137. this.mainSegmentLoader_.load();
  24138. }
  24139. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  24140. // based ABR.
  24141. if (!this.bufferBasedABR) {
  24142. this.mainSegmentLoader_.on('progress', () => {
  24143. this.trigger('progress');
  24144. });
  24145. }
  24146. this.mainSegmentLoader_.on('error', () => {
  24147. const error = this.mainSegmentLoader_.error();
  24148. this.excludePlaylist({
  24149. playlistToExclude: error.playlist,
  24150. error
  24151. });
  24152. });
  24153. this.mainSegmentLoader_.on('appenderror', () => {
  24154. this.error = this.mainSegmentLoader_.error_;
  24155. this.trigger('error');
  24156. });
  24157. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  24158. this.onSyncInfoUpdate_();
  24159. });
  24160. this.mainSegmentLoader_.on('timestampoffset', () => {
  24161. this.tech_.trigger({
  24162. type: 'usage',
  24163. name: 'vhs-timestamp-offset'
  24164. });
  24165. });
  24166. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  24167. this.onSyncInfoUpdate_();
  24168. });
  24169. this.audioSegmentLoader_.on('appenderror', () => {
  24170. this.error = this.audioSegmentLoader_.error_;
  24171. this.trigger('error');
  24172. });
  24173. this.mainSegmentLoader_.on('ended', () => {
  24174. this.logger_('main segment loader ended');
  24175. this.onEndOfStream();
  24176. });
  24177. this.mainSegmentLoader_.on('earlyabort', event => {
  24178. // never try to early abort with the new ABR algorithm
  24179. if (this.bufferBasedABR) {
  24180. return;
  24181. }
  24182. this.delegateLoaders_('all', ['abort']);
  24183. this.excludePlaylist({
  24184. error: {
  24185. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  24186. },
  24187. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  24188. });
  24189. });
  24190. const updateCodecs = () => {
  24191. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  24192. return this.tryToCreateSourceBuffers_();
  24193. }
  24194. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  24195. if (!codecs) {
  24196. return;
  24197. }
  24198. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  24199. };
  24200. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  24201. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  24202. this.mainSegmentLoader_.on('fmp4', () => {
  24203. if (!this.triggeredFmp4Usage) {
  24204. this.tech_.trigger({
  24205. type: 'usage',
  24206. name: 'vhs-fmp4'
  24207. });
  24208. this.triggeredFmp4Usage = true;
  24209. }
  24210. });
  24211. this.audioSegmentLoader_.on('fmp4', () => {
  24212. if (!this.triggeredFmp4Usage) {
  24213. this.tech_.trigger({
  24214. type: 'usage',
  24215. name: 'vhs-fmp4'
  24216. });
  24217. this.triggeredFmp4Usage = true;
  24218. }
  24219. });
  24220. this.audioSegmentLoader_.on('ended', () => {
  24221. this.logger_('audioSegmentLoader ended');
  24222. this.onEndOfStream();
  24223. });
  24224. }
  24225. mediaSecondsLoaded_() {
  24226. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  24227. }
  24228. /**
  24229. * Call load on our SegmentLoaders
  24230. */
  24231. load() {
  24232. this.mainSegmentLoader_.load();
  24233. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24234. this.audioSegmentLoader_.load();
  24235. }
  24236. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  24237. this.subtitleSegmentLoader_.load();
  24238. }
  24239. }
  24240. /**
  24241. * Re-tune playback quality level for the current player
  24242. * conditions. This method will perform destructive actions like removing
  24243. * already buffered content in order to readjust the currently active
  24244. * playlist quickly. This is good for manual quality changes
  24245. *
  24246. * @private
  24247. */
  24248. fastQualityChange_(media = this.selectPlaylist()) {
  24249. if (media === this.mainPlaylistLoader_.media()) {
  24250. this.logger_('skipping fastQualityChange because new media is same as old');
  24251. return;
  24252. }
  24253. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  24254. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  24255. // ahead is roughly the minimum that will accomplish this across a variety of content
  24256. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  24257. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  24258. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  24259. this.mainSegmentLoader_.resetEverything(() => {
  24260. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  24261. // from the previously enabled rendition to load before the new playlist has finished loading
  24262. if (videojs__default["default"].browser.IE_VERSION || videojs__default["default"].browser.IS_EDGE) {
  24263. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  24264. } else {
  24265. this.tech_.setCurrentTime(this.tech_.currentTime());
  24266. }
  24267. }); // don't need to reset audio as it is reset when media changes
  24268. }
  24269. /**
  24270. * Begin playback.
  24271. */
  24272. play() {
  24273. if (this.setupFirstPlay()) {
  24274. return;
  24275. }
  24276. if (this.tech_.ended()) {
  24277. this.tech_.setCurrentTime(0);
  24278. }
  24279. if (this.hasPlayed_) {
  24280. this.load();
  24281. }
  24282. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  24283. // seek forward to the live point
  24284. if (this.tech_.duration() === Infinity) {
  24285. if (this.tech_.currentTime() < seekable.start(0)) {
  24286. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  24287. }
  24288. }
  24289. }
  24290. /**
  24291. * Seek to the latest media position if this is a live video and the
  24292. * player and video are loaded and initialized.
  24293. */
  24294. setupFirstPlay() {
  24295. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  24296. // If 1) there is no active media
  24297. // 2) the player is paused
  24298. // 3) the first play has already been setup
  24299. // then exit early
  24300. if (!media || this.tech_.paused() || this.hasPlayed_) {
  24301. return false;
  24302. } // when the video is a live stream
  24303. if (!media.endList) {
  24304. const seekable = this.seekable();
  24305. if (!seekable.length) {
  24306. // without a seekable range, the player cannot seek to begin buffering at the live
  24307. // point
  24308. return false;
  24309. }
  24310. if (videojs__default["default"].browser.IE_VERSION && this.tech_.readyState() === 0) {
  24311. // IE11 throws an InvalidStateError if you try to set currentTime while the
  24312. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  24313. this.tech_.one('loadedmetadata', () => {
  24314. this.trigger('firstplay');
  24315. this.tech_.setCurrentTime(seekable.end(0));
  24316. this.hasPlayed_ = true;
  24317. });
  24318. return false;
  24319. } // trigger firstplay to inform the source handler to ignore the next seek event
  24320. this.trigger('firstplay'); // seek to the live point
  24321. this.tech_.setCurrentTime(seekable.end(0));
  24322. }
  24323. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  24324. this.load();
  24325. return true;
  24326. }
  24327. /**
  24328. * handle the sourceopen event on the MediaSource
  24329. *
  24330. * @private
  24331. */
  24332. handleSourceOpen_() {
  24333. // Only attempt to create the source buffer if none already exist.
  24334. // handleSourceOpen is also called when we are "re-opening" a source buffer
  24335. // after `endOfStream` has been called (in response to a seek for instance)
  24336. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  24337. // code in video.js but is required because play() must be invoked
  24338. // *after* the media source has opened.
  24339. if (this.tech_.autoplay()) {
  24340. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  24341. // on browsers which return a promise
  24342. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  24343. playPromise.then(null, e => {});
  24344. }
  24345. }
  24346. this.trigger('sourceopen');
  24347. }
  24348. /**
  24349. * handle the sourceended event on the MediaSource
  24350. *
  24351. * @private
  24352. */
  24353. handleSourceEnded_() {
  24354. if (!this.inbandTextTracks_.metadataTrack_) {
  24355. return;
  24356. }
  24357. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  24358. if (!cues || !cues.length) {
  24359. return;
  24360. }
  24361. const duration = this.duration();
  24362. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  24363. }
  24364. /**
  24365. * handle the durationchange event on the MediaSource
  24366. *
  24367. * @private
  24368. */
  24369. handleDurationChange_() {
  24370. this.tech_.trigger('durationchange');
  24371. }
  24372. /**
  24373. * Calls endOfStream on the media source when all active stream types have called
  24374. * endOfStream
  24375. *
  24376. * @param {string} streamType
  24377. * Stream type of the segment loader that called endOfStream
  24378. * @private
  24379. */
  24380. onEndOfStream() {
  24381. let isEndOfStream = this.mainSegmentLoader_.ended_;
  24382. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24383. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  24384. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  24385. // if we do not know if the main segment loader contains video yet or if we
  24386. // definitively know the main segment loader contains video, then we need to wait
  24387. // for both main and audio segment loaders to call endOfStream
  24388. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  24389. } else {
  24390. // otherwise just rely on the audio loader
  24391. isEndOfStream = this.audioSegmentLoader_.ended_;
  24392. }
  24393. }
  24394. if (!isEndOfStream) {
  24395. return;
  24396. }
  24397. this.stopABRTimer_();
  24398. this.sourceUpdater_.endOfStream();
  24399. }
  24400. /**
  24401. * Check if a playlist has stopped being updated
  24402. *
  24403. * @param {Object} playlist the media playlist object
  24404. * @return {boolean} whether the playlist has stopped being updated or not
  24405. */
  24406. stuckAtPlaylistEnd_(playlist) {
  24407. const seekable = this.seekable();
  24408. if (!seekable.length) {
  24409. // playlist doesn't have enough information to determine whether we are stuck
  24410. return false;
  24411. }
  24412. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  24413. if (expired === null) {
  24414. return false;
  24415. } // does not use the safe live end to calculate playlist end, since we
  24416. // don't want to say we are stuck while there is still content
  24417. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  24418. const currentTime = this.tech_.currentTime();
  24419. const buffered = this.tech_.buffered();
  24420. if (!buffered.length) {
  24421. // return true if the playhead reached the absolute end of the playlist
  24422. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  24423. }
  24424. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  24425. // end of playlist
  24426. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  24427. }
  24428. /**
  24429. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  24430. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  24431. *
  24432. * @param {Object=} playlistToExclude
  24433. * the playlist to exclude, defaults to the currently selected playlist
  24434. * @param {Object=} error
  24435. * an optional error
  24436. * @param {number=} playlistExclusionDuration
  24437. * an optional number of seconds to exclude the playlist
  24438. */
  24439. excludePlaylist({
  24440. playlistToExclude = this.mainPlaylistLoader_.media(),
  24441. error = {},
  24442. playlistExclusionDuration
  24443. }) {
  24444. // If the `error` was generated by the playlist loader, it will contain
  24445. // the playlist we were trying to load (but failed) and that should be
  24446. // excluded instead of the currently selected playlist which is likely
  24447. // out-of-date in this scenario
  24448. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  24449. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  24450. // trying to load the main OR while we were disposing of the tech
  24451. if (!playlistToExclude) {
  24452. this.error = error;
  24453. if (this.mediaSource.readyState !== 'open') {
  24454. this.trigger('error');
  24455. } else {
  24456. this.sourceUpdater_.endOfStream('network');
  24457. }
  24458. return;
  24459. }
  24460. playlistToExclude.playlistErrors_++;
  24461. const playlists = this.mainPlaylistLoader_.main.playlists;
  24462. const enabledPlaylists = playlists.filter(isEnabled);
  24463. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  24464. // forever
  24465. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  24466. videojs__default["default"].log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  24467. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  24468. return this.mainPlaylistLoader_.load(isFinalRendition);
  24469. }
  24470. if (isFinalRendition) {
  24471. // Since we're on the final non-excluded playlist, and we're about to exclude
  24472. // it, instead of erring the player or retrying this playlist, clear out the current
  24473. // exclusion list. This allows other playlists to be attempted in case any have been
  24474. // fixed.
  24475. let reincluded = false;
  24476. playlists.forEach(playlist => {
  24477. // skip current playlist which is about to be excluded
  24478. if (playlist === playlistToExclude) {
  24479. return;
  24480. }
  24481. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  24482. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  24483. reincluded = true;
  24484. delete playlist.excludeUntil;
  24485. }
  24486. });
  24487. if (reincluded) {
  24488. videojs__default["default"].log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
  24489. // playlist. This is needed for users relying on the retryplaylist event to catch a
  24490. // case where the player might be stuck and looping through "dead" playlists.
  24491. this.tech_.trigger('retryplaylist');
  24492. }
  24493. } // Exclude this playlist
  24494. let excludeUntil;
  24495. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  24496. excludeUntil = Infinity;
  24497. } else {
  24498. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  24499. }
  24500. playlistToExclude.excludeUntil = excludeUntil;
  24501. if (error.reason) {
  24502. playlistToExclude.lastExcludeReason_ = error.reason;
  24503. }
  24504. this.tech_.trigger('excludeplaylist');
  24505. this.tech_.trigger({
  24506. type: 'usage',
  24507. name: 'vhs-rendition-excluded'
  24508. }); // TODO: only load a new playlist if we're excluding the current playlist
  24509. // If this function was called with a playlist that's not the current active playlist
  24510. // (e.g., media().id !== playlistToExclude.id),
  24511. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  24512. const nextPlaylist = this.selectPlaylist();
  24513. if (!nextPlaylist) {
  24514. this.error = 'Playback cannot continue. No available working or supported playlists.';
  24515. this.trigger('error');
  24516. return;
  24517. }
  24518. const logFn = error.internal ? this.logger_ : videojs__default["default"].log.warn;
  24519. const errorMessage = error.message ? ' ' + error.message : '';
  24520. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  24521. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  24522. this.delegateLoaders_('audio', ['abort', 'pause']);
  24523. } // if subtitle group changed reset subtitle loaders
  24524. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  24525. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  24526. }
  24527. this.delegateLoaders_('main', ['abort', 'pause']);
  24528. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  24529. const shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
  24530. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  24531. }
  24532. /**
  24533. * Pause all segment/playlist loaders
  24534. */
  24535. pauseLoading() {
  24536. this.delegateLoaders_('all', ['abort', 'pause']);
  24537. this.stopABRTimer_();
  24538. }
  24539. /**
  24540. * Call a set of functions in order on playlist loaders, segment loaders,
  24541. * or both types of loaders.
  24542. *
  24543. * @param {string} filter
  24544. * Filter loaders that should call fnNames using a string. Can be:
  24545. * * all - run on all loaders
  24546. * * audio - run on all audio loaders
  24547. * * subtitle - run on all subtitle loaders
  24548. * * main - run on the main loaders
  24549. *
  24550. * @param {Array|string} fnNames
  24551. * A string or array of function names to call.
  24552. */
  24553. delegateLoaders_(filter, fnNames) {
  24554. const loaders = [];
  24555. const dontFilterPlaylist = filter === 'all';
  24556. if (dontFilterPlaylist || filter === 'main') {
  24557. loaders.push(this.mainPlaylistLoader_);
  24558. }
  24559. const mediaTypes = [];
  24560. if (dontFilterPlaylist || filter === 'audio') {
  24561. mediaTypes.push('AUDIO');
  24562. }
  24563. if (dontFilterPlaylist || filter === 'subtitle') {
  24564. mediaTypes.push('CLOSED-CAPTIONS');
  24565. mediaTypes.push('SUBTITLES');
  24566. }
  24567. mediaTypes.forEach(mediaType => {
  24568. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  24569. if (loader) {
  24570. loaders.push(loader);
  24571. }
  24572. });
  24573. ['main', 'audio', 'subtitle'].forEach(name => {
  24574. const loader = this[`${name}SegmentLoader_`];
  24575. if (loader && (filter === name || filter === 'all')) {
  24576. loaders.push(loader);
  24577. }
  24578. });
  24579. loaders.forEach(loader => fnNames.forEach(fnName => {
  24580. if (typeof loader[fnName] === 'function') {
  24581. loader[fnName]();
  24582. }
  24583. }));
  24584. }
  24585. /**
  24586. * set the current time on all segment loaders
  24587. *
  24588. * @param {TimeRange} currentTime the current time to set
  24589. * @return {TimeRange} the current time
  24590. */
  24591. setCurrentTime(currentTime) {
  24592. const buffered = findRange(this.tech_.buffered(), currentTime);
  24593. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  24594. // return immediately if the metadata is not ready yet
  24595. return 0;
  24596. } // it's clearly an edge-case but don't thrown an error if asked to
  24597. // seek within an empty playlist
  24598. if (!this.mainPlaylistLoader_.media().segments) {
  24599. return 0;
  24600. } // if the seek location is already buffered, continue buffering as usual
  24601. if (buffered && buffered.length) {
  24602. return currentTime;
  24603. } // cancel outstanding requests so we begin buffering at the new
  24604. // location
  24605. this.mainSegmentLoader_.resetEverything();
  24606. this.mainSegmentLoader_.abort();
  24607. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24608. this.audioSegmentLoader_.resetEverything();
  24609. this.audioSegmentLoader_.abort();
  24610. }
  24611. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  24612. this.subtitleSegmentLoader_.resetEverything();
  24613. this.subtitleSegmentLoader_.abort();
  24614. } // start segment loader loading in case they are paused
  24615. this.load();
  24616. }
  24617. /**
  24618. * get the current duration
  24619. *
  24620. * @return {TimeRange} the duration
  24621. */
  24622. duration() {
  24623. if (!this.mainPlaylistLoader_) {
  24624. return 0;
  24625. }
  24626. const media = this.mainPlaylistLoader_.media();
  24627. if (!media) {
  24628. // no playlists loaded yet, so can't determine a duration
  24629. return 0;
  24630. } // Don't rely on the media source for duration in the case of a live playlist since
  24631. // setting the native MediaSource's duration to infinity ends up with consequences to
  24632. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  24633. //
  24634. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  24635. // however, few browsers have support for setLiveSeekableRange()
  24636. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  24637. //
  24638. // Until a time when the duration of the media source can be set to infinity, and a
  24639. // seekable range specified across browsers, just return Infinity.
  24640. if (!media.endList) {
  24641. return Infinity;
  24642. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  24643. // available). If it's not available, fall back to a playlist-calculated estimate.
  24644. if (this.mediaSource) {
  24645. return this.mediaSource.duration;
  24646. }
  24647. return Vhs$1.Playlist.duration(media);
  24648. }
  24649. /**
  24650. * check the seekable range
  24651. *
  24652. * @return {TimeRange} the seekable range
  24653. */
  24654. seekable() {
  24655. return this.seekable_;
  24656. }
  24657. onSyncInfoUpdate_() {
  24658. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  24659. //
  24660. // A fix was made to this function where a check for
  24661. // this.sourceUpdater_.hasCreatedSourceBuffers
  24662. // was added to ensure that both source buffers were created before seekable was
  24663. // updated. However, it originally had a bug where it was checking for a true and
  24664. // returning early instead of checking for false. Setting it to check for false to
  24665. // return early though created other issues. A call to play() would check for seekable
  24666. // end without verifying that a seekable range was present. In addition, even checking
  24667. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  24668. // due to a media update calling load on the segment loaders, skipping a seek to live,
  24669. // thereby starting live streams at the beginning of the stream rather than at the end.
  24670. //
  24671. // This conditional should be fixed to wait for the creation of two source buffers at
  24672. // the same time as the other sections of code are fixed to properly seek to live and
  24673. // not throw an error due to checking for a seekable end when no seekable range exists.
  24674. //
  24675. // For now, fall back to the older behavior, with the understanding that the seekable
  24676. // range may not be completely correct, leading to a suboptimal initial live point.
  24677. if (!this.mainPlaylistLoader_) {
  24678. return;
  24679. }
  24680. let media = this.mainPlaylistLoader_.media();
  24681. if (!media) {
  24682. return;
  24683. }
  24684. let expired = this.syncController_.getExpiredTime(media, this.duration());
  24685. if (expired === null) {
  24686. // not enough information to update seekable
  24687. return;
  24688. }
  24689. const main = this.mainPlaylistLoader_.main;
  24690. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  24691. if (mainSeekable.length === 0) {
  24692. return;
  24693. }
  24694. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24695. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  24696. expired = this.syncController_.getExpiredTime(media, this.duration());
  24697. if (expired === null) {
  24698. return;
  24699. }
  24700. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  24701. if (audioSeekable.length === 0) {
  24702. return;
  24703. }
  24704. }
  24705. let oldEnd;
  24706. let oldStart;
  24707. if (this.seekable_ && this.seekable_.length) {
  24708. oldEnd = this.seekable_.end(0);
  24709. oldStart = this.seekable_.start(0);
  24710. }
  24711. if (!audioSeekable) {
  24712. // seekable has been calculated based on buffering video data so it
  24713. // can be returned directly
  24714. this.seekable_ = mainSeekable;
  24715. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  24716. // seekables are pretty far off, rely on main
  24717. this.seekable_ = mainSeekable;
  24718. } else {
  24719. this.seekable_ = createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
  24720. } // seekable is the same as last time
  24721. if (this.seekable_ && this.seekable_.length) {
  24722. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  24723. return;
  24724. }
  24725. }
  24726. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  24727. this.tech_.trigger('seekablechanged');
  24728. }
  24729. /**
  24730. * Update the player duration
  24731. */
  24732. updateDuration(isLive) {
  24733. if (this.updateDuration_) {
  24734. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  24735. this.updateDuration_ = null;
  24736. }
  24737. if (this.mediaSource.readyState !== 'open') {
  24738. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  24739. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  24740. return;
  24741. }
  24742. if (isLive) {
  24743. const seekable = this.seekable();
  24744. if (!seekable.length) {
  24745. return;
  24746. } // Even in the case of a live playlist, the native MediaSource's duration should not
  24747. // be set to Infinity (even though this would be expected for a live playlist), since
  24748. // setting the native MediaSource's duration to infinity ends up with consequences to
  24749. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  24750. //
  24751. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  24752. // however, few browsers have support for setLiveSeekableRange()
  24753. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  24754. //
  24755. // Until a time when the duration of the media source can be set to infinity, and a
  24756. // seekable range specified across browsers, the duration should be greater than or
  24757. // equal to the last possible seekable value.
  24758. // MediaSource duration starts as NaN
  24759. // It is possible (and probable) that this case will never be reached for many
  24760. // sources, since the MediaSource reports duration as the highest value without
  24761. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  24762. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  24763. // time will be between 0 and 100, the native media source may report the duration
  24764. // as 200. However, since we report duration separate from the media source (as
  24765. // Infinity), and as long as the native media source duration value is greater than
  24766. // our reported seekable range, seeks will work as expected. The large number as
  24767. // duration for live is actually a strategy used by some players to work around the
  24768. // issue of live seekable ranges cited above.
  24769. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  24770. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  24771. }
  24772. return;
  24773. }
  24774. const buffered = this.tech_.buffered();
  24775. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  24776. if (buffered.length > 0) {
  24777. duration = Math.max(duration, buffered.end(buffered.length - 1));
  24778. }
  24779. if (this.mediaSource.duration !== duration) {
  24780. this.sourceUpdater_.setDuration(duration);
  24781. }
  24782. }
  24783. /**
  24784. * dispose of the PlaylistController and everything
  24785. * that it controls
  24786. */
  24787. dispose() {
  24788. this.trigger('dispose');
  24789. this.decrypter_.terminate();
  24790. this.mainPlaylistLoader_.dispose();
  24791. this.mainSegmentLoader_.dispose();
  24792. if (this.loadOnPlay_) {
  24793. this.tech_.off('play', this.loadOnPlay_);
  24794. }
  24795. ['AUDIO', 'SUBTITLES'].forEach(type => {
  24796. const groups = this.mediaTypes_[type].groups;
  24797. for (const id in groups) {
  24798. groups[id].forEach(group => {
  24799. if (group.playlistLoader) {
  24800. group.playlistLoader.dispose();
  24801. }
  24802. });
  24803. }
  24804. });
  24805. this.audioSegmentLoader_.dispose();
  24806. this.subtitleSegmentLoader_.dispose();
  24807. this.sourceUpdater_.dispose();
  24808. this.timelineChangeController_.dispose();
  24809. this.stopABRTimer_();
  24810. if (this.updateDuration_) {
  24811. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  24812. }
  24813. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  24814. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  24815. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  24816. this.off();
  24817. }
  24818. /**
  24819. * return the main playlist object if we have one
  24820. *
  24821. * @return {Object} the main playlist object that we parsed
  24822. */
  24823. main() {
  24824. return this.mainPlaylistLoader_.main;
  24825. }
  24826. /**
  24827. * return the currently selected playlist
  24828. *
  24829. * @return {Object} the currently selected playlist object that we parsed
  24830. */
  24831. media() {
  24832. // playlist loader will not return media if it has not been fully loaded
  24833. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  24834. }
  24835. areMediaTypesKnown_() {
  24836. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  24837. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  24838. // otherwise check on the segment loader.
  24839. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  24840. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  24841. return false;
  24842. }
  24843. return true;
  24844. }
  24845. getCodecsOrExclude_() {
  24846. const media = {
  24847. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  24848. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  24849. };
  24850. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  24851. media.video = media.main;
  24852. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  24853. const codecs = {};
  24854. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  24855. if (media.main.hasVideo) {
  24856. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  24857. }
  24858. if (media.main.isMuxed) {
  24859. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  24860. }
  24861. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  24862. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  24863. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  24864. } // no codecs, no playback.
  24865. if (!codecs.audio && !codecs.video) {
  24866. this.excludePlaylist({
  24867. playlistToExclude: playlist,
  24868. error: {
  24869. message: 'Could not determine codecs for playlist.'
  24870. },
  24871. playlistExclusionDuration: Infinity
  24872. });
  24873. return;
  24874. } // fmp4 relies on browser support, while ts relies on muxer support
  24875. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  24876. const unsupportedCodecs = {};
  24877. let unsupportedAudio;
  24878. ['video', 'audio'].forEach(function (type) {
  24879. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  24880. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  24881. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  24882. unsupportedCodecs[supporter].push(codecs[type]);
  24883. if (type === 'audio') {
  24884. unsupportedAudio = supporter;
  24885. }
  24886. }
  24887. });
  24888. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  24889. const audioGroup = playlist.attributes.AUDIO;
  24890. this.main().playlists.forEach(variant => {
  24891. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  24892. if (variantAudioGroup === audioGroup && variant !== playlist) {
  24893. variant.excludeUntil = Infinity;
  24894. }
  24895. });
  24896. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  24897. } // if we have any unsupported codecs exclude this playlist.
  24898. if (Object.keys(unsupportedCodecs).length) {
  24899. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  24900. if (acc) {
  24901. acc += ', ';
  24902. }
  24903. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  24904. return acc;
  24905. }, '') + '.';
  24906. this.excludePlaylist({
  24907. playlistToExclude: playlist,
  24908. error: {
  24909. internal: true,
  24910. message
  24911. },
  24912. playlistExclusionDuration: Infinity
  24913. });
  24914. return;
  24915. } // check if codec switching is happening
  24916. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  24917. const switchMessages = [];
  24918. ['video', 'audio'].forEach(type => {
  24919. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  24920. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  24921. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  24922. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  24923. }
  24924. });
  24925. if (switchMessages.length) {
  24926. this.excludePlaylist({
  24927. playlistToExclude: playlist,
  24928. error: {
  24929. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  24930. internal: true
  24931. },
  24932. playlistExclusionDuration: Infinity
  24933. });
  24934. return;
  24935. }
  24936. } // TODO: when using the muxer shouldn't we just return
  24937. // the codecs that the muxer outputs?
  24938. return codecs;
  24939. }
  24940. /**
  24941. * Create source buffers and exlude any incompatible renditions.
  24942. *
  24943. * @private
  24944. */
  24945. tryToCreateSourceBuffers_() {
  24946. // media source is not ready yet or sourceBuffers are already
  24947. // created.
  24948. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  24949. return;
  24950. }
  24951. if (!this.areMediaTypesKnown_()) {
  24952. return;
  24953. }
  24954. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  24955. if (!codecs) {
  24956. return;
  24957. }
  24958. this.sourceUpdater_.createSourceBuffers(codecs);
  24959. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  24960. this.excludeIncompatibleVariants_(codecString);
  24961. }
  24962. /**
  24963. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  24964. */
  24965. excludeUnsupportedVariants_() {
  24966. const playlists = this.main().playlists;
  24967. const ids = []; // TODO: why don't we have a property to loop through all
  24968. // playlist? Why did we ever mix indexes and keys?
  24969. Object.keys(playlists).forEach(key => {
  24970. const variant = playlists[key]; // check if we already processed this playlist.
  24971. if (ids.indexOf(variant.id) !== -1) {
  24972. return;
  24973. }
  24974. ids.push(variant.id);
  24975. const codecs = codecsForPlaylist(this.main, variant);
  24976. const unsupported = [];
  24977. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  24978. unsupported.push(`audio codec ${codecs.audio}`);
  24979. }
  24980. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  24981. unsupported.push(`video codec ${codecs.video}`);
  24982. }
  24983. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  24984. unsupported.push(`text codec ${codecs.text}`);
  24985. }
  24986. if (unsupported.length) {
  24987. variant.excludeUntil = Infinity;
  24988. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  24989. }
  24990. });
  24991. }
  24992. /**
  24993. * Exclude playlists that are known to be codec or
  24994. * stream-incompatible with the SourceBuffer configuration. For
  24995. * instance, Media Source Extensions would cause the video element to
  24996. * stall waiting for video data if you switched from a variant with
  24997. * video and audio to an audio-only one.
  24998. *
  24999. * @param {Object} media a media playlist compatible with the current
  25000. * set of SourceBuffers. Variants in the current main playlist that
  25001. * do not appear to have compatible codec or stream configurations
  25002. * will be excluded from the default playlist selection algorithm
  25003. * indefinitely.
  25004. * @private
  25005. */
  25006. excludeIncompatibleVariants_(codecString) {
  25007. const ids = [];
  25008. const playlists = this.main().playlists;
  25009. const codecs = unwrapCodecList(parseCodecs(codecString));
  25010. const codecCount_ = codecCount(codecs);
  25011. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  25012. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  25013. Object.keys(playlists).forEach(key => {
  25014. const variant = playlists[key]; // check if we already processed this playlist.
  25015. // or it if it is already excluded forever.
  25016. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  25017. return;
  25018. }
  25019. ids.push(variant.id);
  25020. const exclusionReasons = []; // get codecs from the playlist for this variant
  25021. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  25022. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  25023. // variant is incompatible. Wait for mux.js to probe
  25024. if (!variantCodecs.audio && !variantCodecs.video) {
  25025. return;
  25026. } // TODO: we can support this by removing the
  25027. // old media source and creating a new one, but it will take some work.
  25028. // The number of streams cannot change
  25029. if (variantCodecCount !== codecCount_) {
  25030. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  25031. } // only exclude playlists by codec change, if codecs cannot switch
  25032. // during playback.
  25033. if (!this.sourceUpdater_.canChangeType()) {
  25034. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  25035. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  25036. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  25037. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  25038. } // the audio codec cannot change
  25039. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  25040. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  25041. }
  25042. }
  25043. if (exclusionReasons.length) {
  25044. variant.excludeUntil = Infinity;
  25045. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  25046. }
  25047. });
  25048. }
  25049. updateAdCues_(media) {
  25050. let offset = 0;
  25051. const seekable = this.seekable();
  25052. if (seekable.length) {
  25053. offset = seekable.start(0);
  25054. }
  25055. updateAdCues(media, this.cueTagsTrack_, offset);
  25056. }
  25057. /**
  25058. * Calculates the desired forward buffer length based on current time
  25059. *
  25060. * @return {number} Desired forward buffer length in seconds
  25061. */
  25062. goalBufferLength() {
  25063. const currentTime = this.tech_.currentTime();
  25064. const initial = Config.GOAL_BUFFER_LENGTH;
  25065. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  25066. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  25067. return Math.min(initial + currentTime * rate, max);
  25068. }
  25069. /**
  25070. * Calculates the desired buffer low water line based on current time
  25071. *
  25072. * @return {number} Desired buffer low water line in seconds
  25073. */
  25074. bufferLowWaterLine() {
  25075. const currentTime = this.tech_.currentTime();
  25076. const initial = Config.BUFFER_LOW_WATER_LINE;
  25077. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  25078. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  25079. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  25080. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  25081. }
  25082. bufferHighWaterLine() {
  25083. return Config.BUFFER_HIGH_WATER_LINE;
  25084. }
  25085. }
  25086. /**
  25087. * Returns a function that acts as the Enable/disable playlist function.
  25088. *
  25089. * @param {PlaylistLoader} loader - The main playlist loader
  25090. * @param {string} playlistID - id of the playlist
  25091. * @param {Function} changePlaylistFn - A function to be called after a
  25092. * playlist's enabled-state has been changed. Will NOT be called if a
  25093. * playlist's enabled-state is unchanged
  25094. * @param {boolean=} enable - Value to set the playlist enabled-state to
  25095. * or if undefined returns the current enabled-state for the playlist
  25096. * @return {Function} Function for setting/getting enabled
  25097. */
  25098. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  25099. const playlist = loader.main.playlists[playlistID];
  25100. const incompatible = isIncompatible(playlist);
  25101. const currentlyEnabled = isEnabled(playlist);
  25102. if (typeof enable === 'undefined') {
  25103. return currentlyEnabled;
  25104. }
  25105. if (enable) {
  25106. delete playlist.disabled;
  25107. } else {
  25108. playlist.disabled = true;
  25109. }
  25110. if (enable !== currentlyEnabled && !incompatible) {
  25111. // Ensure the outside world knows about our changes
  25112. changePlaylistFn();
  25113. if (enable) {
  25114. loader.trigger('renditionenabled');
  25115. } else {
  25116. loader.trigger('renditiondisabled');
  25117. }
  25118. }
  25119. return enable;
  25120. };
  25121. /**
  25122. * The representation object encapsulates the publicly visible information
  25123. * in a media playlist along with a setter/getter-type function (enabled)
  25124. * for changing the enabled-state of a particular playlist entry
  25125. *
  25126. * @class Representation
  25127. */
  25128. class Representation {
  25129. constructor(vhsHandler, playlist, id) {
  25130. const {
  25131. playlistController_: pc
  25132. } = vhsHandler;
  25133. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  25134. if (playlist.attributes) {
  25135. const resolution = playlist.attributes.RESOLUTION;
  25136. this.width = resolution && resolution.width;
  25137. this.height = resolution && resolution.height;
  25138. this.bandwidth = playlist.attributes.BANDWIDTH;
  25139. this.frameRate = playlist.attributes['FRAME-RATE'];
  25140. }
  25141. this.codecs = codecsForPlaylist(pc.main(), playlist);
  25142. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  25143. // within the main playlist
  25144. this.id = id; // Partially-apply the enableFunction to create a playlist-
  25145. // specific variant
  25146. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  25147. }
  25148. }
  25149. /**
  25150. * A mixin function that adds the `representations` api to an instance
  25151. * of the VhsHandler class
  25152. *
  25153. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  25154. * representation API into
  25155. */
  25156. const renditionSelectionMixin = function (vhsHandler) {
  25157. // Add a single API-specific function to the VhsHandler instance
  25158. vhsHandler.representations = () => {
  25159. const main = vhsHandler.playlistController_.main();
  25160. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  25161. if (!playlists) {
  25162. return [];
  25163. }
  25164. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  25165. };
  25166. };
  25167. /**
  25168. * @file playback-watcher.js
  25169. *
  25170. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  25171. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  25172. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  25173. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  25174. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  25175. */
  25176. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  25177. /**
  25178. * @class PlaybackWatcher
  25179. */
  25180. class PlaybackWatcher {
  25181. /**
  25182. * Represents an PlaybackWatcher object.
  25183. *
  25184. * @class
  25185. * @param {Object} options an object that includes the tech and settings
  25186. */
  25187. constructor(options) {
  25188. this.playlistController_ = options.playlistController;
  25189. this.tech_ = options.tech;
  25190. this.seekable = options.seekable;
  25191. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  25192. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  25193. this.media = options.media;
  25194. this.consecutiveUpdates = 0;
  25195. this.lastRecordedTime = null;
  25196. this.checkCurrentTimeTimeout_ = null;
  25197. this.logger_ = logger('PlaybackWatcher');
  25198. this.logger_('initialize');
  25199. const playHandler = () => this.monitorCurrentTime_();
  25200. const canPlayHandler = () => this.monitorCurrentTime_();
  25201. const waitingHandler = () => this.techWaiting_();
  25202. const cancelTimerHandler = () => this.resetTimeUpdate_();
  25203. const pc = this.playlistController_;
  25204. const loaderTypes = ['main', 'subtitle', 'audio'];
  25205. const loaderChecks = {};
  25206. loaderTypes.forEach(type => {
  25207. loaderChecks[type] = {
  25208. reset: () => this.resetSegmentDownloads_(type),
  25209. updateend: () => this.checkSegmentDownloads_(type)
  25210. };
  25211. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  25212. // isn't changing we want to reset. We cannot assume that the new rendition
  25213. // will also be stalled, until after new appends.
  25214. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  25215. // This prevents one segment playlists (single vtt or single segment content)
  25216. // from being detected as stalling. As the buffer will not change in those cases, since
  25217. // the buffer is the entire video duration.
  25218. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  25219. });
  25220. /**
  25221. * We check if a seek was into a gap through the following steps:
  25222. * 1. We get a seeking event and we do not get a seeked event. This means that
  25223. * a seek was attempted but not completed.
  25224. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  25225. * removed everything from our buffer and appended a segment, and should be ready
  25226. * to check for gaps.
  25227. */
  25228. const setSeekingHandlers = fn => {
  25229. ['main', 'audio'].forEach(type => {
  25230. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  25231. });
  25232. };
  25233. this.seekingAppendCheck_ = () => {
  25234. if (this.fixesBadSeeks_()) {
  25235. this.consecutiveUpdates = 0;
  25236. this.lastRecordedTime = this.tech_.currentTime();
  25237. setSeekingHandlers('off');
  25238. }
  25239. };
  25240. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  25241. this.watchForBadSeeking_ = () => {
  25242. this.clearSeekingAppendCheck_();
  25243. setSeekingHandlers('on');
  25244. };
  25245. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  25246. this.tech_.on('seeking', this.watchForBadSeeking_);
  25247. this.tech_.on('waiting', waitingHandler);
  25248. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  25249. this.tech_.on('canplay', canPlayHandler);
  25250. /*
  25251. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  25252. is surfaced in one of two ways:
  25253. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  25254. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  25255. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  25256. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  25257. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  25258. even if the player is in a playing state
  25259. */
  25260. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  25261. this.dispose = () => {
  25262. this.clearSeekingAppendCheck_();
  25263. this.logger_('dispose');
  25264. this.tech_.off('waiting', waitingHandler);
  25265. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  25266. this.tech_.off('canplay', canPlayHandler);
  25267. this.tech_.off('play', playHandler);
  25268. this.tech_.off('seeking', this.watchForBadSeeking_);
  25269. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  25270. loaderTypes.forEach(type => {
  25271. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  25272. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  25273. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  25274. });
  25275. if (this.checkCurrentTimeTimeout_) {
  25276. window.clearTimeout(this.checkCurrentTimeTimeout_);
  25277. }
  25278. this.resetTimeUpdate_();
  25279. };
  25280. }
  25281. /**
  25282. * Periodically check current time to see if playback stopped
  25283. *
  25284. * @private
  25285. */
  25286. monitorCurrentTime_() {
  25287. this.checkCurrentTime_();
  25288. if (this.checkCurrentTimeTimeout_) {
  25289. window.clearTimeout(this.checkCurrentTimeTimeout_);
  25290. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  25291. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  25292. }
  25293. /**
  25294. * Reset stalled download stats for a specific type of loader
  25295. *
  25296. * @param {string} type
  25297. * The segment loader type to check.
  25298. *
  25299. * @listens SegmentLoader#playlistupdate
  25300. * @listens Tech#seeking
  25301. * @listens Tech#seeked
  25302. */
  25303. resetSegmentDownloads_(type) {
  25304. const loader = this.playlistController_[`${type}SegmentLoader_`];
  25305. if (this[`${type}StalledDownloads_`] > 0) {
  25306. this.logger_(`resetting possible stalled download count for ${type} loader`);
  25307. }
  25308. this[`${type}StalledDownloads_`] = 0;
  25309. this[`${type}Buffered_`] = loader.buffered_();
  25310. }
  25311. /**
  25312. * Checks on every segment `appendsdone` to see
  25313. * if segment appends are making progress. If they are not
  25314. * and we are still downloading bytes. We exclude the playlist.
  25315. *
  25316. * @param {string} type
  25317. * The segment loader type to check.
  25318. *
  25319. * @listens SegmentLoader#appendsdone
  25320. */
  25321. checkSegmentDownloads_(type) {
  25322. const pc = this.playlistController_;
  25323. const loader = pc[`${type}SegmentLoader_`];
  25324. const buffered = loader.buffered_();
  25325. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  25326. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  25327. // the buffered value for this loader changed
  25328. // appends are working
  25329. if (isBufferedDifferent) {
  25330. this.resetSegmentDownloads_(type);
  25331. return;
  25332. }
  25333. this[`${type}StalledDownloads_`]++;
  25334. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  25335. playlistId: loader.playlist_ && loader.playlist_.id,
  25336. buffered: timeRangesToArray(buffered)
  25337. }); // after 10 possibly stalled appends with no reset, exclude
  25338. if (this[`${type}StalledDownloads_`] < 10) {
  25339. return;
  25340. }
  25341. this.logger_(`${type} loader stalled download exclusion`);
  25342. this.resetSegmentDownloads_(type);
  25343. this.tech_.trigger({
  25344. type: 'usage',
  25345. name: `vhs-${type}-download-exclusion`
  25346. });
  25347. if (type === 'subtitle') {
  25348. return;
  25349. } // TODO: should we exclude audio tracks rather than main tracks
  25350. // when type is audio?
  25351. pc.excludePlaylist({
  25352. error: {
  25353. message: `Excessive ${type} segment downloading detected.`
  25354. },
  25355. playlistExclusionDuration: Infinity
  25356. });
  25357. }
  25358. /**
  25359. * The purpose of this function is to emulate the "waiting" event on
  25360. * browsers that do not emit it when they are waiting for more
  25361. * data to continue playback
  25362. *
  25363. * @private
  25364. */
  25365. checkCurrentTime_() {
  25366. if (this.tech_.paused() || this.tech_.seeking()) {
  25367. return;
  25368. }
  25369. const currentTime = this.tech_.currentTime();
  25370. const buffered = this.tech_.buffered();
  25371. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  25372. // If current time is at the end of the final buffered region, then any playback
  25373. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  25374. // should fire a `waiting` event in this scenario, but due to browser and tech
  25375. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  25376. // responding to a native `waiting` event when the tech fails to emit one.
  25377. return this.techWaiting_();
  25378. }
  25379. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  25380. this.consecutiveUpdates++;
  25381. this.waiting_();
  25382. } else if (currentTime === this.lastRecordedTime) {
  25383. this.consecutiveUpdates++;
  25384. } else {
  25385. this.consecutiveUpdates = 0;
  25386. this.lastRecordedTime = currentTime;
  25387. }
  25388. }
  25389. /**
  25390. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  25391. *
  25392. * @private
  25393. */
  25394. resetTimeUpdate_() {
  25395. this.consecutiveUpdates = 0;
  25396. }
  25397. /**
  25398. * Fixes situations where there's a bad seek
  25399. *
  25400. * @return {boolean} whether an action was taken to fix the seek
  25401. * @private
  25402. */
  25403. fixesBadSeeks_() {
  25404. const seeking = this.tech_.seeking();
  25405. if (!seeking) {
  25406. return false;
  25407. } // TODO: It's possible that these seekable checks should be moved out of this function
  25408. // and into a function that runs on seekablechange. It's also possible that we only need
  25409. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  25410. // seekable range.
  25411. const seekable = this.seekable();
  25412. const currentTime = this.tech_.currentTime();
  25413. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  25414. let seekTo;
  25415. if (isAfterSeekableRange) {
  25416. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  25417. seekTo = seekableEnd;
  25418. }
  25419. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  25420. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  25421. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  25422. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  25423. // happen in live with a 3 segment playlist), then don't use a time delta
  25424. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  25425. }
  25426. if (typeof seekTo !== 'undefined') {
  25427. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  25428. this.tech_.setCurrentTime(seekTo);
  25429. return true;
  25430. }
  25431. const sourceUpdater = this.playlistController_.sourceUpdater_;
  25432. const buffered = this.tech_.buffered();
  25433. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  25434. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  25435. const media = this.media(); // verify that at least two segment durations or one part duration have been
  25436. // appended before checking for a gap.
  25437. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  25438. // appended before checking for a gap.
  25439. const bufferedToCheck = [audioBuffered, videoBuffered];
  25440. for (let i = 0; i < bufferedToCheck.length; i++) {
  25441. // skip null buffered
  25442. if (!bufferedToCheck[i]) {
  25443. continue;
  25444. }
  25445. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  25446. // duration behind we haven't appended enough to call this a bad seek.
  25447. if (timeAhead < minAppendedDuration) {
  25448. return false;
  25449. }
  25450. }
  25451. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  25452. // to seek over the gap
  25453. if (nextRange.length === 0) {
  25454. return false;
  25455. }
  25456. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  25457. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  25458. this.tech_.setCurrentTime(seekTo);
  25459. return true;
  25460. }
  25461. /**
  25462. * Handler for situations when we determine the player is waiting.
  25463. *
  25464. * @private
  25465. */
  25466. waiting_() {
  25467. if (this.techWaiting_()) {
  25468. return;
  25469. } // All tech waiting checks failed. Use last resort correction
  25470. const currentTime = this.tech_.currentTime();
  25471. const buffered = this.tech_.buffered();
  25472. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  25473. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  25474. // currentTime is usually enough to kickstart the player. This checks that the player
  25475. // is currently within a buffered region before attempting a corrective seek.
  25476. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  25477. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  25478. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  25479. // to avoid triggering an `unknownwaiting` event when the network is slow.
  25480. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  25481. this.resetTimeUpdate_();
  25482. this.tech_.setCurrentTime(currentTime);
  25483. this.logger_(`Stopped at ${currentTime} while inside a buffered region ` + `[${currentRange.start(0)} -> ${currentRange.end(0)}]. Attempting to resume ` + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
  25484. this.tech_.trigger({
  25485. type: 'usage',
  25486. name: 'vhs-unknown-waiting'
  25487. });
  25488. return;
  25489. }
  25490. }
  25491. /**
  25492. * Handler for situations when the tech fires a `waiting` event
  25493. *
  25494. * @return {boolean}
  25495. * True if an action (or none) was needed to correct the waiting. False if no
  25496. * checks passed
  25497. * @private
  25498. */
  25499. techWaiting_() {
  25500. const seekable = this.seekable();
  25501. const currentTime = this.tech_.currentTime();
  25502. if (this.tech_.seeking()) {
  25503. // Tech is seeking or already waiting on another action, no action needed
  25504. return true;
  25505. }
  25506. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  25507. const livePoint = seekable.end(seekable.length - 1);
  25508. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  25509. this.resetTimeUpdate_();
  25510. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  25511. this.tech_.trigger({
  25512. type: 'usage',
  25513. name: 'vhs-live-resync'
  25514. });
  25515. return true;
  25516. }
  25517. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  25518. const buffered = this.tech_.buffered();
  25519. const videoUnderflow = this.videoUnderflow_({
  25520. audioBuffered: sourceUpdater.audioBuffered(),
  25521. videoBuffered: sourceUpdater.videoBuffered(),
  25522. currentTime
  25523. });
  25524. if (videoUnderflow) {
  25525. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  25526. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  25527. // allows the video to catch up to the audio position without losing any audio
  25528. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  25529. this.resetTimeUpdate_();
  25530. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  25531. this.tech_.trigger({
  25532. type: 'usage',
  25533. name: 'vhs-video-underflow'
  25534. });
  25535. return true;
  25536. }
  25537. const nextRange = findNextRange(buffered, currentTime); // check for gap
  25538. if (nextRange.length > 0) {
  25539. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  25540. this.resetTimeUpdate_();
  25541. this.skipTheGap_(currentTime);
  25542. return true;
  25543. } // All checks failed. Returning false to indicate failure to correct waiting
  25544. return false;
  25545. }
  25546. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  25547. if (!seekable.length) {
  25548. // we can't make a solid case if there's no seekable, default to false
  25549. return false;
  25550. }
  25551. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  25552. const isLive = !playlist.endList;
  25553. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  25554. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  25555. }
  25556. if (currentTime > allowedEnd) {
  25557. return true;
  25558. }
  25559. return false;
  25560. }
  25561. beforeSeekableWindow_(seekable, currentTime) {
  25562. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  25563. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  25564. return true;
  25565. }
  25566. return false;
  25567. }
  25568. videoUnderflow_({
  25569. videoBuffered,
  25570. audioBuffered,
  25571. currentTime
  25572. }) {
  25573. // audio only content will not have video underflow :)
  25574. if (!videoBuffered) {
  25575. return;
  25576. }
  25577. let gap; // find a gap in demuxed content.
  25578. if (videoBuffered.length && audioBuffered.length) {
  25579. // in Chrome audio will continue to play for ~3s when we run out of video
  25580. // so we have to check that the video buffer did have some buffer in the
  25581. // past.
  25582. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  25583. const videoRange = findRange(videoBuffered, currentTime);
  25584. const audioRange = findRange(audioBuffered, currentTime);
  25585. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  25586. gap = {
  25587. start: lastVideoRange.end(0),
  25588. end: audioRange.end(0)
  25589. };
  25590. } // find a gap in muxed content.
  25591. } else {
  25592. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  25593. // stuck in a gap due to video underflow.
  25594. if (!nextRange.length) {
  25595. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  25596. }
  25597. }
  25598. if (gap) {
  25599. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  25600. return true;
  25601. }
  25602. return false;
  25603. }
  25604. /**
  25605. * Timer callback. If playback still has not proceeded, then we seek
  25606. * to the start of the next buffered region.
  25607. *
  25608. * @private
  25609. */
  25610. skipTheGap_(scheduledCurrentTime) {
  25611. const buffered = this.tech_.buffered();
  25612. const currentTime = this.tech_.currentTime();
  25613. const nextRange = findNextRange(buffered, currentTime);
  25614. this.resetTimeUpdate_();
  25615. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  25616. return;
  25617. }
  25618. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  25619. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  25620. this.tech_.trigger({
  25621. type: 'usage',
  25622. name: 'vhs-gap-skip'
  25623. });
  25624. }
  25625. gapFromVideoUnderflow_(buffered, currentTime) {
  25626. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  25627. // playing for ~3 seconds after the video gap starts. This is done to account for
  25628. // video buffer underflow/underrun (note that this is not done when there is audio
  25629. // buffer underflow/underrun -- in that case the video will stop as soon as it
  25630. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  25631. // video stalls). The player's time will reflect the playthrough of audio, so the
  25632. // time will appear as if we are in a buffered region, even if we are stuck in a
  25633. // "gap."
  25634. //
  25635. // Example:
  25636. // video buffer: 0 => 10.1, 10.2 => 20
  25637. // audio buffer: 0 => 20
  25638. // overall buffer: 0 => 10.1, 10.2 => 20
  25639. // current time: 13
  25640. //
  25641. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  25642. // however, the audio continued playing until it reached ~3 seconds past the gap
  25643. // (13 seconds), at which point it stops as well. Since current time is past the
  25644. // gap, findNextRange will return no ranges.
  25645. //
  25646. // To check for this issue, we see if there is a gap that starts somewhere within
  25647. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  25648. const gaps = findGaps(buffered);
  25649. for (let i = 0; i < gaps.length; i++) {
  25650. const start = gaps.start(i);
  25651. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  25652. if (currentTime - start < 4 && currentTime - start > 2) {
  25653. return {
  25654. start,
  25655. end
  25656. };
  25657. }
  25658. }
  25659. return null;
  25660. }
  25661. }
  25662. const defaultOptions = {
  25663. errorInterval: 30,
  25664. getSource(next) {
  25665. const tech = this.tech({
  25666. IWillNotUseThisInPlugins: true
  25667. });
  25668. const sourceObj = tech.currentSource_ || this.currentSource();
  25669. return next(sourceObj);
  25670. }
  25671. };
  25672. /**
  25673. * Main entry point for the plugin
  25674. *
  25675. * @param {Player} player a reference to a videojs Player instance
  25676. * @param {Object} [options] an object with plugin options
  25677. * @private
  25678. */
  25679. const initPlugin = function (player, options) {
  25680. let lastCalled = 0;
  25681. let seekTo = 0;
  25682. const localOptions = merge$1(defaultOptions, options);
  25683. player.ready(() => {
  25684. player.trigger({
  25685. type: 'usage',
  25686. name: 'vhs-error-reload-initialized'
  25687. });
  25688. });
  25689. /**
  25690. * Player modifications to perform that must wait until `loadedmetadata`
  25691. * has been triggered
  25692. *
  25693. * @private
  25694. */
  25695. const loadedMetadataHandler = function () {
  25696. if (seekTo) {
  25697. player.currentTime(seekTo);
  25698. }
  25699. };
  25700. /**
  25701. * Set the source on the player element, play, and seek if necessary
  25702. *
  25703. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  25704. * @private
  25705. */
  25706. const setSource = function (sourceObj) {
  25707. if (sourceObj === null || sourceObj === undefined) {
  25708. return;
  25709. }
  25710. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  25711. player.one('loadedmetadata', loadedMetadataHandler);
  25712. player.src(sourceObj);
  25713. player.trigger({
  25714. type: 'usage',
  25715. name: 'vhs-error-reload'
  25716. });
  25717. player.play();
  25718. };
  25719. /**
  25720. * Attempt to get a source from either the built-in getSource function
  25721. * or a custom function provided via the options
  25722. *
  25723. * @private
  25724. */
  25725. const errorHandler = function () {
  25726. // Do not attempt to reload the source if a source-reload occurred before
  25727. // 'errorInterval' time has elapsed since the last source-reload
  25728. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  25729. player.trigger({
  25730. type: 'usage',
  25731. name: 'vhs-error-reload-canceled'
  25732. });
  25733. return;
  25734. }
  25735. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  25736. videojs__default["default"].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  25737. return;
  25738. }
  25739. lastCalled = Date.now();
  25740. return localOptions.getSource.call(player, setSource);
  25741. };
  25742. /**
  25743. * Unbind any event handlers that were bound by the plugin
  25744. *
  25745. * @private
  25746. */
  25747. const cleanupEvents = function () {
  25748. player.off('loadedmetadata', loadedMetadataHandler);
  25749. player.off('error', errorHandler);
  25750. player.off('dispose', cleanupEvents);
  25751. };
  25752. /**
  25753. * Cleanup before re-initializing the plugin
  25754. *
  25755. * @param {Object} [newOptions] an object with plugin options
  25756. * @private
  25757. */
  25758. const reinitPlugin = function (newOptions) {
  25759. cleanupEvents();
  25760. initPlugin(player, newOptions);
  25761. };
  25762. player.on('error', errorHandler);
  25763. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  25764. // initializing the plugin
  25765. player.reloadSourceOnError = reinitPlugin;
  25766. };
  25767. /**
  25768. * Reload the source when an error is detected as long as there
  25769. * wasn't an error previously within the last 30 seconds
  25770. *
  25771. * @param {Object} [options] an object with plugin options
  25772. */
  25773. const reloadSourceOnError = function (options) {
  25774. initPlugin(this, options);
  25775. };
  25776. var version$4 = "3.0.2";
  25777. var version$3 = "6.3.0";
  25778. var version$2 = "1.0.1";
  25779. var version$1 = "6.0.0";
  25780. var version = "4.0.1";
  25781. /**
  25782. * @file videojs-http-streaming.js
  25783. *
  25784. * The main file for the VHS project.
  25785. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  25786. */
  25787. const Vhs = {
  25788. PlaylistLoader,
  25789. Playlist,
  25790. utils,
  25791. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  25792. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  25793. lastBandwidthSelector,
  25794. movingAverageBandwidthSelector,
  25795. comparePlaylistBandwidth,
  25796. comparePlaylistResolution,
  25797. xhr: xhrFactory()
  25798. }; // Define getter/setters for config properties
  25799. Object.keys(Config).forEach(prop => {
  25800. Object.defineProperty(Vhs, prop, {
  25801. get() {
  25802. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  25803. return Config[prop];
  25804. },
  25805. set(value) {
  25806. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  25807. if (typeof value !== 'number' || value < 0) {
  25808. videojs__default["default"].log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  25809. return;
  25810. }
  25811. Config[prop] = value;
  25812. }
  25813. });
  25814. });
  25815. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  25816. /**
  25817. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  25818. *
  25819. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  25820. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  25821. * @function handleVhsMediaChange
  25822. */
  25823. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  25824. const newPlaylist = playlistLoader.media();
  25825. let selectedIndex = -1;
  25826. for (let i = 0; i < qualityLevels.length; i++) {
  25827. if (qualityLevels[i].id === newPlaylist.id) {
  25828. selectedIndex = i;
  25829. break;
  25830. }
  25831. }
  25832. qualityLevels.selectedIndex_ = selectedIndex;
  25833. qualityLevels.trigger({
  25834. selectedIndex,
  25835. type: 'change'
  25836. });
  25837. };
  25838. /**
  25839. * Adds quality levels to list once playlist metadata is available
  25840. *
  25841. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  25842. * @param {Object} vhs Vhs object to listen to for media events.
  25843. * @function handleVhsLoadedMetadata
  25844. */
  25845. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  25846. vhs.representations().forEach(rep => {
  25847. qualityLevels.addQualityLevel(rep);
  25848. });
  25849. handleVhsMediaChange(qualityLevels, vhs.playlists);
  25850. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  25851. // as one do not cause exceptions.
  25852. Vhs.canPlaySource = function () {
  25853. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  25854. };
  25855. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  25856. if (!keySystemOptions) {
  25857. return keySystemOptions;
  25858. }
  25859. let codecs = {};
  25860. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  25861. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  25862. }
  25863. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  25864. codecs.audio = audioPlaylist.attributes.CODECS;
  25865. }
  25866. const videoContentType = getMimeForCodec(codecs.video);
  25867. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  25868. const keySystemContentTypes = {};
  25869. for (const keySystem in keySystemOptions) {
  25870. keySystemContentTypes[keySystem] = {};
  25871. if (audioContentType) {
  25872. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  25873. }
  25874. if (videoContentType) {
  25875. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  25876. } // Default to using the video playlist's PSSH even though they may be different, as
  25877. // videojs-contrib-eme will only accept one in the options.
  25878. //
  25879. // This shouldn't be an issue for most cases as early intialization will handle all
  25880. // unique PSSH values, and if they aren't, then encrypted events should have the
  25881. // specific information needed for the unique license.
  25882. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  25883. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  25884. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  25885. // so we need to prevent overwriting the URL entirely
  25886. if (typeof keySystemOptions[keySystem] === 'string') {
  25887. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  25888. }
  25889. }
  25890. return merge$1(keySystemOptions, keySystemContentTypes);
  25891. };
  25892. /**
  25893. * @typedef {Object} KeySystems
  25894. *
  25895. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  25896. * Note: not all options are listed here.
  25897. *
  25898. * @property {Uint8Array} [pssh]
  25899. * Protection System Specific Header
  25900. */
  25901. /**
  25902. * Goes through all the playlists and collects an array of KeySystems options objects
  25903. * containing each playlist's keySystems and their pssh values, if available.
  25904. *
  25905. * @param {Object[]} playlists
  25906. * The playlists to look through
  25907. * @param {string[]} keySystems
  25908. * The keySystems to collect pssh values for
  25909. *
  25910. * @return {KeySystems[]}
  25911. * An array of KeySystems objects containing available key systems and their
  25912. * pssh values
  25913. */
  25914. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  25915. return playlists.reduce((keySystemsArr, playlist) => {
  25916. if (!playlist.contentProtection) {
  25917. return keySystemsArr;
  25918. }
  25919. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  25920. const keySystemOptions = playlist.contentProtection[keySystem];
  25921. if (keySystemOptions && keySystemOptions.pssh) {
  25922. keySystemsObj[keySystem] = {
  25923. pssh: keySystemOptions.pssh
  25924. };
  25925. }
  25926. return keySystemsObj;
  25927. }, {});
  25928. if (Object.keys(keySystemsOptions).length) {
  25929. keySystemsArr.push(keySystemsOptions);
  25930. }
  25931. return keySystemsArr;
  25932. }, []);
  25933. };
  25934. /**
  25935. * Returns a promise that waits for the
  25936. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  25937. *
  25938. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  25939. * browsers.
  25940. *
  25941. * As per the above ticket, this is particularly important for Chrome, where, if
  25942. * unencrypted content is appended before encrypted content and the key session has not
  25943. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  25944. * during playback.
  25945. *
  25946. * @param {Object} player
  25947. * The player instance
  25948. * @param {Object[]} sourceKeySystems
  25949. * The key systems options from the player source
  25950. * @param {Object} [audioMedia]
  25951. * The active audio media playlist (optional)
  25952. * @param {Object[]} mainPlaylists
  25953. * The playlists found on the main playlist object
  25954. *
  25955. * @return {Object}
  25956. * Promise that resolves when the key session has been created
  25957. */
  25958. const waitForKeySessionCreation = ({
  25959. player,
  25960. sourceKeySystems,
  25961. audioMedia,
  25962. mainPlaylists
  25963. }) => {
  25964. if (!player.eme.initializeMediaKeys) {
  25965. return Promise.resolve();
  25966. } // TODO should all audio PSSH values be initialized for DRM?
  25967. //
  25968. // All unique video rendition pssh values are initialized for DRM, but here only
  25969. // the initial audio playlist license is initialized. In theory, an encrypted
  25970. // event should be fired if the user switches to an alternative audio playlist
  25971. // where a license is required, but this case hasn't yet been tested. In addition, there
  25972. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  25973. // languages).
  25974. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  25975. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  25976. const initializationFinishedPromises = [];
  25977. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  25978. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  25979. // return for IE11 above, and the existence of modern EME APIs in addition to
  25980. // ms-prefixed APIs on Edge should prevent this from being a concern.
  25981. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  25982. keySystemsOptionsArr.forEach(keySystemsOptions => {
  25983. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  25984. player.tech_.one('keysessioncreated', resolve);
  25985. }));
  25986. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  25987. player.eme.initializeMediaKeys({
  25988. keySystems: keySystemsOptions
  25989. }, err => {
  25990. if (err) {
  25991. reject(err);
  25992. return;
  25993. }
  25994. resolve();
  25995. });
  25996. }));
  25997. }); // The reasons Promise.race is chosen over Promise.any:
  25998. //
  25999. // * Promise.any is only available in Safari 14+.
  26000. // * None of these promises are expected to reject. If they do reject, it might be
  26001. // better here for the race to surface the rejection, rather than mask it by using
  26002. // Promise.any.
  26003. return Promise.race([// If a session was previously created, these will all finish resolving without
  26004. // creating a new session, otherwise it will take until the end of all license
  26005. // requests, which is why the key session check is used (to make setup much faster).
  26006. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  26007. Promise.race(keySessionCreatedPromises)]);
  26008. };
  26009. /**
  26010. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  26011. * there are keySystems on the source, sets up source options to prepare the source for
  26012. * eme.
  26013. *
  26014. * @param {Object} player
  26015. * The player instance
  26016. * @param {Object[]} sourceKeySystems
  26017. * The key systems options from the player source
  26018. * @param {Object} media
  26019. * The active media playlist
  26020. * @param {Object} [audioMedia]
  26021. * The active audio media playlist (optional)
  26022. *
  26023. * @return {boolean}
  26024. * Whether or not options were configured and EME is available
  26025. */
  26026. const setupEmeOptions = ({
  26027. player,
  26028. sourceKeySystems,
  26029. media,
  26030. audioMedia
  26031. }) => {
  26032. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  26033. if (!sourceOptions) {
  26034. return false;
  26035. }
  26036. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  26037. // do nothing.
  26038. if (sourceOptions && !player.eme) {
  26039. videojs__default["default"].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  26040. return false;
  26041. }
  26042. return true;
  26043. };
  26044. const getVhsLocalStorage = () => {
  26045. if (!window.localStorage) {
  26046. return null;
  26047. }
  26048. const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  26049. if (!storedObject) {
  26050. return null;
  26051. }
  26052. try {
  26053. return JSON.parse(storedObject);
  26054. } catch (e) {
  26055. // someone may have tampered with the value
  26056. return null;
  26057. }
  26058. };
  26059. const updateVhsLocalStorage = options => {
  26060. if (!window.localStorage) {
  26061. return false;
  26062. }
  26063. let objectToStore = getVhsLocalStorage();
  26064. objectToStore = objectToStore ? merge$1(objectToStore, options) : options;
  26065. try {
  26066. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  26067. } catch (e) {
  26068. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  26069. // storage is set to 0).
  26070. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  26071. // No need to perform any operation.
  26072. return false;
  26073. }
  26074. return objectToStore;
  26075. };
  26076. /**
  26077. * Parses VHS-supported media types from data URIs. See
  26078. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  26079. * for information on data URIs.
  26080. *
  26081. * @param {string} dataUri
  26082. * The data URI
  26083. *
  26084. * @return {string|Object}
  26085. * The parsed object/string, or the original string if no supported media type
  26086. * was found
  26087. */
  26088. const expandDataUri = dataUri => {
  26089. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  26090. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  26091. } // no known case for this data URI, return the string as-is
  26092. return dataUri;
  26093. };
  26094. /**
  26095. * Whether the browser has built-in HLS support.
  26096. */
  26097. Vhs.supportsNativeHls = function () {
  26098. if (!document || !document.createElement) {
  26099. return false;
  26100. }
  26101. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  26102. if (!videojs__default["default"].getTech('Html5').isSupported()) {
  26103. return false;
  26104. } // HLS manifests can go by many mime-types
  26105. const canPlay = [// Apple santioned
  26106. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  26107. 'audio/mpegurl', // Very common
  26108. 'audio/x-mpegurl', // Very common
  26109. 'application/x-mpegurl', // Included for completeness
  26110. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  26111. return canPlay.some(function (canItPlay) {
  26112. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  26113. });
  26114. }();
  26115. Vhs.supportsNativeDash = function () {
  26116. if (!document || !document.createElement || !videojs__default["default"].getTech('Html5').isSupported()) {
  26117. return false;
  26118. }
  26119. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  26120. }();
  26121. Vhs.supportsTypeNatively = type => {
  26122. if (type === 'hls') {
  26123. return Vhs.supportsNativeHls;
  26124. }
  26125. if (type === 'dash') {
  26126. return Vhs.supportsNativeDash;
  26127. }
  26128. return false;
  26129. };
  26130. /**
  26131. * VHS is a source handler, not a tech. Make sure attempts to use it
  26132. * as one do not cause exceptions.
  26133. */
  26134. Vhs.isSupported = function () {
  26135. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  26136. };
  26137. const Component = videojs__default["default"].getComponent('Component');
  26138. /**
  26139. * The Vhs Handler object, where we orchestrate all of the parts
  26140. * of VHS to interact with video.js
  26141. *
  26142. * @class VhsHandler
  26143. * @extends videojs.Component
  26144. * @param {Object} source the soruce object
  26145. * @param {Tech} tech the parent tech object
  26146. * @param {Object} options optional and required options
  26147. */
  26148. class VhsHandler extends Component {
  26149. constructor(source, tech, options) {
  26150. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  26151. // use that over the VHS level `bandwidth` option
  26152. if (typeof options.initialBandwidth === 'number') {
  26153. this.options_.bandwidth = options.initialBandwidth;
  26154. }
  26155. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  26156. // so, get it from Video.js via the `playerId`
  26157. if (tech.options_ && tech.options_.playerId) {
  26158. const _player = videojs__default["default"].getPlayer(tech.options_.playerId);
  26159. this.player_ = _player;
  26160. }
  26161. this.tech_ = tech;
  26162. this.source_ = source;
  26163. this.stats = {};
  26164. this.ignoreNextSeekingEvent_ = false;
  26165. this.setOptions_();
  26166. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  26167. tech.overrideNativeAudioTracks(true);
  26168. tech.overrideNativeVideoTracks(true);
  26169. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  26170. // overriding native VHS only works if audio tracks have been emulated
  26171. // error early if we're misconfigured
  26172. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  26173. } // listen for fullscreenchange events for this player so that we
  26174. // can adjust our quality selection quickly
  26175. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  26176. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  26177. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  26178. this.playlistController_.fastQualityChange_();
  26179. } else {
  26180. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  26181. // than full screen, see if there should be a rendition switch down to preserve
  26182. // bandwidth.
  26183. this.playlistController_.checkABR_();
  26184. }
  26185. });
  26186. this.on(this.tech_, 'seeking', function () {
  26187. if (this.ignoreNextSeekingEvent_) {
  26188. this.ignoreNextSeekingEvent_ = false;
  26189. return;
  26190. }
  26191. this.setCurrentTime(this.tech_.currentTime());
  26192. });
  26193. this.on(this.tech_, 'error', function () {
  26194. // verify that the error was real and we are loaded
  26195. // enough to have pc loaded.
  26196. if (this.tech_.error() && this.playlistController_) {
  26197. this.playlistController_.pauseLoading();
  26198. }
  26199. });
  26200. this.on(this.tech_, 'play', this.play);
  26201. }
  26202. setOptions_() {
  26203. // defaults
  26204. this.options_.withCredentials = this.options_.withCredentials || false;
  26205. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  26206. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  26207. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  26208. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  26209. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  26210. this.options_.customTagParsers = this.options_.customTagParsers || [];
  26211. this.options_.customTagMappers = this.options_.customTagMappers || [];
  26212. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  26213. this.options_.llhls = this.options_.llhls === false ? false : true;
  26214. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  26215. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  26216. this.options_.playlistExclusionDuration = 5 * 60;
  26217. }
  26218. if (typeof this.options_.bandwidth !== 'number') {
  26219. if (this.options_.useBandwidthFromLocalStorage) {
  26220. const storedObject = getVhsLocalStorage();
  26221. if (storedObject && storedObject.bandwidth) {
  26222. this.options_.bandwidth = storedObject.bandwidth;
  26223. this.tech_.trigger({
  26224. type: 'usage',
  26225. name: 'vhs-bandwidth-from-local-storage'
  26226. });
  26227. }
  26228. if (storedObject && storedObject.throughput) {
  26229. this.options_.throughput = storedObject.throughput;
  26230. this.tech_.trigger({
  26231. type: 'usage',
  26232. name: 'vhs-throughput-from-local-storage'
  26233. });
  26234. }
  26235. }
  26236. } // if bandwidth was not set by options or pulled from local storage, start playlist
  26237. // selection at a reasonable bandwidth
  26238. if (typeof this.options_.bandwidth !== 'number') {
  26239. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  26240. } // If the bandwidth number is unchanged from the initial setting
  26241. // then this takes precedence over the enableLowInitialPlaylist option
  26242. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  26243. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  26244. if (typeof this.source_[option] !== 'undefined') {
  26245. this.options_[option] = this.source_[option];
  26246. }
  26247. });
  26248. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  26249. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  26250. }
  26251. /**
  26252. * called when player.src gets called, handle a new source
  26253. *
  26254. * @param {Object} src the source object to handle
  26255. */
  26256. src(src, type) {
  26257. // do nothing if the src is falsey
  26258. if (!src) {
  26259. return;
  26260. }
  26261. this.setOptions_(); // add main playlist controller options
  26262. this.options_.src = expandDataUri(this.source_.src);
  26263. this.options_.tech = this.tech_;
  26264. this.options_.externVhs = Vhs;
  26265. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  26266. this.options_.seekTo = time => {
  26267. this.tech_.setCurrentTime(time);
  26268. };
  26269. this.playlistController_ = new PlaylistController(this.options_);
  26270. const playbackWatcherOptions = merge$1({
  26271. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  26272. }, this.options_, {
  26273. seekable: () => this.seekable(),
  26274. media: () => this.playlistController_.media(),
  26275. playlistController: this.playlistController_
  26276. });
  26277. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  26278. this.playlistController_.on('error', () => {
  26279. const player = videojs__default["default"].players[this.tech_.options_.playerId];
  26280. let error = this.playlistController_.error;
  26281. if (typeof error === 'object' && !error.code) {
  26282. error.code = 3;
  26283. } else if (typeof error === 'string') {
  26284. error = {
  26285. message: error,
  26286. code: 3
  26287. };
  26288. }
  26289. player.error(error);
  26290. });
  26291. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  26292. // compatibility with < v2
  26293. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  26294. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  26295. this.playlists = this.playlistController_.mainPlaylistLoader_;
  26296. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  26297. // controller. Using a custom property for backwards compatibility
  26298. // with < v2
  26299. Object.defineProperties(this, {
  26300. selectPlaylist: {
  26301. get() {
  26302. return this.playlistController_.selectPlaylist;
  26303. },
  26304. set(selectPlaylist) {
  26305. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  26306. }
  26307. },
  26308. throughput: {
  26309. get() {
  26310. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  26311. },
  26312. set(throughput) {
  26313. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  26314. // for the cumulative average
  26315. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  26316. }
  26317. },
  26318. bandwidth: {
  26319. get() {
  26320. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  26321. const networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  26322. const tenMbpsAsBitsPerSecond = 10e6;
  26323. if (this.options_.useNetworkInformationApi && networkInformation) {
  26324. // downlink returns Mbps
  26325. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  26326. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  26327. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  26328. // high quality streams are not filtered out.
  26329. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  26330. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  26331. } else {
  26332. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  26333. }
  26334. }
  26335. return playerBandwidthEst;
  26336. },
  26337. set(bandwidth) {
  26338. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  26339. // `count` is set to zero that current value of `rate` isn't included
  26340. // in the cumulative average
  26341. this.playlistController_.mainSegmentLoader_.throughput = {
  26342. rate: 0,
  26343. count: 0
  26344. };
  26345. }
  26346. },
  26347. /**
  26348. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  26349. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  26350. * the entire process after that - decryption, transmuxing, and appending - provided
  26351. * by `throughput`.
  26352. *
  26353. * Since the two process are serial, the overall system bandwidth is given by:
  26354. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  26355. */
  26356. systemBandwidth: {
  26357. get() {
  26358. const invBandwidth = 1 / (this.bandwidth || 1);
  26359. let invThroughput;
  26360. if (this.throughput > 0) {
  26361. invThroughput = 1 / this.throughput;
  26362. } else {
  26363. invThroughput = 0;
  26364. }
  26365. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  26366. return systemBitrate;
  26367. },
  26368. set() {
  26369. videojs__default["default"].log.error('The "systemBandwidth" property is read-only');
  26370. }
  26371. }
  26372. });
  26373. if (this.options_.bandwidth) {
  26374. this.bandwidth = this.options_.bandwidth;
  26375. }
  26376. if (this.options_.throughput) {
  26377. this.throughput = this.options_.throughput;
  26378. }
  26379. Object.defineProperties(this.stats, {
  26380. bandwidth: {
  26381. get: () => this.bandwidth || 0,
  26382. enumerable: true
  26383. },
  26384. mediaRequests: {
  26385. get: () => this.playlistController_.mediaRequests_() || 0,
  26386. enumerable: true
  26387. },
  26388. mediaRequestsAborted: {
  26389. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  26390. enumerable: true
  26391. },
  26392. mediaRequestsTimedout: {
  26393. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  26394. enumerable: true
  26395. },
  26396. mediaRequestsErrored: {
  26397. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  26398. enumerable: true
  26399. },
  26400. mediaTransferDuration: {
  26401. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  26402. enumerable: true
  26403. },
  26404. mediaBytesTransferred: {
  26405. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  26406. enumerable: true
  26407. },
  26408. mediaSecondsLoaded: {
  26409. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  26410. enumerable: true
  26411. },
  26412. mediaAppends: {
  26413. get: () => this.playlistController_.mediaAppends_() || 0,
  26414. enumerable: true
  26415. },
  26416. mainAppendsToLoadedData: {
  26417. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  26418. enumerable: true
  26419. },
  26420. audioAppendsToLoadedData: {
  26421. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  26422. enumerable: true
  26423. },
  26424. appendsToLoadedData: {
  26425. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  26426. enumerable: true
  26427. },
  26428. timeToLoadedData: {
  26429. get: () => this.playlistController_.timeToLoadedData_() || 0,
  26430. enumerable: true
  26431. },
  26432. buffered: {
  26433. get: () => timeRangesToArray(this.tech_.buffered()),
  26434. enumerable: true
  26435. },
  26436. currentTime: {
  26437. get: () => this.tech_.currentTime(),
  26438. enumerable: true
  26439. },
  26440. currentSource: {
  26441. get: () => this.tech_.currentSource_,
  26442. enumerable: true
  26443. },
  26444. currentTech: {
  26445. get: () => this.tech_.name_,
  26446. enumerable: true
  26447. },
  26448. duration: {
  26449. get: () => this.tech_.duration(),
  26450. enumerable: true
  26451. },
  26452. main: {
  26453. get: () => this.playlists.main,
  26454. enumerable: true
  26455. },
  26456. playerDimensions: {
  26457. get: () => this.tech_.currentDimensions(),
  26458. enumerable: true
  26459. },
  26460. seekable: {
  26461. get: () => timeRangesToArray(this.tech_.seekable()),
  26462. enumerable: true
  26463. },
  26464. timestamp: {
  26465. get: () => Date.now(),
  26466. enumerable: true
  26467. },
  26468. videoPlaybackQuality: {
  26469. get: () => this.tech_.getVideoPlaybackQuality(),
  26470. enumerable: true
  26471. }
  26472. });
  26473. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  26474. this.tech_.on('bandwidthupdate', () => {
  26475. if (this.options_.useBandwidthFromLocalStorage) {
  26476. updateVhsLocalStorage({
  26477. bandwidth: this.bandwidth,
  26478. throughput: Math.round(this.throughput)
  26479. });
  26480. }
  26481. });
  26482. this.playlistController_.on('selectedinitialmedia', () => {
  26483. // Add the manual rendition mix-in to VhsHandler
  26484. renditionSelectionMixin(this);
  26485. });
  26486. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  26487. this.setupEme_();
  26488. }); // the bandwidth of the primary segment loader is our best
  26489. // estimate of overall bandwidth
  26490. this.on(this.playlistController_, 'progress', function () {
  26491. this.tech_.trigger('progress');
  26492. }); // In the live case, we need to ignore the very first `seeking` event since
  26493. // that will be the result of the seek-to-live behavior
  26494. this.on(this.playlistController_, 'firstplay', function () {
  26495. this.ignoreNextSeekingEvent_ = true;
  26496. });
  26497. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  26498. // this can occur if someone sets the src in player.ready(), for instance
  26499. if (!this.tech_.el()) {
  26500. return;
  26501. }
  26502. this.mediaSourceUrl_ = window.URL.createObjectURL(this.playlistController_.mediaSource);
  26503. this.tech_.src(this.mediaSourceUrl_);
  26504. }
  26505. createKeySessions_() {
  26506. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  26507. this.logger_('waiting for EME key session creation');
  26508. waitForKeySessionCreation({
  26509. player: this.player_,
  26510. sourceKeySystems: this.source_.keySystems,
  26511. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  26512. mainPlaylists: this.playlists.main.playlists
  26513. }).then(() => {
  26514. this.logger_('created EME key session');
  26515. this.playlistController_.sourceUpdater_.initializedEme();
  26516. }).catch(err => {
  26517. this.logger_('error while creating EME key session', err);
  26518. this.player_.error({
  26519. message: 'Failed to initialize media keys for EME',
  26520. code: 3
  26521. });
  26522. });
  26523. }
  26524. handleWaitingForKey_() {
  26525. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  26526. // the key is in the manifest. While this should've happened on initial source load, it
  26527. // may happen again in live streams where the keys change, and the manifest info
  26528. // reflects the update.
  26529. //
  26530. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  26531. // already requested keys for, we don't have to worry about this generating extraneous
  26532. // requests.
  26533. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  26534. this.createKeySessions_();
  26535. }
  26536. /**
  26537. * If necessary and EME is available, sets up EME options and waits for key session
  26538. * creation.
  26539. *
  26540. * This function also updates the source updater so taht it can be used, as for some
  26541. * browsers, EME must be configured before content is appended (if appending unencrypted
  26542. * content before encrypted content).
  26543. */
  26544. setupEme_() {
  26545. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  26546. const didSetupEmeOptions = setupEmeOptions({
  26547. player: this.player_,
  26548. sourceKeySystems: this.source_.keySystems,
  26549. media: this.playlists.media(),
  26550. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  26551. });
  26552. this.player_.tech_.on('keystatuschange', e => {
  26553. if (e.status !== 'output-restricted') {
  26554. return;
  26555. }
  26556. const mainPlaylist = this.playlistController_.main();
  26557. if (!mainPlaylist || !mainPlaylist.playlists) {
  26558. return;
  26559. }
  26560. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  26561. mainPlaylist.playlists.forEach(playlist => {
  26562. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  26563. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  26564. playlist.excludeUntil = Infinity;
  26565. excludedHDPlaylists.push(playlist);
  26566. }
  26567. }
  26568. });
  26569. if (excludedHDPlaylists.length) {
  26570. videojs__default["default"].log.warn('DRM keystatus changed to "output-restricted." Removing the following HD playlists ' + 'that will most likely fail to play and clearing the buffer. ' + 'This may be due to HDCP restrictions on the stream and the capabilities of the current device.', ...excludedHDPlaylists); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  26571. this.playlistController_.fastQualityChange_();
  26572. }
  26573. });
  26574. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  26575. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  26576. // promises.
  26577. if (videojs__default["default"].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  26578. // If EME options were not set up, we've done all we could to initialize EME.
  26579. this.playlistController_.sourceUpdater_.initializedEme();
  26580. return;
  26581. }
  26582. this.createKeySessions_();
  26583. }
  26584. /**
  26585. * Initializes the quality levels and sets listeners to update them.
  26586. *
  26587. * @method setupQualityLevels_
  26588. * @private
  26589. */
  26590. setupQualityLevels_() {
  26591. const player = videojs__default["default"].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  26592. // or qualityLevels_ listeners have already been setup, do nothing.
  26593. if (!player || !player.qualityLevels || this.qualityLevels_) {
  26594. return;
  26595. }
  26596. this.qualityLevels_ = player.qualityLevels();
  26597. this.playlistController_.on('selectedinitialmedia', () => {
  26598. handleVhsLoadedMetadata(this.qualityLevels_, this);
  26599. });
  26600. this.playlists.on('mediachange', () => {
  26601. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  26602. });
  26603. }
  26604. /**
  26605. * return the version
  26606. */
  26607. static version() {
  26608. return {
  26609. '@videojs/http-streaming': version$4,
  26610. 'mux.js': version$3,
  26611. 'mpd-parser': version$2,
  26612. 'm3u8-parser': version$1,
  26613. 'aes-decrypter': version
  26614. };
  26615. }
  26616. /**
  26617. * return the version
  26618. */
  26619. version() {
  26620. return this.constructor.version();
  26621. }
  26622. canChangeType() {
  26623. return SourceUpdater.canChangeType();
  26624. }
  26625. /**
  26626. * Begin playing the video.
  26627. */
  26628. play() {
  26629. this.playlistController_.play();
  26630. }
  26631. /**
  26632. * a wrapper around the function in PlaylistController
  26633. */
  26634. setCurrentTime(currentTime) {
  26635. this.playlistController_.setCurrentTime(currentTime);
  26636. }
  26637. /**
  26638. * a wrapper around the function in PlaylistController
  26639. */
  26640. duration() {
  26641. return this.playlistController_.duration();
  26642. }
  26643. /**
  26644. * a wrapper around the function in PlaylistController
  26645. */
  26646. seekable() {
  26647. return this.playlistController_.seekable();
  26648. }
  26649. /**
  26650. * Abort all outstanding work and cleanup.
  26651. */
  26652. dispose() {
  26653. if (this.playbackWatcher_) {
  26654. this.playbackWatcher_.dispose();
  26655. }
  26656. if (this.playlistController_) {
  26657. this.playlistController_.dispose();
  26658. }
  26659. if (this.qualityLevels_) {
  26660. this.qualityLevels_.dispose();
  26661. }
  26662. if (this.tech_ && this.tech_.vhs) {
  26663. delete this.tech_.vhs;
  26664. }
  26665. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  26666. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  26667. this.mediaSourceUrl_ = null;
  26668. }
  26669. if (this.tech_) {
  26670. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  26671. }
  26672. super.dispose();
  26673. }
  26674. convertToProgramTime(time, callback) {
  26675. return getProgramTime({
  26676. playlist: this.playlistController_.media(),
  26677. time,
  26678. callback
  26679. });
  26680. } // the player must be playing before calling this
  26681. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  26682. return seekToProgramTime({
  26683. programTime,
  26684. playlist: this.playlistController_.media(),
  26685. retryCount,
  26686. pauseAfterSeek,
  26687. seekTo: this.options_.seekTo,
  26688. tech: this.options_.tech,
  26689. callback
  26690. });
  26691. }
  26692. }
  26693. /**
  26694. * The Source Handler object, which informs video.js what additional
  26695. * MIME types are supported and sets up playback. It is registered
  26696. * automatically to the appropriate tech based on the capabilities of
  26697. * the browser it is running in. It is not necessary to use or modify
  26698. * this object in normal usage.
  26699. */
  26700. const VhsSourceHandler = {
  26701. name: 'videojs-http-streaming',
  26702. VERSION: version$4,
  26703. canHandleSource(srcObj, options = {}) {
  26704. const localOptions = merge$1(videojs__default["default"].options, options);
  26705. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  26706. },
  26707. handleSource(source, tech, options = {}) {
  26708. const localOptions = merge$1(videojs__default["default"].options, options);
  26709. tech.vhs = new VhsHandler(source, tech, localOptions);
  26710. tech.vhs.xhr = xhrFactory();
  26711. tech.vhs.src(source.src, source.type);
  26712. return tech.vhs;
  26713. },
  26714. canPlayType(type, options) {
  26715. const simpleType = simpleTypeFromSourceType(type);
  26716. if (!simpleType) {
  26717. return '';
  26718. }
  26719. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  26720. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  26721. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  26722. return canUseMsePlayback ? 'maybe' : '';
  26723. },
  26724. getOverrideNative(options = {}) {
  26725. const {
  26726. vhs = {}
  26727. } = options;
  26728. const defaultOverrideNative = !(videojs__default["default"].browser.IS_ANY_SAFARI || videojs__default["default"].browser.IS_IOS);
  26729. const {
  26730. overrideNative = defaultOverrideNative
  26731. } = vhs;
  26732. return overrideNative;
  26733. }
  26734. };
  26735. /**
  26736. * Check to see if the native MediaSource object exists and supports
  26737. * an MP4 container with both H.264 video and AAC-LC audio.
  26738. *
  26739. * @return {boolean} if native media sources are supported
  26740. */
  26741. const supportsNativeMediaSources = () => {
  26742. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  26743. }; // register source handlers with the appropriate techs
  26744. if (supportsNativeMediaSources()) {
  26745. videojs__default["default"].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  26746. }
  26747. videojs__default["default"].VhsHandler = VhsHandler;
  26748. videojs__default["default"].VhsSourceHandler = VhsSourceHandler;
  26749. videojs__default["default"].Vhs = Vhs;
  26750. if (!videojs__default["default"].use) {
  26751. videojs__default["default"].registerComponent('Vhs', Vhs);
  26752. }
  26753. videojs__default["default"].options.vhs = videojs__default["default"].options.vhs || {};
  26754. if (!videojs__default["default"].getPlugin || !videojs__default["default"].getPlugin('reloadSourceOnError')) {
  26755. videojs__default["default"].registerPlugin('reloadSourceOnError', reloadSourceOnError);
  26756. }
  26757. exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
  26758. exports.Vhs = Vhs;
  26759. exports.VhsHandler = VhsHandler;
  26760. exports.VhsSourceHandler = VhsSourceHandler;
  26761. exports.emeKeySystems = emeKeySystems;
  26762. exports.expandDataUri = expandDataUri;
  26763. exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
  26764. exports.setupEmeOptions = setupEmeOptions;
  26765. exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
  26766. exports.waitForKeySessionCreation = waitForKeySessionCreation;
  26767. Object.defineProperty(exports, '__esModule', { value: true });
  26768. }));