videojs-http-streaming.es.js 838 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408
  1. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  2. import document from 'global/document';
  3. import window$1 from 'global/window';
  4. import _resolveUrl from '@videojs/vhs-utils/es/resolve-url.js';
  5. import videojs from 'video.js';
  6. import _extends from '@babel/runtime/helpers/extends';
  7. import { Parser } from 'm3u8-parser';
  8. import { isAudioCodec, translateLegacyCodec, codecsFromDefault, parseCodecs, getMimeForCodec, DEFAULT_VIDEO_CODEC, DEFAULT_AUDIO_CODEC, browserSupportsCodec, muxerSupportsCodec } from '@videojs/vhs-utils/es/codecs.js';
  9. import { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
  10. export { simpleTypeFromSourceType } from '@videojs/vhs-utils/es/media-types.js';
  11. import { isArrayBufferView, concatTypedArrays, stringToBytes, toUint8 } from '@videojs/vhs-utils/es/byte-helpers';
  12. import { generateSidxKey, parseUTCTiming, parse, addSidxSegmentsToPlaylist } from 'mpd-parser';
  13. import parseSidx from 'mux.js/lib/tools/parse-sidx';
  14. import { getId3Offset } from '@videojs/vhs-utils/es/id3-helpers';
  15. import { detectContainerForBytes, isLikelyFmp4MediaSegment } from '@videojs/vhs-utils/es/containers';
  16. import { ONE_SECOND_IN_TS } from 'mux.js/lib/utils/clock';
  17. /**
  18. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  19. */
  20. const resolveUrl = _resolveUrl;
  21. /**
  22. * If the xhr request was redirected, return the responseURL, otherwise,
  23. * return the original url.
  24. *
  25. * @api private
  26. *
  27. * @param {string} url - an url being requested
  28. * @param {XMLHttpRequest} req - xhr request result
  29. *
  30. * @return {string}
  31. */
  32. const resolveManifestRedirect = (url, req) => {
  33. // To understand how the responseURL below is set and generated:
  34. // - https://fetch.spec.whatwg.org/#concept-response-url
  35. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  36. if (req && req.responseURL && url !== req.responseURL) {
  37. return req.responseURL;
  38. }
  39. return url;
  40. };
  41. const logger = source => {
  42. if (videojs.log.debug) {
  43. return videojs.log.debug.bind(videojs, 'VHS:', `${source} >`);
  44. }
  45. return function () {};
  46. };
  47. /**
  48. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  49. */
  50. /**
  51. * Delegates to videojs.obj.merge (Video.js 8) or
  52. * videojs.mergeOptions (Video.js 7).
  53. */
  54. function merge(...args) {
  55. const context = videojs.obj || videojs;
  56. const fn = context.merge || context.mergeOptions;
  57. return fn.apply(context, args);
  58. }
  59. /**
  60. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  61. * videojs.createTimeRanges (Video.js 7).
  62. */
  63. function createTimeRanges(...args) {
  64. const context = videojs.time || videojs;
  65. const fn = context.createTimeRanges || context.createTimeRanges;
  66. return fn.apply(context, args);
  67. }
  68. /**
  69. * ranges
  70. *
  71. * Utilities for working with TimeRanges.
  72. *
  73. */
  74. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  75. // can be misleading because of precision differences or when the current media has poorly
  76. // aligned audio and video, which can cause values to be slightly off from what you would
  77. // expect. This value is what we consider to be safe to use in such comparisons to account
  78. // for these scenarios.
  79. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  80. const filterRanges = function (timeRanges, predicate) {
  81. const results = [];
  82. let i;
  83. if (timeRanges && timeRanges.length) {
  84. // Search for ranges that match the predicate
  85. for (i = 0; i < timeRanges.length; i++) {
  86. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  87. results.push([timeRanges.start(i), timeRanges.end(i)]);
  88. }
  89. }
  90. }
  91. return createTimeRanges(results);
  92. };
  93. /**
  94. * Attempts to find the buffered TimeRange that contains the specified
  95. * time.
  96. *
  97. * @param {TimeRanges} buffered - the TimeRanges object to query
  98. * @param {number} time - the time to filter on.
  99. * @return {TimeRanges} a new TimeRanges object
  100. */
  101. const findRange = function (buffered, time) {
  102. return filterRanges(buffered, function (start, end) {
  103. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  104. });
  105. };
  106. /**
  107. * Returns the TimeRanges that begin later than the specified time.
  108. *
  109. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  110. * @param {number} time - the time to filter on.
  111. * @return {TimeRanges} a new TimeRanges object.
  112. */
  113. const findNextRange = function (timeRanges, time) {
  114. return filterRanges(timeRanges, function (start) {
  115. return start - TIME_FUDGE_FACTOR >= time;
  116. });
  117. };
  118. /**
  119. * Returns gaps within a list of TimeRanges
  120. *
  121. * @param {TimeRanges} buffered - the TimeRanges object
  122. * @return {TimeRanges} a TimeRanges object of gaps
  123. */
  124. const findGaps = function (buffered) {
  125. if (buffered.length < 2) {
  126. return createTimeRanges();
  127. }
  128. const ranges = [];
  129. for (let i = 1; i < buffered.length; i++) {
  130. const start = buffered.end(i - 1);
  131. const end = buffered.start(i);
  132. ranges.push([start, end]);
  133. }
  134. return createTimeRanges(ranges);
  135. };
  136. /**
  137. * Calculate the intersection of two TimeRanges
  138. *
  139. * @param {TimeRanges} bufferA
  140. * @param {TimeRanges} bufferB
  141. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  142. */
  143. const bufferIntersection = function (bufferA, bufferB) {
  144. let start = null;
  145. let end = null;
  146. let arity = 0;
  147. const extents = [];
  148. const ranges = [];
  149. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  150. return createTimeRanges();
  151. } // Handle the case where we have both buffers and create an
  152. // intersection of the two
  153. let count = bufferA.length; // A) Gather up all start and end times
  154. while (count--) {
  155. extents.push({
  156. time: bufferA.start(count),
  157. type: 'start'
  158. });
  159. extents.push({
  160. time: bufferA.end(count),
  161. type: 'end'
  162. });
  163. }
  164. count = bufferB.length;
  165. while (count--) {
  166. extents.push({
  167. time: bufferB.start(count),
  168. type: 'start'
  169. });
  170. extents.push({
  171. time: bufferB.end(count),
  172. type: 'end'
  173. });
  174. } // B) Sort them by time
  175. extents.sort(function (a, b) {
  176. return a.time - b.time;
  177. }); // C) Go along one by one incrementing arity for start and decrementing
  178. // arity for ends
  179. for (count = 0; count < extents.length; count++) {
  180. if (extents[count].type === 'start') {
  181. arity++; // D) If arity is ever incremented to 2 we are entering an
  182. // overlapping range
  183. if (arity === 2) {
  184. start = extents[count].time;
  185. }
  186. } else if (extents[count].type === 'end') {
  187. arity--; // E) If arity is ever decremented to 1 we leaving an
  188. // overlapping range
  189. if (arity === 1) {
  190. end = extents[count].time;
  191. }
  192. } // F) Record overlapping ranges
  193. if (start !== null && end !== null) {
  194. ranges.push([start, end]);
  195. start = null;
  196. end = null;
  197. }
  198. }
  199. return createTimeRanges(ranges);
  200. };
  201. /**
  202. * Gets a human readable string for a TimeRange
  203. *
  204. * @param {TimeRange} range
  205. * @return {string} a human readable string
  206. */
  207. const printableRange = range => {
  208. const strArr = [];
  209. if (!range || !range.length) {
  210. return '';
  211. }
  212. for (let i = 0; i < range.length; i++) {
  213. strArr.push(range.start(i) + ' => ' + range.end(i));
  214. }
  215. return strArr.join(', ');
  216. };
  217. /**
  218. * Calculates the amount of time left in seconds until the player hits the end of the
  219. * buffer and causes a rebuffer
  220. *
  221. * @param {TimeRange} buffered
  222. * The state of the buffer
  223. * @param {Numnber} currentTime
  224. * The current time of the player
  225. * @param {number} playbackRate
  226. * The current playback rate of the player. Defaults to 1.
  227. * @return {number}
  228. * Time until the player has to start rebuffering in seconds.
  229. * @function timeUntilRebuffer
  230. */
  231. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  232. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  233. return (bufferedEnd - currentTime) / playbackRate;
  234. };
  235. /**
  236. * Converts a TimeRanges object into an array representation
  237. *
  238. * @param {TimeRanges} timeRanges
  239. * @return {Array}
  240. */
  241. const timeRangesToArray = timeRanges => {
  242. const timeRangesList = [];
  243. for (let i = 0; i < timeRanges.length; i++) {
  244. timeRangesList.push({
  245. start: timeRanges.start(i),
  246. end: timeRanges.end(i)
  247. });
  248. }
  249. return timeRangesList;
  250. };
  251. /**
  252. * Determines if two time range objects are different.
  253. *
  254. * @param {TimeRange} a
  255. * the first time range object to check
  256. *
  257. * @param {TimeRange} b
  258. * the second time range object to check
  259. *
  260. * @return {Boolean}
  261. * Whether the time range objects differ
  262. */
  263. const isRangeDifferent = function (a, b) {
  264. // same object
  265. if (a === b) {
  266. return false;
  267. } // one or the other is undefined
  268. if (!a && b || !b && a) {
  269. return true;
  270. } // length is different
  271. if (a.length !== b.length) {
  272. return true;
  273. } // see if any start/end pair is different
  274. for (let i = 0; i < a.length; i++) {
  275. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  276. return true;
  277. }
  278. } // if the length and every pair is the same
  279. // this is the same time range
  280. return false;
  281. };
  282. const lastBufferedEnd = function (a) {
  283. if (!a || !a.length || !a.end) {
  284. return;
  285. }
  286. return a.end(a.length - 1);
  287. };
  288. /**
  289. * A utility function to add up the amount of time in a timeRange
  290. * after a specified startTime.
  291. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  292. * would return 40 as there are 40s seconds after 0 in the timeRange
  293. *
  294. * @param {TimeRange} range
  295. * The range to check against
  296. * @param {number} startTime
  297. * The time in the time range that you should start counting from
  298. *
  299. * @return {number}
  300. * The number of seconds in the buffer passed the specified time.
  301. */
  302. const timeAheadOf = function (range, startTime) {
  303. let time = 0;
  304. if (!range || !range.length) {
  305. return time;
  306. }
  307. for (let i = 0; i < range.length; i++) {
  308. const start = range.start(i);
  309. const end = range.end(i); // startTime is after this range entirely
  310. if (startTime > end) {
  311. continue;
  312. } // startTime is within this range
  313. if (startTime > start && startTime <= end) {
  314. time += end - startTime;
  315. continue;
  316. } // startTime is before this range.
  317. time += end - start;
  318. }
  319. return time;
  320. };
  321. /**
  322. * @file playlist.js
  323. *
  324. * Playlist related utilities.
  325. */
  326. /**
  327. * Get the duration of a segment, with special cases for
  328. * llhls segments that do not have a duration yet.
  329. *
  330. * @param {Object} playlist
  331. * the playlist that the segment belongs to.
  332. * @param {Object} segment
  333. * the segment to get a duration for.
  334. *
  335. * @return {number}
  336. * the segment duration
  337. */
  338. const segmentDurationWithParts = (playlist, segment) => {
  339. // if this isn't a preload segment
  340. // then we will have a segment duration that is accurate.
  341. if (!segment.preload) {
  342. return segment.duration;
  343. } // otherwise we have to add up parts and preload hints
  344. // to get an up to date duration.
  345. let result = 0;
  346. (segment.parts || []).forEach(function (p) {
  347. result += p.duration;
  348. }); // for preload hints we have to use partTargetDuration
  349. // as they won't even have a duration yet.
  350. (segment.preloadHints || []).forEach(function (p) {
  351. if (p.type === 'PART') {
  352. result += playlist.partTargetDuration;
  353. }
  354. });
  355. return result;
  356. };
  357. /**
  358. * A function to get a combined list of parts and segments with durations
  359. * and indexes.
  360. *
  361. * @param {Playlist} playlist the playlist to get the list for.
  362. *
  363. * @return {Array} The part/segment list.
  364. */
  365. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  366. if (segment.parts) {
  367. segment.parts.forEach(function (part, pi) {
  368. acc.push({
  369. duration: part.duration,
  370. segmentIndex: si,
  371. partIndex: pi,
  372. part,
  373. segment
  374. });
  375. });
  376. } else {
  377. acc.push({
  378. duration: segment.duration,
  379. segmentIndex: si,
  380. partIndex: null,
  381. segment,
  382. part: null
  383. });
  384. }
  385. return acc;
  386. }, []);
  387. const getLastParts = media => {
  388. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  389. return lastSegment && lastSegment.parts || [];
  390. };
  391. const getKnownPartCount = ({
  392. preloadSegment
  393. }) => {
  394. if (!preloadSegment) {
  395. return;
  396. }
  397. const {
  398. parts,
  399. preloadHints
  400. } = preloadSegment;
  401. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  402. partCount += parts && parts.length ? parts.length : 0;
  403. return partCount;
  404. };
  405. /**
  406. * Get the number of seconds to delay from the end of a
  407. * live playlist.
  408. *
  409. * @param {Playlist} main the main playlist
  410. * @param {Playlist} media the media playlist
  411. * @return {number} the hold back in seconds.
  412. */
  413. const liveEdgeDelay = (main, media) => {
  414. if (media.endList) {
  415. return 0;
  416. } // dash suggestedPresentationDelay trumps everything
  417. if (main && main.suggestedPresentationDelay) {
  418. return main.suggestedPresentationDelay;
  419. }
  420. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  421. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  422. return media.serverControl.partHoldBack;
  423. } else if (hasParts && media.partTargetDuration) {
  424. return media.partTargetDuration * 3; // finally look for full segment delays
  425. } else if (media.serverControl && media.serverControl.holdBack) {
  426. return media.serverControl.holdBack;
  427. } else if (media.targetDuration) {
  428. return media.targetDuration * 3;
  429. }
  430. return 0;
  431. };
  432. /**
  433. * walk backward until we find a duration we can use
  434. * or return a failure
  435. *
  436. * @param {Playlist} playlist the playlist to walk through
  437. * @param {Number} endSequence the mediaSequence to stop walking on
  438. */
  439. const backwardDuration = function (playlist, endSequence) {
  440. let result = 0;
  441. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  442. // the interval, use it
  443. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  444. // information that is earlier than endSequence
  445. if (segment) {
  446. if (typeof segment.start !== 'undefined') {
  447. return {
  448. result: segment.start,
  449. precise: true
  450. };
  451. }
  452. if (typeof segment.end !== 'undefined') {
  453. return {
  454. result: segment.end - segment.duration,
  455. precise: true
  456. };
  457. }
  458. }
  459. while (i--) {
  460. segment = playlist.segments[i];
  461. if (typeof segment.end !== 'undefined') {
  462. return {
  463. result: result + segment.end,
  464. precise: true
  465. };
  466. }
  467. result += segmentDurationWithParts(playlist, segment);
  468. if (typeof segment.start !== 'undefined') {
  469. return {
  470. result: result + segment.start,
  471. precise: true
  472. };
  473. }
  474. }
  475. return {
  476. result,
  477. precise: false
  478. };
  479. };
  480. /**
  481. * walk forward until we find a duration we can use
  482. * or return a failure
  483. *
  484. * @param {Playlist} playlist the playlist to walk through
  485. * @param {number} endSequence the mediaSequence to stop walking on
  486. */
  487. const forwardDuration = function (playlist, endSequence) {
  488. let result = 0;
  489. let segment;
  490. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  491. // information
  492. for (; i < playlist.segments.length; i++) {
  493. segment = playlist.segments[i];
  494. if (typeof segment.start !== 'undefined') {
  495. return {
  496. result: segment.start - result,
  497. precise: true
  498. };
  499. }
  500. result += segmentDurationWithParts(playlist, segment);
  501. if (typeof segment.end !== 'undefined') {
  502. return {
  503. result: segment.end - result,
  504. precise: true
  505. };
  506. }
  507. } // indicate we didn't find a useful duration estimate
  508. return {
  509. result: -1,
  510. precise: false
  511. };
  512. };
  513. /**
  514. * Calculate the media duration from the segments associated with a
  515. * playlist. The duration of a subinterval of the available segments
  516. * may be calculated by specifying an end index.
  517. *
  518. * @param {Object} playlist a media playlist object
  519. * @param {number=} endSequence an exclusive upper boundary
  520. * for the playlist. Defaults to playlist length.
  521. * @param {number} expired the amount of time that has dropped
  522. * off the front of the playlist in a live scenario
  523. * @return {number} the duration between the first available segment
  524. * and end index.
  525. */
  526. const intervalDuration = function (playlist, endSequence, expired) {
  527. if (typeof endSequence === 'undefined') {
  528. endSequence = playlist.mediaSequence + playlist.segments.length;
  529. }
  530. if (endSequence < playlist.mediaSequence) {
  531. return 0;
  532. } // do a backward walk to estimate the duration
  533. const backward = backwardDuration(playlist, endSequence);
  534. if (backward.precise) {
  535. // if we were able to base our duration estimate on timing
  536. // information provided directly from the Media Source, return
  537. // it
  538. return backward.result;
  539. } // walk forward to see if a precise duration estimate can be made
  540. // that way
  541. const forward = forwardDuration(playlist, endSequence);
  542. if (forward.precise) {
  543. // we found a segment that has been buffered and so it's
  544. // position is known precisely
  545. return forward.result;
  546. } // return the less-precise, playlist-based duration estimate
  547. return backward.result + expired;
  548. };
  549. /**
  550. * Calculates the duration of a playlist. If a start and end index
  551. * are specified, the duration will be for the subset of the media
  552. * timeline between those two indices. The total duration for live
  553. * playlists is always Infinity.
  554. *
  555. * @param {Object} playlist a media playlist object
  556. * @param {number=} endSequence an exclusive upper
  557. * boundary for the playlist. Defaults to the playlist media
  558. * sequence number plus its length.
  559. * @param {number=} expired the amount of time that has
  560. * dropped off the front of the playlist in a live scenario
  561. * @return {number} the duration between the start index and end
  562. * index.
  563. */
  564. const duration = function (playlist, endSequence, expired) {
  565. if (!playlist) {
  566. return 0;
  567. }
  568. if (typeof expired !== 'number') {
  569. expired = 0;
  570. } // if a slice of the total duration is not requested, use
  571. // playlist-level duration indicators when they're present
  572. if (typeof endSequence === 'undefined') {
  573. // if present, use the duration specified in the playlist
  574. if (playlist.totalDuration) {
  575. return playlist.totalDuration;
  576. } // duration should be Infinity for live playlists
  577. if (!playlist.endList) {
  578. return window$1.Infinity;
  579. }
  580. } // calculate the total duration based on the segment durations
  581. return intervalDuration(playlist, endSequence, expired);
  582. };
  583. /**
  584. * Calculate the time between two indexes in the current playlist
  585. * neight the start- nor the end-index need to be within the current
  586. * playlist in which case, the targetDuration of the playlist is used
  587. * to approximate the durations of the segments
  588. *
  589. * @param {Array} options.durationList list to iterate over for durations.
  590. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  591. * @param {number} options.startIndex partsAndSegments index to start
  592. * @param {number} options.endIndex partsAndSegments index to end.
  593. * @return {number} the number of seconds between startIndex and endIndex
  594. */
  595. const sumDurations = function ({
  596. defaultDuration,
  597. durationList,
  598. startIndex,
  599. endIndex
  600. }) {
  601. let durations = 0;
  602. if (startIndex > endIndex) {
  603. [startIndex, endIndex] = [endIndex, startIndex];
  604. }
  605. if (startIndex < 0) {
  606. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  607. durations += defaultDuration;
  608. }
  609. startIndex = 0;
  610. }
  611. for (let i = startIndex; i < endIndex; i++) {
  612. durations += durationList[i].duration;
  613. }
  614. return durations;
  615. };
  616. /**
  617. * Calculates the playlist end time
  618. *
  619. * @param {Object} playlist a media playlist object
  620. * @param {number=} expired the amount of time that has
  621. * dropped off the front of the playlist in a live scenario
  622. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  623. * playlist end calculation should consider the safe live end
  624. * (truncate the playlist end by three segments). This is normally
  625. * used for calculating the end of the playlist's seekable range.
  626. * This takes into account the value of liveEdgePadding.
  627. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  628. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  629. * If this is provided, it is used in the safe live end calculation.
  630. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  631. * Corresponds to suggestedPresentationDelay in DASH manifests.
  632. * @return {number} the end time of playlist
  633. * @function playlistEnd
  634. */
  635. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  636. if (!playlist || !playlist.segments) {
  637. return null;
  638. }
  639. if (playlist.endList) {
  640. return duration(playlist);
  641. }
  642. if (expired === null) {
  643. return null;
  644. }
  645. expired = expired || 0;
  646. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  647. if (useSafeLiveEnd) {
  648. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  649. lastSegmentEndTime -= liveEdgePadding;
  650. } // don't return a time less than zero
  651. return Math.max(0, lastSegmentEndTime);
  652. };
  653. /**
  654. * Calculates the interval of time that is currently seekable in a
  655. * playlist. The returned time ranges are relative to the earliest
  656. * moment in the specified playlist that is still available. A full
  657. * seekable implementation for live streams would need to offset
  658. * these values by the duration of content that has expired from the
  659. * stream.
  660. *
  661. * @param {Object} playlist a media playlist object
  662. * dropped off the front of the playlist in a live scenario
  663. * @param {number=} expired the amount of time that has
  664. * dropped off the front of the playlist in a live scenario
  665. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  666. * Corresponds to suggestedPresentationDelay in DASH manifests.
  667. * @return {TimeRanges} the periods of time that are valid targets
  668. * for seeking
  669. */
  670. const seekable = function (playlist, expired, liveEdgePadding) {
  671. const useSafeLiveEnd = true;
  672. const seekableStart = expired || 0;
  673. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  674. if (seekableEnd === null) {
  675. return createTimeRanges();
  676. }
  677. return createTimeRanges(seekableStart, seekableEnd);
  678. };
  679. /**
  680. * Determine the index and estimated starting time of the segment that
  681. * contains a specified playback position in a media playlist.
  682. *
  683. * @param {Object} options.playlist the media playlist to query
  684. * @param {number} options.currentTime The number of seconds since the earliest
  685. * possible position to determine the containing segment for
  686. * @param {number} options.startTime the time when the segment/part starts
  687. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  688. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  689. *
  690. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  691. */
  692. const getMediaInfoForTime = function ({
  693. playlist,
  694. currentTime,
  695. startingSegmentIndex,
  696. startingPartIndex,
  697. startTime,
  698. exactManifestTimings
  699. }) {
  700. let time = currentTime - startTime;
  701. const partsAndSegments = getPartsAndSegments(playlist);
  702. let startIndex = 0;
  703. for (let i = 0; i < partsAndSegments.length; i++) {
  704. const partAndSegment = partsAndSegments[i];
  705. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  706. continue;
  707. } // skip this if part index does not match.
  708. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  709. continue;
  710. }
  711. startIndex = i;
  712. break;
  713. }
  714. if (time < 0) {
  715. // Walk backward from startIndex in the playlist, adding durations
  716. // until we find a segment that contains `time` and return it
  717. if (startIndex > 0) {
  718. for (let i = startIndex - 1; i >= 0; i--) {
  719. const partAndSegment = partsAndSegments[i];
  720. time += partAndSegment.duration;
  721. if (exactManifestTimings) {
  722. if (time < 0) {
  723. continue;
  724. }
  725. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  726. continue;
  727. }
  728. return {
  729. partIndex: partAndSegment.partIndex,
  730. segmentIndex: partAndSegment.segmentIndex,
  731. startTime: startTime - sumDurations({
  732. defaultDuration: playlist.targetDuration,
  733. durationList: partsAndSegments,
  734. startIndex,
  735. endIndex: i
  736. })
  737. };
  738. }
  739. } // We were unable to find a good segment within the playlist
  740. // so select the first segment
  741. return {
  742. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  743. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  744. startTime: currentTime
  745. };
  746. } // When startIndex is negative, we first walk forward to first segment
  747. // adding target durations. If we "run out of time" before getting to
  748. // the first segment, return the first segment
  749. if (startIndex < 0) {
  750. for (let i = startIndex; i < 0; i++) {
  751. time -= playlist.targetDuration;
  752. if (time < 0) {
  753. return {
  754. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  755. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  756. startTime: currentTime
  757. };
  758. }
  759. }
  760. startIndex = 0;
  761. } // Walk forward from startIndex in the playlist, subtracting durations
  762. // until we find a segment that contains `time` and return it
  763. for (let i = startIndex; i < partsAndSegments.length; i++) {
  764. const partAndSegment = partsAndSegments[i];
  765. time -= partAndSegment.duration;
  766. if (exactManifestTimings) {
  767. if (time > 0) {
  768. continue;
  769. }
  770. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  771. continue;
  772. }
  773. return {
  774. partIndex: partAndSegment.partIndex,
  775. segmentIndex: partAndSegment.segmentIndex,
  776. startTime: startTime + sumDurations({
  777. defaultDuration: playlist.targetDuration,
  778. durationList: partsAndSegments,
  779. startIndex,
  780. endIndex: i
  781. })
  782. };
  783. } // We are out of possible candidates so load the last one...
  784. return {
  785. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  786. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  787. startTime: currentTime
  788. };
  789. };
  790. /**
  791. * Check whether the playlist is excluded or not.
  792. *
  793. * @param {Object} playlist the media playlist object
  794. * @return {boolean} whether the playlist is excluded or not
  795. * @function isExcluded
  796. */
  797. const isExcluded = function (playlist) {
  798. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  799. };
  800. /**
  801. * Check whether the playlist is compatible with current playback configuration or has
  802. * been excluded permanently for being incompatible.
  803. *
  804. * @param {Object} playlist the media playlist object
  805. * @return {boolean} whether the playlist is incompatible or not
  806. * @function isIncompatible
  807. */
  808. const isIncompatible = function (playlist) {
  809. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  810. };
  811. /**
  812. * Check whether the playlist is enabled or not.
  813. *
  814. * @param {Object} playlist the media playlist object
  815. * @return {boolean} whether the playlist is enabled or not
  816. * @function isEnabled
  817. */
  818. const isEnabled = function (playlist) {
  819. const excluded = isExcluded(playlist);
  820. return !playlist.disabled && !excluded;
  821. };
  822. /**
  823. * Check whether the playlist has been manually disabled through the representations api.
  824. *
  825. * @param {Object} playlist the media playlist object
  826. * @return {boolean} whether the playlist is disabled manually or not
  827. * @function isDisabled
  828. */
  829. const isDisabled = function (playlist) {
  830. return playlist.disabled;
  831. };
  832. /**
  833. * Returns whether the current playlist is an AES encrypted HLS stream
  834. *
  835. * @return {boolean} true if it's an AES encrypted HLS stream
  836. */
  837. const isAes = function (media) {
  838. for (let i = 0; i < media.segments.length; i++) {
  839. if (media.segments[i].key) {
  840. return true;
  841. }
  842. }
  843. return false;
  844. };
  845. /**
  846. * Checks if the playlist has a value for the specified attribute
  847. *
  848. * @param {string} attr
  849. * Attribute to check for
  850. * @param {Object} playlist
  851. * The media playlist object
  852. * @return {boolean}
  853. * Whether the playlist contains a value for the attribute or not
  854. * @function hasAttribute
  855. */
  856. const hasAttribute = function (attr, playlist) {
  857. return playlist.attributes && playlist.attributes[attr];
  858. };
  859. /**
  860. * Estimates the time required to complete a segment download from the specified playlist
  861. *
  862. * @param {number} segmentDuration
  863. * Duration of requested segment
  864. * @param {number} bandwidth
  865. * Current measured bandwidth of the player
  866. * @param {Object} playlist
  867. * The media playlist object
  868. * @param {number=} bytesReceived
  869. * Number of bytes already received for the request. Defaults to 0
  870. * @return {number|NaN}
  871. * The estimated time to request the segment. NaN if bandwidth information for
  872. * the given playlist is unavailable
  873. * @function estimateSegmentRequestTime
  874. */
  875. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  876. if (!hasAttribute('BANDWIDTH', playlist)) {
  877. return NaN;
  878. }
  879. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  880. return (size - bytesReceived * 8) / bandwidth;
  881. };
  882. /*
  883. * Returns whether the current playlist is the lowest rendition
  884. *
  885. * @return {Boolean} true if on lowest rendition
  886. */
  887. const isLowestEnabledRendition = (main, media) => {
  888. if (main.playlists.length === 1) {
  889. return true;
  890. }
  891. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  892. return main.playlists.filter(playlist => {
  893. if (!isEnabled(playlist)) {
  894. return false;
  895. }
  896. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  897. }).length === 0;
  898. };
  899. const playlistMatch = (a, b) => {
  900. // both playlits are null
  901. // or only one playlist is non-null
  902. // no match
  903. if (!a && !b || !a && b || a && !b) {
  904. return false;
  905. } // playlist objects are the same, match
  906. if (a === b) {
  907. return true;
  908. } // first try to use id as it should be the most
  909. // accurate
  910. if (a.id && b.id && a.id === b.id) {
  911. return true;
  912. } // next try to use reslovedUri as it should be the
  913. // second most accurate.
  914. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  915. return true;
  916. } // finally try to use uri as it should be accurate
  917. // but might miss a few cases for relative uris
  918. if (a.uri && b.uri && a.uri === b.uri) {
  919. return true;
  920. }
  921. return false;
  922. };
  923. const someAudioVariant = function (main, callback) {
  924. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  925. let found = false;
  926. for (const groupName in AUDIO) {
  927. for (const label in AUDIO[groupName]) {
  928. found = callback(AUDIO[groupName][label]);
  929. if (found) {
  930. break;
  931. }
  932. }
  933. if (found) {
  934. break;
  935. }
  936. }
  937. return !!found;
  938. };
  939. const isAudioOnly = main => {
  940. // we are audio only if we have no main playlists but do
  941. // have media group playlists.
  942. if (!main || !main.playlists || !main.playlists.length) {
  943. // without audio variants or playlists this
  944. // is not an audio only main.
  945. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  946. return found;
  947. } // if every playlist has only an audio codec it is audio only
  948. for (let i = 0; i < main.playlists.length; i++) {
  949. const playlist = main.playlists[i];
  950. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  951. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  952. continue;
  953. } // playlist is in an audio group it is audio only
  954. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  955. if (found) {
  956. continue;
  957. } // if we make it here this playlist isn't audio and we
  958. // are not audio only
  959. return false;
  960. } // if we make it past every playlist without returning, then
  961. // this is an audio only playlist.
  962. return true;
  963. }; // exports
  964. var Playlist = {
  965. liveEdgeDelay,
  966. duration,
  967. seekable,
  968. getMediaInfoForTime,
  969. isEnabled,
  970. isDisabled,
  971. isExcluded,
  972. isIncompatible,
  973. playlistEnd,
  974. isAes,
  975. hasAttribute,
  976. estimateSegmentRequestTime,
  977. isLowestEnabledRendition,
  978. isAudioOnly,
  979. playlistMatch,
  980. segmentDurationWithParts
  981. };
  982. const {
  983. log
  984. } = videojs;
  985. const createPlaylistID = (index, uri) => {
  986. return `${index}-${uri}`;
  987. }; // default function for creating a group id
  988. const groupID = (type, group, label) => {
  989. return `placeholder-uri-${type}-${group}-${label}`;
  990. };
  991. /**
  992. * Parses a given m3u8 playlist
  993. *
  994. * @param {Function} [onwarn]
  995. * a function to call when the parser triggers a warning event.
  996. * @param {Function} [oninfo]
  997. * a function to call when the parser triggers an info event.
  998. * @param {string} manifestString
  999. * The downloaded manifest string
  1000. * @param {Object[]} [customTagParsers]
  1001. * An array of custom tag parsers for the m3u8-parser instance
  1002. * @param {Object[]} [customTagMappers]
  1003. * An array of custom tag mappers for the m3u8-parser instance
  1004. * @param {boolean} [llhls]
  1005. * Whether to keep ll-hls features in the manifest after parsing.
  1006. * @return {Object}
  1007. * The manifest object
  1008. */
  1009. const parseManifest = ({
  1010. onwarn,
  1011. oninfo,
  1012. manifestString,
  1013. customTagParsers = [],
  1014. customTagMappers = [],
  1015. llhls
  1016. }) => {
  1017. const parser = new Parser();
  1018. if (onwarn) {
  1019. parser.on('warn', onwarn);
  1020. }
  1021. if (oninfo) {
  1022. parser.on('info', oninfo);
  1023. }
  1024. customTagParsers.forEach(customParser => parser.addParser(customParser));
  1025. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  1026. parser.push(manifestString);
  1027. parser.end();
  1028. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  1029. // if we don't want llhls support.
  1030. if (!llhls) {
  1031. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  1032. if (manifest.hasOwnProperty(k)) {
  1033. delete manifest[k];
  1034. }
  1035. });
  1036. if (manifest.segments) {
  1037. manifest.segments.forEach(function (segment) {
  1038. ['parts', 'preloadHints'].forEach(function (k) {
  1039. if (segment.hasOwnProperty(k)) {
  1040. delete segment[k];
  1041. }
  1042. });
  1043. });
  1044. }
  1045. }
  1046. if (!manifest.targetDuration) {
  1047. let targetDuration = 10;
  1048. if (manifest.segments && manifest.segments.length) {
  1049. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  1050. }
  1051. if (onwarn) {
  1052. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  1053. }
  1054. manifest.targetDuration = targetDuration;
  1055. }
  1056. const parts = getLastParts(manifest);
  1057. if (parts.length && !manifest.partTargetDuration) {
  1058. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  1059. if (onwarn) {
  1060. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  1061. 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.');
  1062. }
  1063. manifest.partTargetDuration = partTargetDuration;
  1064. }
  1065. return manifest;
  1066. };
  1067. /**
  1068. * Loops through all supported media groups in main and calls the provided
  1069. * callback for each group
  1070. *
  1071. * @param {Object} main
  1072. * The parsed main manifest object
  1073. * @param {Function} callback
  1074. * Callback to call for each media group
  1075. */
  1076. const forEachMediaGroup = (main, callback) => {
  1077. if (!main.mediaGroups) {
  1078. return;
  1079. }
  1080. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  1081. if (!main.mediaGroups[mediaType]) {
  1082. return;
  1083. }
  1084. for (const groupKey in main.mediaGroups[mediaType]) {
  1085. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  1086. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  1087. callback(mediaProperties, mediaType, groupKey, labelKey);
  1088. }
  1089. }
  1090. });
  1091. };
  1092. /**
  1093. * Adds properties and attributes to the playlist to keep consistent functionality for
  1094. * playlists throughout VHS.
  1095. *
  1096. * @param {Object} config
  1097. * Arguments object
  1098. * @param {Object} config.playlist
  1099. * The media playlist
  1100. * @param {string} [config.uri]
  1101. * The uri to the media playlist (if media playlist is not from within a main
  1102. * playlist)
  1103. * @param {string} id
  1104. * ID to use for the playlist
  1105. */
  1106. const setupMediaPlaylist = ({
  1107. playlist,
  1108. uri,
  1109. id
  1110. }) => {
  1111. playlist.id = id;
  1112. playlist.playlistErrors_ = 0;
  1113. if (uri) {
  1114. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  1115. // playlists do not contain their own source URI, but one is needed for consistency in
  1116. // VHS.
  1117. playlist.uri = uri;
  1118. } // For HLS main playlists, even though certain attributes MUST be defined, the
  1119. // stream may still be played without them.
  1120. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  1121. // manifest.
  1122. //
  1123. // To avoid undefined reference errors through the project, and make the code easier
  1124. // to write/read, add an empty attributes object for these cases.
  1125. playlist.attributes = playlist.attributes || {};
  1126. };
  1127. /**
  1128. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  1129. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  1130. * playlist references to the playlists array.
  1131. *
  1132. * @param {Object} main
  1133. * The main playlist
  1134. */
  1135. const setupMediaPlaylists = main => {
  1136. let i = main.playlists.length;
  1137. while (i--) {
  1138. const playlist = main.playlists[i];
  1139. setupMediaPlaylist({
  1140. playlist,
  1141. id: createPlaylistID(i, playlist.uri)
  1142. });
  1143. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  1144. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  1145. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  1146. // the stream can be played without it. Although an attributes property may have been
  1147. // added to the playlist to prevent undefined references, issue a warning to fix the
  1148. // manifest.
  1149. if (!playlist.attributes.BANDWIDTH) {
  1150. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  1151. }
  1152. }
  1153. };
  1154. /**
  1155. * Adds resolvedUri properties to each media group.
  1156. *
  1157. * @param {Object} main
  1158. * The main playlist
  1159. */
  1160. const resolveMediaGroupUris = main => {
  1161. forEachMediaGroup(main, properties => {
  1162. if (properties.uri) {
  1163. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  1164. }
  1165. });
  1166. };
  1167. /**
  1168. * Creates a main playlist wrapper to insert a sole media playlist into.
  1169. *
  1170. * @param {Object} media
  1171. * Media playlist
  1172. * @param {string} uri
  1173. * The media URI
  1174. *
  1175. * @return {Object}
  1176. * main playlist
  1177. */
  1178. const mainForMedia = (media, uri) => {
  1179. const id = createPlaylistID(0, uri);
  1180. const main = {
  1181. mediaGroups: {
  1182. 'AUDIO': {},
  1183. 'VIDEO': {},
  1184. 'CLOSED-CAPTIONS': {},
  1185. 'SUBTITLES': {}
  1186. },
  1187. uri: window$1.location.href,
  1188. resolvedUri: window$1.location.href,
  1189. playlists: [{
  1190. uri,
  1191. id,
  1192. resolvedUri: uri,
  1193. // m3u8-parser does not attach an attributes property to media playlists so make
  1194. // sure that the property is attached to avoid undefined reference errors
  1195. attributes: {}
  1196. }]
  1197. }; // set up ID reference
  1198. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  1199. main.playlists[uri] = main.playlists[0];
  1200. return main;
  1201. };
  1202. /**
  1203. * Does an in-place update of the main manifest to add updated playlist URI references
  1204. * as well as other properties needed by VHS that aren't included by the parser.
  1205. *
  1206. * @param {Object} main
  1207. * main manifest object
  1208. * @param {string} uri
  1209. * The source URI
  1210. * @param {function} createGroupID
  1211. * A function to determine how to create the groupID for mediaGroups
  1212. */
  1213. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  1214. main.uri = uri;
  1215. for (let i = 0; i < main.playlists.length; i++) {
  1216. if (!main.playlists[i].uri) {
  1217. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  1218. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  1219. // TODO: consider adding dummy URIs in mpd-parser
  1220. const phonyUri = `placeholder-uri-${i}`;
  1221. main.playlists[i].uri = phonyUri;
  1222. }
  1223. }
  1224. const audioOnlyMain = isAudioOnly(main);
  1225. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1226. // add a playlist array under properties
  1227. if (!properties.playlists || !properties.playlists.length) {
  1228. // If the manifest is audio only and this media group does not have a uri, check
  1229. // if the media group is located in the main list of playlists. If it is, don't add
  1230. // placeholder properties as it shouldn't be considered an alternate audio track.
  1231. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  1232. for (let i = 0; i < main.playlists.length; i++) {
  1233. const p = main.playlists[i];
  1234. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  1235. return;
  1236. }
  1237. }
  1238. }
  1239. properties.playlists = [_extends({}, properties)];
  1240. }
  1241. properties.playlists.forEach(function (p, i) {
  1242. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  1243. const id = createPlaylistID(i, groupId);
  1244. if (p.uri) {
  1245. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  1246. } else {
  1247. // DEPRECATED, this has been added to prevent a breaking change.
  1248. // previously we only ever had a single media group playlist, so
  1249. // we mark the first playlist uri without prepending the index as we used to
  1250. // ideally we would do all of the playlists the same way.
  1251. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  1252. // the placeholder again
  1253. p.resolvedUri = p.uri;
  1254. }
  1255. p.id = p.id || id; // add an empty attributes object, all playlists are
  1256. // expected to have this.
  1257. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  1258. main.playlists[p.id] = p;
  1259. main.playlists[p.uri] = p;
  1260. });
  1261. });
  1262. setupMediaPlaylists(main);
  1263. resolveMediaGroupUris(main);
  1264. };
  1265. /**
  1266. * @file playlist-loader.js
  1267. *
  1268. * A state machine that manages the loading, caching, and updating of
  1269. * M3U8 playlists.
  1270. *
  1271. */
  1272. const {
  1273. EventTarget: EventTarget$1
  1274. } = videojs;
  1275. const addLLHLSQueryDirectives = (uri, media) => {
  1276. if (media.endList || !media.serverControl) {
  1277. return uri;
  1278. }
  1279. const parameters = {};
  1280. if (media.serverControl.canBlockReload) {
  1281. const {
  1282. preloadSegment
  1283. } = media; // next msn is a zero based value, length is not.
  1284. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  1285. // that we are going to request a part of that preload segment.
  1286. // the logic below is used to determine that.
  1287. if (preloadSegment) {
  1288. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  1289. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  1290. // length of parts, then we know we had part preload hints
  1291. // and we need to add the _HLS_part= query
  1292. if (nextPart > -1 && nextPart !== parts.length - 1) {
  1293. // add existing parts to our preload hints
  1294. // eslint-disable-next-line
  1295. parameters._HLS_part = nextPart;
  1296. } // this if statement makes sure that we request the msn
  1297. // of the preload segment if:
  1298. // 1. the preload segment had parts (and was not yet a full segment)
  1299. // but was added to our segments array
  1300. // 2. the preload segment had preload hints for parts that are not in
  1301. // the manifest yet.
  1302. // in all other cases we want the segment after the preload segment
  1303. // which will be given by using media.segments.length because it is 1 based
  1304. // rather than 0 based.
  1305. if (nextPart > -1 || parts.length) {
  1306. nextMSN--;
  1307. }
  1308. } // add _HLS_msn= in front of any _HLS_part query
  1309. // eslint-disable-next-line
  1310. parameters._HLS_msn = nextMSN;
  1311. }
  1312. if (media.serverControl && media.serverControl.canSkipUntil) {
  1313. // add _HLS_skip= infront of all other queries.
  1314. // eslint-disable-next-line
  1315. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  1316. }
  1317. if (Object.keys(parameters).length) {
  1318. const parsedUri = new window$1.URL(uri);
  1319. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  1320. if (!parameters.hasOwnProperty(name)) {
  1321. return;
  1322. }
  1323. parsedUri.searchParams.set(name, parameters[name]);
  1324. });
  1325. uri = parsedUri.toString();
  1326. }
  1327. return uri;
  1328. };
  1329. /**
  1330. * Returns a new segment object with properties and
  1331. * the parts array merged.
  1332. *
  1333. * @param {Object} a the old segment
  1334. * @param {Object} b the new segment
  1335. *
  1336. * @return {Object} the merged segment
  1337. */
  1338. const updateSegment = (a, b) => {
  1339. if (!a) {
  1340. return b;
  1341. }
  1342. const result = merge(a, b); // if only the old segment has preload hints
  1343. // and the new one does not, remove preload hints.
  1344. if (a.preloadHints && !b.preloadHints) {
  1345. delete result.preloadHints;
  1346. } // if only the old segment has parts
  1347. // then the parts are no longer valid
  1348. if (a.parts && !b.parts) {
  1349. delete result.parts; // if both segments have parts
  1350. // copy part propeties from the old segment
  1351. // to the new one.
  1352. } else if (a.parts && b.parts) {
  1353. for (let i = 0; i < b.parts.length; i++) {
  1354. if (a.parts && a.parts[i]) {
  1355. result.parts[i] = merge(a.parts[i], b.parts[i]);
  1356. }
  1357. }
  1358. } // set skipped to false for segments that have
  1359. // have had information merged from the old segment.
  1360. if (!a.skipped && b.skipped) {
  1361. result.skipped = false;
  1362. } // set preload to false for segments that have
  1363. // had information added in the new segment.
  1364. if (a.preload && !b.preload) {
  1365. result.preload = false;
  1366. }
  1367. return result;
  1368. };
  1369. /**
  1370. * Returns a new array of segments that is the result of merging
  1371. * properties from an older list of segments onto an updated
  1372. * list. No properties on the updated playlist will be ovewritten.
  1373. *
  1374. * @param {Array} original the outdated list of segments
  1375. * @param {Array} update the updated list of segments
  1376. * @param {number=} offset the index of the first update
  1377. * segment in the original segment list. For non-live playlists,
  1378. * this should always be zero and does not need to be
  1379. * specified. For live playlists, it should be the difference
  1380. * between the media sequence numbers in the original and updated
  1381. * playlists.
  1382. * @return {Array} a list of merged segment objects
  1383. */
  1384. const updateSegments = (original, update, offset) => {
  1385. const oldSegments = original.slice();
  1386. const newSegments = update.slice();
  1387. offset = offset || 0;
  1388. const result = [];
  1389. let currentMap;
  1390. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  1391. const oldSegment = oldSegments[newIndex + offset];
  1392. const newSegment = newSegments[newIndex];
  1393. if (oldSegment) {
  1394. currentMap = oldSegment.map || currentMap;
  1395. result.push(updateSegment(oldSegment, newSegment));
  1396. } else {
  1397. // carry over map to new segment if it is missing
  1398. if (currentMap && !newSegment.map) {
  1399. newSegment.map = currentMap;
  1400. }
  1401. result.push(newSegment);
  1402. }
  1403. }
  1404. return result;
  1405. };
  1406. const resolveSegmentUris = (segment, baseUri) => {
  1407. // preloadSegment will not have a uri at all
  1408. // as the segment isn't actually in the manifest yet, only parts
  1409. if (!segment.resolvedUri && segment.uri) {
  1410. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  1411. }
  1412. if (segment.key && !segment.key.resolvedUri) {
  1413. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  1414. }
  1415. if (segment.map && !segment.map.resolvedUri) {
  1416. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  1417. }
  1418. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  1419. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  1420. }
  1421. if (segment.parts && segment.parts.length) {
  1422. segment.parts.forEach(p => {
  1423. if (p.resolvedUri) {
  1424. return;
  1425. }
  1426. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1427. });
  1428. }
  1429. if (segment.preloadHints && segment.preloadHints.length) {
  1430. segment.preloadHints.forEach(p => {
  1431. if (p.resolvedUri) {
  1432. return;
  1433. }
  1434. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1435. });
  1436. }
  1437. };
  1438. const getAllSegments = function (media) {
  1439. const segments = media.segments || [];
  1440. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  1441. // a usable segment, only include a preloadSegment that has
  1442. // parts.
  1443. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  1444. // if preloadHints has a MAP that means that the
  1445. // init segment is going to change. We cannot use any of the parts
  1446. // from this preload segment.
  1447. if (preloadSegment.preloadHints) {
  1448. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  1449. if (preloadSegment.preloadHints[i].type === 'MAP') {
  1450. return segments;
  1451. }
  1452. }
  1453. } // set the duration for our preload segment to target duration.
  1454. preloadSegment.duration = media.targetDuration;
  1455. preloadSegment.preload = true;
  1456. segments.push(preloadSegment);
  1457. }
  1458. return segments;
  1459. }; // consider the playlist unchanged if the playlist object is the same or
  1460. // the number of segments is equal, the media sequence number is unchanged,
  1461. // and this playlist hasn't become the end of the playlist
  1462. 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;
  1463. /**
  1464. * Returns a new main playlist that is the result of merging an
  1465. * updated media playlist into the original version. If the
  1466. * updated media playlist does not match any of the playlist
  1467. * entries in the original main playlist, null is returned.
  1468. *
  1469. * @param {Object} main a parsed main M3U8 object
  1470. * @param {Object} media a parsed media M3U8 object
  1471. * @return {Object} a new object that represents the original
  1472. * main playlist with the updated media playlist merged in, or
  1473. * null if the merge produced no change.
  1474. */
  1475. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  1476. const result = merge(main, {});
  1477. const oldMedia = result.playlists[newMedia.id];
  1478. if (!oldMedia) {
  1479. return null;
  1480. }
  1481. if (unchangedCheck(oldMedia, newMedia)) {
  1482. return null;
  1483. }
  1484. newMedia.segments = getAllSegments(newMedia);
  1485. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  1486. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  1487. delete mergedPlaylist.preloadSegment;
  1488. } // if the update could overlap existing segment information, merge the two segment lists
  1489. if (oldMedia.segments) {
  1490. if (newMedia.skip) {
  1491. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  1492. // old properties into the new segments
  1493. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  1494. newMedia.segments.unshift({
  1495. skipped: true
  1496. });
  1497. }
  1498. }
  1499. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  1500. } // resolve any segment URIs to prevent us from having to do it later
  1501. mergedPlaylist.segments.forEach(segment => {
  1502. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  1503. }); // TODO Right now in the playlists array there are two references to each playlist, one
  1504. // that is referenced by index, and one by URI. The index reference may no longer be
  1505. // necessary.
  1506. for (let i = 0; i < result.playlists.length; i++) {
  1507. if (result.playlists[i].id === newMedia.id) {
  1508. result.playlists[i] = mergedPlaylist;
  1509. }
  1510. }
  1511. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  1512. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  1513. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1514. if (!properties.playlists) {
  1515. return;
  1516. }
  1517. for (let i = 0; i < properties.playlists.length; i++) {
  1518. if (newMedia.id === properties.playlists[i].id) {
  1519. properties.playlists[i] = mergedPlaylist;
  1520. }
  1521. }
  1522. });
  1523. return result;
  1524. };
  1525. /**
  1526. * Calculates the time to wait before refreshing a live playlist
  1527. *
  1528. * @param {Object} media
  1529. * The current media
  1530. * @param {boolean} update
  1531. * True if there were any updates from the last refresh, false otherwise
  1532. * @return {number}
  1533. * The time in ms to wait before refreshing the live playlist
  1534. */
  1535. const refreshDelay = (media, update) => {
  1536. const segments = media.segments || [];
  1537. const lastSegment = segments[segments.length - 1];
  1538. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  1539. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  1540. if (update && lastDuration) {
  1541. return lastDuration * 1000;
  1542. } // if the playlist is unchanged since the last reload or last segment duration
  1543. // cannot be determined, try again after half the target duration
  1544. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  1545. };
  1546. /**
  1547. * Load a playlist from a remote location
  1548. *
  1549. * @class PlaylistLoader
  1550. * @extends Stream
  1551. * @param {string|Object} src url or object of manifest
  1552. * @param {boolean} withCredentials the withCredentials xhr option
  1553. * @class
  1554. */
  1555. class PlaylistLoader extends EventTarget$1 {
  1556. constructor(src, vhs, options = {}) {
  1557. super();
  1558. if (!src) {
  1559. throw new Error('A non-empty playlist URL or object is required');
  1560. }
  1561. this.logger_ = logger('PlaylistLoader');
  1562. const {
  1563. withCredentials = false
  1564. } = options;
  1565. this.src = src;
  1566. this.vhs_ = vhs;
  1567. this.withCredentials = withCredentials;
  1568. const vhsOptions = vhs.options_;
  1569. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  1570. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  1571. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  1572. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  1573. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  1574. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  1575. }
  1576. handleMediaupdatetimeout_() {
  1577. if (this.state !== 'HAVE_METADATA') {
  1578. // only refresh the media playlist if no other activity is going on
  1579. return;
  1580. }
  1581. const media = this.media();
  1582. let uri = resolveUrl(this.main.uri, media.uri);
  1583. if (this.llhls) {
  1584. uri = addLLHLSQueryDirectives(uri, media);
  1585. }
  1586. this.state = 'HAVE_CURRENT_METADATA';
  1587. this.request = this.vhs_.xhr({
  1588. uri,
  1589. withCredentials: this.withCredentials
  1590. }, (error, req) => {
  1591. // disposed
  1592. if (!this.request) {
  1593. return;
  1594. }
  1595. if (error) {
  1596. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  1597. }
  1598. this.haveMetadata({
  1599. playlistString: this.request.responseText,
  1600. url: this.media().uri,
  1601. id: this.media().id
  1602. });
  1603. });
  1604. }
  1605. playlistRequestError(xhr, playlist, startingState) {
  1606. const {
  1607. uri,
  1608. id
  1609. } = playlist; // any in-flight request is now finished
  1610. this.request = null;
  1611. if (startingState) {
  1612. this.state = startingState;
  1613. }
  1614. this.error = {
  1615. playlist: this.main.playlists[id],
  1616. status: xhr.status,
  1617. message: `HLS playlist request error at URL: ${uri}.`,
  1618. responseText: xhr.responseText,
  1619. code: xhr.status >= 500 ? 4 : 2
  1620. };
  1621. this.trigger('error');
  1622. }
  1623. parseManifest_({
  1624. url,
  1625. manifestString
  1626. }) {
  1627. return parseManifest({
  1628. onwarn: ({
  1629. message
  1630. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  1631. oninfo: ({
  1632. message
  1633. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  1634. manifestString,
  1635. customTagParsers: this.customTagParsers,
  1636. customTagMappers: this.customTagMappers,
  1637. llhls: this.llhls
  1638. });
  1639. }
  1640. /**
  1641. * Update the playlist loader's state in response to a new or updated playlist.
  1642. *
  1643. * @param {string} [playlistString]
  1644. * Playlist string (if playlistObject is not provided)
  1645. * @param {Object} [playlistObject]
  1646. * Playlist object (if playlistString is not provided)
  1647. * @param {string} url
  1648. * URL of playlist
  1649. * @param {string} id
  1650. * ID to use for playlist
  1651. */
  1652. haveMetadata({
  1653. playlistString,
  1654. playlistObject,
  1655. url,
  1656. id
  1657. }) {
  1658. // any in-flight request is now finished
  1659. this.request = null;
  1660. this.state = 'HAVE_METADATA';
  1661. const playlist = playlistObject || this.parseManifest_({
  1662. url,
  1663. manifestString: playlistString
  1664. });
  1665. playlist.lastRequest = Date.now();
  1666. setupMediaPlaylist({
  1667. playlist,
  1668. uri: url,
  1669. id
  1670. }); // merge this playlist into the main manifest
  1671. const update = updateMain$1(this.main, playlist);
  1672. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  1673. this.pendingMedia_ = null;
  1674. if (update) {
  1675. this.main = update;
  1676. this.media_ = this.main.playlists[id];
  1677. } else {
  1678. this.trigger('playlistunchanged');
  1679. }
  1680. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  1681. this.trigger('loadedplaylist');
  1682. }
  1683. /**
  1684. * Abort any outstanding work and clean up.
  1685. */
  1686. dispose() {
  1687. this.trigger('dispose');
  1688. this.stopRequest();
  1689. window$1.clearTimeout(this.mediaUpdateTimeout);
  1690. window$1.clearTimeout(this.finalRenditionTimeout);
  1691. this.off();
  1692. }
  1693. stopRequest() {
  1694. if (this.request) {
  1695. const oldRequest = this.request;
  1696. this.request = null;
  1697. oldRequest.onreadystatechange = null;
  1698. oldRequest.abort();
  1699. }
  1700. }
  1701. /**
  1702. * When called without any arguments, returns the currently
  1703. * active media playlist. When called with a single argument,
  1704. * triggers the playlist loader to asynchronously switch to the
  1705. * specified media playlist. Calling this method while the
  1706. * loader is in the HAVE_NOTHING causes an error to be emitted
  1707. * but otherwise has no effect.
  1708. *
  1709. * @param {Object=} playlist the parsed media playlist
  1710. * object to switch to
  1711. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  1712. *
  1713. * @return {Playlist} the current loaded media
  1714. */
  1715. media(playlist, shouldDelay) {
  1716. // getter
  1717. if (!playlist) {
  1718. return this.media_;
  1719. } // setter
  1720. if (this.state === 'HAVE_NOTHING') {
  1721. throw new Error('Cannot switch media playlist from ' + this.state);
  1722. } // find the playlist object if the target playlist has been
  1723. // specified by URI
  1724. if (typeof playlist === 'string') {
  1725. if (!this.main.playlists[playlist]) {
  1726. throw new Error('Unknown playlist URI: ' + playlist);
  1727. }
  1728. playlist = this.main.playlists[playlist];
  1729. }
  1730. window$1.clearTimeout(this.finalRenditionTimeout);
  1731. if (shouldDelay) {
  1732. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  1733. this.finalRenditionTimeout = window$1.setTimeout(this.media.bind(this, playlist, false), delay);
  1734. return;
  1735. }
  1736. const startingState = this.state;
  1737. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  1738. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  1739. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  1740. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  1741. playlist.endList && playlist.segments.length) {
  1742. // abort outstanding playlist requests
  1743. if (this.request) {
  1744. this.request.onreadystatechange = null;
  1745. this.request.abort();
  1746. this.request = null;
  1747. }
  1748. this.state = 'HAVE_METADATA';
  1749. this.media_ = playlist; // trigger media change if the active media has been updated
  1750. if (mediaChange) {
  1751. this.trigger('mediachanging');
  1752. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1753. // The initial playlist was a main manifest, and the first media selected was
  1754. // also provided (in the form of a resolved playlist object) as part of the
  1755. // source object (rather than just a URL). Therefore, since the media playlist
  1756. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  1757. // normal flow, and needs an explicit trigger here.
  1758. this.trigger('loadedmetadata');
  1759. } else {
  1760. this.trigger('mediachange');
  1761. }
  1762. }
  1763. return;
  1764. } // We update/set the timeout here so that live playlists
  1765. // that are not a media change will "start" the loader as expected.
  1766. // We expect that this function will start the media update timeout
  1767. // cycle again. This also prevents a playlist switch failure from
  1768. // causing us to stall during live.
  1769. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  1770. if (!mediaChange) {
  1771. return;
  1772. }
  1773. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  1774. if (this.request) {
  1775. if (playlist.resolvedUri === this.request.url) {
  1776. // requesting to switch to the same playlist multiple times
  1777. // has no effect after the first
  1778. return;
  1779. }
  1780. this.request.onreadystatechange = null;
  1781. this.request.abort();
  1782. this.request = null;
  1783. } // request the new playlist
  1784. if (this.media_) {
  1785. this.trigger('mediachanging');
  1786. }
  1787. this.pendingMedia_ = playlist;
  1788. this.request = this.vhs_.xhr({
  1789. uri: playlist.resolvedUri,
  1790. withCredentials: this.withCredentials
  1791. }, (error, req) => {
  1792. // disposed
  1793. if (!this.request) {
  1794. return;
  1795. }
  1796. playlist.lastRequest = Date.now();
  1797. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  1798. if (error) {
  1799. return this.playlistRequestError(this.request, playlist, startingState);
  1800. }
  1801. this.haveMetadata({
  1802. playlistString: req.responseText,
  1803. url: playlist.uri,
  1804. id: playlist.id
  1805. }); // fire loadedmetadata the first time a media playlist is loaded
  1806. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1807. this.trigger('loadedmetadata');
  1808. } else {
  1809. this.trigger('mediachange');
  1810. }
  1811. });
  1812. }
  1813. /**
  1814. * pause loading of the playlist
  1815. */
  1816. pause() {
  1817. if (this.mediaUpdateTimeout) {
  1818. window$1.clearTimeout(this.mediaUpdateTimeout);
  1819. this.mediaUpdateTimeout = null;
  1820. }
  1821. this.stopRequest();
  1822. if (this.state === 'HAVE_NOTHING') {
  1823. // If we pause the loader before any data has been retrieved, its as if we never
  1824. // started, so reset to an unstarted state.
  1825. this.started = false;
  1826. } // Need to restore state now that no activity is happening
  1827. if (this.state === 'SWITCHING_MEDIA') {
  1828. // if the loader was in the process of switching media, it should either return to
  1829. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  1830. // playlist yet. This is determined by the existence of loader.media_
  1831. if (this.media_) {
  1832. this.state = 'HAVE_METADATA';
  1833. } else {
  1834. this.state = 'HAVE_MAIN_MANIFEST';
  1835. }
  1836. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  1837. this.state = 'HAVE_METADATA';
  1838. }
  1839. }
  1840. /**
  1841. * start loading of the playlist
  1842. */
  1843. load(shouldDelay) {
  1844. if (this.mediaUpdateTimeout) {
  1845. window$1.clearTimeout(this.mediaUpdateTimeout);
  1846. this.mediaUpdateTimeout = null;
  1847. }
  1848. const media = this.media();
  1849. if (shouldDelay) {
  1850. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  1851. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  1852. this.mediaUpdateTimeout = null;
  1853. this.load();
  1854. }, delay);
  1855. return;
  1856. }
  1857. if (!this.started) {
  1858. this.start();
  1859. return;
  1860. }
  1861. if (media && !media.endList) {
  1862. this.trigger('mediaupdatetimeout');
  1863. } else {
  1864. this.trigger('loadedplaylist');
  1865. }
  1866. }
  1867. updateMediaUpdateTimeout_(delay) {
  1868. if (this.mediaUpdateTimeout) {
  1869. window$1.clearTimeout(this.mediaUpdateTimeout);
  1870. this.mediaUpdateTimeout = null;
  1871. } // we only have use mediaupdatetimeout for live playlists.
  1872. if (!this.media() || this.media().endList) {
  1873. return;
  1874. }
  1875. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  1876. this.mediaUpdateTimeout = null;
  1877. this.trigger('mediaupdatetimeout');
  1878. this.updateMediaUpdateTimeout_(delay);
  1879. }, delay);
  1880. }
  1881. /**
  1882. * start loading of the playlist
  1883. */
  1884. start() {
  1885. this.started = true;
  1886. if (typeof this.src === 'object') {
  1887. // in the case of an entirely constructed manifest object (meaning there's no actual
  1888. // manifest on a server), default the uri to the page's href
  1889. if (!this.src.uri) {
  1890. this.src.uri = window$1.location.href;
  1891. } // resolvedUri is added on internally after the initial request. Since there's no
  1892. // request for pre-resolved manifests, add on resolvedUri here.
  1893. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  1894. // request can be skipped (since the top level of the manifest, at a minimum, is
  1895. // already available as a parsed manifest object). However, if the manifest object
  1896. // represents a main playlist, some media playlists may need to be resolved before
  1897. // the starting segment list is available. Therefore, go directly to setup of the
  1898. // initial playlist, and let the normal flow continue from there.
  1899. //
  1900. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  1901. // that the first request is asynchronous.
  1902. setTimeout(() => {
  1903. this.setupInitialPlaylist(this.src);
  1904. }, 0);
  1905. return;
  1906. } // request the specified URL
  1907. this.request = this.vhs_.xhr({
  1908. uri: this.src,
  1909. withCredentials: this.withCredentials
  1910. }, (error, req) => {
  1911. // disposed
  1912. if (!this.request) {
  1913. return;
  1914. } // clear the loader's request reference
  1915. this.request = null;
  1916. if (error) {
  1917. this.error = {
  1918. status: req.status,
  1919. message: `HLS playlist request error at URL: ${this.src}.`,
  1920. responseText: req.responseText,
  1921. // MEDIA_ERR_NETWORK
  1922. code: 2
  1923. };
  1924. if (this.state === 'HAVE_NOTHING') {
  1925. this.started = false;
  1926. }
  1927. return this.trigger('error');
  1928. }
  1929. this.src = resolveManifestRedirect(this.src, req);
  1930. const manifest = this.parseManifest_({
  1931. manifestString: req.responseText,
  1932. url: this.src
  1933. });
  1934. this.setupInitialPlaylist(manifest);
  1935. });
  1936. }
  1937. srcUri() {
  1938. return typeof this.src === 'string' ? this.src : this.src.uri;
  1939. }
  1940. /**
  1941. * Given a manifest object that's either a main or media playlist, trigger the proper
  1942. * events and set the state of the playlist loader.
  1943. *
  1944. * If the manifest object represents a main playlist, `loadedplaylist` will be
  1945. * triggered to allow listeners to select a playlist. If none is selected, the loader
  1946. * will default to the first one in the playlists array.
  1947. *
  1948. * If the manifest object represents a media playlist, `loadedplaylist` will be
  1949. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  1950. *
  1951. * In the case of a media playlist, a main playlist object wrapper with one playlist
  1952. * will be created so that all logic can handle playlists in the same fashion (as an
  1953. * assumed manifest object schema).
  1954. *
  1955. * @param {Object} manifest
  1956. * The parsed manifest object
  1957. */
  1958. setupInitialPlaylist(manifest) {
  1959. this.state = 'HAVE_MAIN_MANIFEST';
  1960. if (manifest.playlists) {
  1961. this.main = manifest;
  1962. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  1963. // then resolve URIs in advance, as they are usually done after a playlist request,
  1964. // which may not happen if the playlist is resolved.
  1965. manifest.playlists.forEach(playlist => {
  1966. playlist.segments = getAllSegments(playlist);
  1967. playlist.segments.forEach(segment => {
  1968. resolveSegmentUris(segment, playlist.resolvedUri);
  1969. });
  1970. });
  1971. this.trigger('loadedplaylist');
  1972. if (!this.request) {
  1973. // no media playlist was specifically selected so start
  1974. // from the first listed one
  1975. this.media(this.main.playlists[0]);
  1976. }
  1977. return;
  1978. } // In order to support media playlists passed in as vhs-json, the case where the uri
  1979. // is not provided as part of the manifest should be considered, and an appropriate
  1980. // default used.
  1981. const uri = this.srcUri() || window$1.location.href;
  1982. this.main = mainForMedia(manifest, uri);
  1983. this.haveMetadata({
  1984. playlistObject: manifest,
  1985. url: uri,
  1986. id: this.main.playlists[0].id
  1987. });
  1988. this.trigger('loadedmetadata');
  1989. }
  1990. }
  1991. /**
  1992. * @file xhr.js
  1993. */
  1994. const {
  1995. xhr: videojsXHR
  1996. } = videojs;
  1997. const callbackWrapper = function (request, error, response, callback) {
  1998. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  1999. if (!error && reqResponse) {
  2000. request.responseTime = Date.now();
  2001. request.roundTripTime = request.responseTime - request.requestTime;
  2002. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  2003. if (!request.bandwidth) {
  2004. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  2005. }
  2006. }
  2007. if (response.headers) {
  2008. request.responseHeaders = response.headers;
  2009. } // videojs.xhr now uses a specific code on the error
  2010. // object to signal that a request has timed out instead
  2011. // of setting a boolean on the request object
  2012. if (error && error.code === 'ETIMEDOUT') {
  2013. request.timedout = true;
  2014. } // videojs.xhr no longer considers status codes outside of 200 and 0
  2015. // (for file uris) to be errors, but the old XHR did, so emulate that
  2016. // behavior. Status 206 may be used in response to byterange requests.
  2017. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  2018. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  2019. }
  2020. callback(error, request);
  2021. };
  2022. const xhrFactory = function () {
  2023. const xhr = function XhrFunction(options, callback) {
  2024. // Add a default timeout
  2025. options = merge({
  2026. timeout: 45e3
  2027. }, options); // Allow an optional user-specified function to modify the option
  2028. // object before we construct the xhr request
  2029. const beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  2030. if (beforeRequest && typeof beforeRequest === 'function') {
  2031. const newOptions = beforeRequest(options);
  2032. if (newOptions) {
  2033. options = newOptions;
  2034. }
  2035. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  2036. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  2037. const xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  2038. const request = xhrMethod(options, function (error, response) {
  2039. return callbackWrapper(request, error, response, callback);
  2040. });
  2041. const originalAbort = request.abort;
  2042. request.abort = function () {
  2043. request.aborted = true;
  2044. return originalAbort.apply(request, arguments);
  2045. };
  2046. request.uri = options.uri;
  2047. request.requestTime = Date.now();
  2048. return request;
  2049. };
  2050. xhr.original = true;
  2051. return xhr;
  2052. };
  2053. /**
  2054. * Turns segment byterange into a string suitable for use in
  2055. * HTTP Range requests
  2056. *
  2057. * @param {Object} byterange - an object with two values defining the start and end
  2058. * of a byte-range
  2059. */
  2060. const byterangeStr = function (byterange) {
  2061. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  2062. // header uses inclusive ranges
  2063. let byterangeEnd;
  2064. const byterangeStart = byterange.offset;
  2065. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  2066. byterangeEnd = window$1.BigInt(byterange.offset) + window$1.BigInt(byterange.length) - window$1.BigInt(1);
  2067. } else {
  2068. byterangeEnd = byterange.offset + byterange.length - 1;
  2069. }
  2070. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  2071. };
  2072. /**
  2073. * Defines headers for use in the xhr request for a particular segment.
  2074. *
  2075. * @param {Object} segment - a simplified copy of the segmentInfo object
  2076. * from SegmentLoader
  2077. */
  2078. const segmentXhrHeaders = function (segment) {
  2079. const headers = {};
  2080. if (segment.byterange) {
  2081. headers.Range = byterangeStr(segment.byterange);
  2082. }
  2083. return headers;
  2084. };
  2085. /**
  2086. * @file bin-utils.js
  2087. */
  2088. /**
  2089. * convert a TimeRange to text
  2090. *
  2091. * @param {TimeRange} range the timerange to use for conversion
  2092. * @param {number} i the iterator on the range to convert
  2093. * @return {string} the range in string format
  2094. */
  2095. const textRange = function (range, i) {
  2096. return range.start(i) + '-' + range.end(i);
  2097. };
  2098. /**
  2099. * format a number as hex string
  2100. *
  2101. * @param {number} e The number
  2102. * @param {number} i the iterator
  2103. * @return {string} the hex formatted number as a string
  2104. */
  2105. const formatHexString = function (e, i) {
  2106. const value = e.toString(16);
  2107. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  2108. };
  2109. const formatAsciiString = function (e) {
  2110. if (e >= 0x20 && e < 0x7e) {
  2111. return String.fromCharCode(e);
  2112. }
  2113. return '.';
  2114. };
  2115. /**
  2116. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  2117. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  2118. *
  2119. * @param {Object} message
  2120. * Object of properties and values to send to the web worker
  2121. * @return {Object}
  2122. * Modified message with TypedArray values expanded
  2123. * @function createTransferableMessage
  2124. */
  2125. const createTransferableMessage = function (message) {
  2126. const transferable = {};
  2127. Object.keys(message).forEach(key => {
  2128. const value = message[key];
  2129. if (isArrayBufferView(value)) {
  2130. transferable[key] = {
  2131. bytes: value.buffer,
  2132. byteOffset: value.byteOffset,
  2133. byteLength: value.byteLength
  2134. };
  2135. } else {
  2136. transferable[key] = value;
  2137. }
  2138. });
  2139. return transferable;
  2140. };
  2141. /**
  2142. * Returns a unique string identifier for a media initialization
  2143. * segment.
  2144. *
  2145. * @param {Object} initSegment
  2146. * the init segment object.
  2147. *
  2148. * @return {string} the generated init segment id
  2149. */
  2150. const initSegmentId = function (initSegment) {
  2151. const byterange = initSegment.byterange || {
  2152. length: Infinity,
  2153. offset: 0
  2154. };
  2155. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  2156. };
  2157. /**
  2158. * Returns a unique string identifier for a media segment key.
  2159. *
  2160. * @param {Object} key the encryption key
  2161. * @return {string} the unique id for the media segment key.
  2162. */
  2163. const segmentKeyId = function (key) {
  2164. return key.resolvedUri;
  2165. };
  2166. /**
  2167. * utils to help dump binary data to the console
  2168. *
  2169. * @param {Array|TypedArray} data
  2170. * data to dump to a string
  2171. *
  2172. * @return {string} the data as a hex string.
  2173. */
  2174. const hexDump = data => {
  2175. const bytes = Array.prototype.slice.call(data);
  2176. const step = 16;
  2177. let result = '';
  2178. let hex;
  2179. let ascii;
  2180. for (let j = 0; j < bytes.length / step; j++) {
  2181. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  2182. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  2183. result += hex + ' ' + ascii + '\n';
  2184. }
  2185. return result;
  2186. };
  2187. const tagDump = ({
  2188. bytes
  2189. }) => hexDump(bytes);
  2190. const textRanges = ranges => {
  2191. let result = '';
  2192. let i;
  2193. for (i = 0; i < ranges.length; i++) {
  2194. result += textRange(ranges, i) + ' ';
  2195. }
  2196. return result;
  2197. };
  2198. var utils = /*#__PURE__*/Object.freeze({
  2199. __proto__: null,
  2200. createTransferableMessage: createTransferableMessage,
  2201. initSegmentId: initSegmentId,
  2202. segmentKeyId: segmentKeyId,
  2203. hexDump: hexDump,
  2204. tagDump: tagDump,
  2205. textRanges: textRanges
  2206. });
  2207. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  2208. // 25% was arbitrarily chosen, and may need to be refined over time.
  2209. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  2210. /**
  2211. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  2212. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  2213. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  2214. *
  2215. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  2216. * point" (a point where we have a mapping from program time to player time, with player
  2217. * time being the post transmux start of the segment).
  2218. *
  2219. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  2220. *
  2221. * @param {number} playerTime the player time
  2222. * @param {Object} segment the segment which contains the player time
  2223. * @return {Date} program time
  2224. */
  2225. const playerTimeToProgramTime = (playerTime, segment) => {
  2226. if (!segment.dateTimeObject) {
  2227. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  2228. // be used to map the start of a segment with a real world time).
  2229. return null;
  2230. }
  2231. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  2232. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  2233. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  2234. const offsetFromSegmentStart = playerTime - startOfSegment;
  2235. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  2236. };
  2237. const originalSegmentVideoDuration = videoTimingInfo => {
  2238. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  2239. };
  2240. /**
  2241. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  2242. * returned segment might be an estimate or an accurate match.
  2243. *
  2244. * @param {string} programTime The ISO-8601 programTime to find a match for
  2245. * @param {Object} playlist A playlist object to search within
  2246. */
  2247. const findSegmentForProgramTime = (programTime, playlist) => {
  2248. // Assumptions:
  2249. // - verifyProgramDateTimeTags has already been run
  2250. // - live streams have been started
  2251. let dateTimeObject;
  2252. try {
  2253. dateTimeObject = new Date(programTime);
  2254. } catch (e) {
  2255. return null;
  2256. }
  2257. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2258. return null;
  2259. }
  2260. let segment = playlist.segments[0];
  2261. if (dateTimeObject < segment.dateTimeObject) {
  2262. // Requested time is before stream start.
  2263. return null;
  2264. }
  2265. for (let i = 0; i < playlist.segments.length - 1; i++) {
  2266. segment = playlist.segments[i];
  2267. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  2268. if (dateTimeObject < nextSegmentStart) {
  2269. break;
  2270. }
  2271. }
  2272. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2273. const lastSegmentStart = lastSegment.dateTimeObject;
  2274. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  2275. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  2276. if (dateTimeObject > lastSegmentEnd) {
  2277. // Beyond the end of the stream, or our best guess of the end of the stream.
  2278. return null;
  2279. }
  2280. if (dateTimeObject > lastSegmentStart) {
  2281. segment = lastSegment;
  2282. }
  2283. return {
  2284. segment,
  2285. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  2286. // Although, given that all segments have accurate date time objects, the segment
  2287. // selected should be accurate, unless the video has been transmuxed at some point
  2288. // (determined by the presence of the videoTimingInfo object), the segment's "player
  2289. // time" (the start time in the player) can't be considered accurate.
  2290. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2291. };
  2292. };
  2293. /**
  2294. * Finds a segment that contains the given player time(in seconds).
  2295. *
  2296. * @param {number} time The player time to find a match for
  2297. * @param {Object} playlist A playlist object to search within
  2298. */
  2299. const findSegmentForPlayerTime = (time, playlist) => {
  2300. // Assumptions:
  2301. // - there will always be a segment.duration
  2302. // - we can start from zero
  2303. // - segments are in time order
  2304. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2305. return null;
  2306. }
  2307. let segmentEnd = 0;
  2308. let segment;
  2309. for (let i = 0; i < playlist.segments.length; i++) {
  2310. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  2311. // should contain the most accurate values we have for the segment's player times.
  2312. //
  2313. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  2314. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  2315. // calculate an end value.
  2316. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  2317. if (time <= segmentEnd) {
  2318. break;
  2319. }
  2320. }
  2321. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2322. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  2323. // The time requested is beyond the stream end.
  2324. return null;
  2325. }
  2326. if (time > segmentEnd) {
  2327. // The time is within or beyond the last segment.
  2328. //
  2329. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  2330. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  2331. // Technically, because the duration value is only an estimate, the time may still
  2332. // exist in the last segment, however, there isn't enough information to make even
  2333. // a reasonable estimate.
  2334. return null;
  2335. }
  2336. segment = lastSegment;
  2337. }
  2338. return {
  2339. segment,
  2340. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  2341. // Because videoTimingInfo is only set after transmux, it is the only way to get
  2342. // accurate timing values.
  2343. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2344. };
  2345. };
  2346. /**
  2347. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  2348. * If the offset returned is positive, the programTime occurs after the
  2349. * comparisonTimestamp.
  2350. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  2351. *
  2352. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  2353. * @param {string} programTime The programTime as an ISO-8601 string
  2354. * @return {number} offset
  2355. */
  2356. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  2357. let segmentDateTime;
  2358. let programDateTime;
  2359. try {
  2360. segmentDateTime = new Date(comparisonTimeStamp);
  2361. programDateTime = new Date(programTime);
  2362. } catch (e) {// TODO handle error
  2363. }
  2364. const segmentTimeEpoch = segmentDateTime.getTime();
  2365. const programTimeEpoch = programDateTime.getTime();
  2366. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  2367. };
  2368. /**
  2369. * Checks that all segments in this playlist have programDateTime tags.
  2370. *
  2371. * @param {Object} playlist A playlist object
  2372. */
  2373. const verifyProgramDateTimeTags = playlist => {
  2374. if (!playlist.segments || playlist.segments.length === 0) {
  2375. return false;
  2376. }
  2377. for (let i = 0; i < playlist.segments.length; i++) {
  2378. const segment = playlist.segments[i];
  2379. if (!segment.dateTimeObject) {
  2380. return false;
  2381. }
  2382. }
  2383. return true;
  2384. };
  2385. /**
  2386. * Returns the programTime of the media given a playlist and a playerTime.
  2387. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  2388. * If the segments containing the time requested have not been buffered yet, an estimate
  2389. * may be returned to the callback.
  2390. *
  2391. * @param {Object} args
  2392. * @param {Object} args.playlist A playlist object to search within
  2393. * @param {number} time A playerTime in seconds
  2394. * @param {Function} callback(err, programTime)
  2395. * @return {string} err.message A detailed error message
  2396. * @return {Object} programTime
  2397. * @return {number} programTime.mediaSeconds The streamTime in seconds
  2398. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  2399. */
  2400. const getProgramTime = ({
  2401. playlist,
  2402. time = undefined,
  2403. callback
  2404. }) => {
  2405. if (!callback) {
  2406. throw new Error('getProgramTime: callback must be provided');
  2407. }
  2408. if (!playlist || time === undefined) {
  2409. return callback({
  2410. message: 'getProgramTime: playlist and time must be provided'
  2411. });
  2412. }
  2413. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  2414. if (!matchedSegment) {
  2415. return callback({
  2416. message: 'valid programTime was not found'
  2417. });
  2418. }
  2419. if (matchedSegment.type === 'estimate') {
  2420. return callback({
  2421. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  2422. seekTime: matchedSegment.estimatedStart
  2423. });
  2424. }
  2425. const programTimeObject = {
  2426. mediaSeconds: time
  2427. };
  2428. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  2429. if (programTime) {
  2430. programTimeObject.programDateTime = programTime.toISOString();
  2431. }
  2432. return callback(null, programTimeObject);
  2433. };
  2434. /**
  2435. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  2436. *
  2437. * @param {Object} args
  2438. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  2439. * @param {Object} args.playlist A playlist to look within
  2440. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  2441. * @param {Function} args.seekTo A method to perform a seek
  2442. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  2443. * @param {Object} args.tech The tech to seek on
  2444. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  2445. * @return {string} err.message A detailed error message
  2446. * @return {number} newTime The exact time that was seeked to in seconds
  2447. */
  2448. const seekToProgramTime = ({
  2449. programTime,
  2450. playlist,
  2451. retryCount = 2,
  2452. seekTo,
  2453. pauseAfterSeek = true,
  2454. tech,
  2455. callback
  2456. }) => {
  2457. if (!callback) {
  2458. throw new Error('seekToProgramTime: callback must be provided');
  2459. }
  2460. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  2461. return callback({
  2462. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  2463. });
  2464. }
  2465. if (!playlist.endList && !tech.hasStarted_) {
  2466. return callback({
  2467. message: 'player must be playing a live stream to start buffering'
  2468. });
  2469. }
  2470. if (!verifyProgramDateTimeTags(playlist)) {
  2471. return callback({
  2472. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  2473. });
  2474. }
  2475. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  2476. if (!matchedSegment) {
  2477. return callback({
  2478. message: `${programTime} was not found in the stream`
  2479. });
  2480. }
  2481. const segment = matchedSegment.segment;
  2482. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  2483. if (matchedSegment.type === 'estimate') {
  2484. // we've run out of retries
  2485. if (retryCount === 0) {
  2486. return callback({
  2487. message: `${programTime} is not buffered yet. Try again`
  2488. });
  2489. }
  2490. seekTo(matchedSegment.estimatedStart + mediaOffset);
  2491. tech.one('seeked', () => {
  2492. seekToProgramTime({
  2493. programTime,
  2494. playlist,
  2495. retryCount: retryCount - 1,
  2496. seekTo,
  2497. pauseAfterSeek,
  2498. tech,
  2499. callback
  2500. });
  2501. });
  2502. return;
  2503. } // Since the segment.start value is determined from the buffered end or ending time
  2504. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  2505. // modifications.
  2506. const seekToTime = segment.start + mediaOffset;
  2507. const seekedCallback = () => {
  2508. return callback(null, tech.currentTime());
  2509. }; // listen for seeked event
  2510. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  2511. if (pauseAfterSeek) {
  2512. tech.pause();
  2513. }
  2514. seekTo(seekToTime);
  2515. };
  2516. // which will only happen if the request is complete.
  2517. const callbackOnCompleted = (request, cb) => {
  2518. if (request.readyState === 4) {
  2519. return cb();
  2520. }
  2521. return;
  2522. };
  2523. const containerRequest = (uri, xhr, cb) => {
  2524. let bytes = [];
  2525. let id3Offset;
  2526. let finished = false;
  2527. const endRequestAndCallback = function (err, req, type, _bytes) {
  2528. req.abort();
  2529. finished = true;
  2530. return cb(err, req, type, _bytes);
  2531. };
  2532. const progressListener = function (error, request) {
  2533. if (finished) {
  2534. return;
  2535. }
  2536. if (error) {
  2537. return endRequestAndCallback(error, request, '', bytes);
  2538. } // grap the new part of content that was just downloaded
  2539. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  2540. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  2541. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  2542. // or we need at least two bytes after an id3Offset
  2543. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  2544. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2545. }
  2546. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  2547. // to see the second sync byte, wait until we have enough data
  2548. // before declaring it ts
  2549. if (type === 'ts' && bytes.length < 188) {
  2550. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2551. } // this may be an unsynced ts segment
  2552. // wait for 376 bytes before detecting no container
  2553. if (!type && bytes.length < 376) {
  2554. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2555. }
  2556. return endRequestAndCallback(null, request, type, bytes);
  2557. };
  2558. const options = {
  2559. uri,
  2560. beforeSend(request) {
  2561. // this forces the browser to pass the bytes to us unprocessed
  2562. request.overrideMimeType('text/plain; charset=x-user-defined');
  2563. request.addEventListener('progress', function ({
  2564. total,
  2565. loaded
  2566. }) {
  2567. return callbackWrapper(request, null, {
  2568. statusCode: request.status
  2569. }, progressListener);
  2570. });
  2571. }
  2572. };
  2573. const request = xhr(options, function (error, response) {
  2574. return callbackWrapper(request, error, response, progressListener);
  2575. });
  2576. return request;
  2577. };
  2578. const {
  2579. EventTarget
  2580. } = videojs;
  2581. const dashPlaylistUnchanged = function (a, b) {
  2582. if (!isPlaylistUnchanged(a, b)) {
  2583. return false;
  2584. } // for dash the above check will often return true in scenarios where
  2585. // the playlist actually has changed because mediaSequence isn't a
  2586. // dash thing, and we often set it to 1. So if the playlists have the same amount
  2587. // of segments we return true.
  2588. // So for dash we need to make sure that the underlying segments are different.
  2589. // if sidx changed then the playlists are different.
  2590. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  2591. return false;
  2592. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  2593. return false;
  2594. } // one or the other does not have segments
  2595. // there was a change.
  2596. if (a.segments && !b.segments || !a.segments && b.segments) {
  2597. return false;
  2598. } // neither has segments nothing changed
  2599. if (!a.segments && !b.segments) {
  2600. return true;
  2601. } // check segments themselves
  2602. for (let i = 0; i < a.segments.length; i++) {
  2603. const aSegment = a.segments[i];
  2604. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  2605. if (aSegment.uri !== bSegment.uri) {
  2606. return false;
  2607. } // neither segment has a byterange, there will be no byterange change.
  2608. if (!aSegment.byterange && !bSegment.byterange) {
  2609. continue;
  2610. }
  2611. const aByterange = aSegment.byterange;
  2612. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  2613. if (aByterange && !bByterange || !aByterange && bByterange) {
  2614. return false;
  2615. } // if both segments have byterange with different offsets, there was a change.
  2616. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  2617. return false;
  2618. }
  2619. } // if everything was the same with segments, this is the same playlist.
  2620. return true;
  2621. };
  2622. /**
  2623. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  2624. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  2625. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  2626. * periods without continuous playback this function may need modification as well as the parser.
  2627. */
  2628. const dashGroupId = (type, group, label, playlist) => {
  2629. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  2630. const playlistId = playlist.attributes.NAME || label;
  2631. return `placeholder-uri-${type}-${group}-${playlistId}`;
  2632. };
  2633. /**
  2634. * Parses the main XML string and updates playlist URI references.
  2635. *
  2636. * @param {Object} config
  2637. * Object of arguments
  2638. * @param {string} config.mainXml
  2639. * The mpd XML
  2640. * @param {string} config.srcUrl
  2641. * The mpd URL
  2642. * @param {Date} config.clientOffset
  2643. * A time difference between server and client
  2644. * @param {Object} config.sidxMapping
  2645. * SIDX mappings for moof/mdat URIs and byte ranges
  2646. * @return {Object}
  2647. * The parsed mpd manifest object
  2648. */
  2649. const parseMainXml = ({
  2650. mainXml,
  2651. srcUrl,
  2652. clientOffset,
  2653. sidxMapping,
  2654. previousManifest
  2655. }) => {
  2656. const manifest = parse(mainXml, {
  2657. manifestUri: srcUrl,
  2658. clientOffset,
  2659. sidxMapping,
  2660. previousManifest
  2661. });
  2662. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  2663. return manifest;
  2664. };
  2665. /**
  2666. * Removes any mediaGroup labels that no longer exist in the newMain
  2667. *
  2668. * @param {Object} update
  2669. * The previous mpd object being updated
  2670. * @param {Object} newMain
  2671. * The new mpd object
  2672. */
  2673. const removeOldMediaGroupLabels = (update, newMain) => {
  2674. forEachMediaGroup(update, (properties, type, group, label) => {
  2675. if (!(label in newMain.mediaGroups[type][group])) {
  2676. delete update.mediaGroups[type][group][label];
  2677. }
  2678. });
  2679. };
  2680. /**
  2681. * Returns a new main manifest that is the result of merging an updated main manifest
  2682. * into the original version.
  2683. *
  2684. * @param {Object} oldMain
  2685. * The old parsed mpd object
  2686. * @param {Object} newMain
  2687. * The updated parsed mpd object
  2688. * @return {Object}
  2689. * A new object representing the original main manifest with the updated media
  2690. * playlists merged in
  2691. */
  2692. const updateMain = (oldMain, newMain, sidxMapping) => {
  2693. let noChanges = true;
  2694. let update = merge(oldMain, {
  2695. // These are top level properties that can be updated
  2696. duration: newMain.duration,
  2697. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  2698. timelineStarts: newMain.timelineStarts
  2699. }); // First update the playlists in playlist list
  2700. for (let i = 0; i < newMain.playlists.length; i++) {
  2701. const playlist = newMain.playlists[i];
  2702. if (playlist.sidx) {
  2703. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  2704. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  2705. addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  2706. }
  2707. }
  2708. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  2709. if (playlistUpdate) {
  2710. update = playlistUpdate;
  2711. noChanges = false;
  2712. }
  2713. } // Then update media group playlists
  2714. forEachMediaGroup(newMain, (properties, type, group, label) => {
  2715. if (properties.playlists && properties.playlists.length) {
  2716. const id = properties.playlists[0].id;
  2717. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  2718. if (playlistUpdate) {
  2719. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  2720. if (!(label in update.mediaGroups[type][group])) {
  2721. update.mediaGroups[type][group][label] = properties;
  2722. } // update the playlist reference within media groups
  2723. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  2724. noChanges = false;
  2725. }
  2726. }
  2727. }); // remove mediaGroup labels and references that no longer exist in the newMain
  2728. removeOldMediaGroupLabels(update, newMain);
  2729. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  2730. noChanges = false;
  2731. }
  2732. if (noChanges) {
  2733. return null;
  2734. }
  2735. return update;
  2736. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  2737. // If the SIDXs have maps, the two maps should match,
  2738. // both `a` and `b` missing SIDXs is considered matching.
  2739. // If `a` or `b` but not both have a map, they aren't matching.
  2740. const equivalentSidx = (a, b) => {
  2741. const neitherMap = Boolean(!a.map && !b.map);
  2742. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  2743. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  2744. }; // exported for testing
  2745. const compareSidxEntry = (playlists, oldSidxMapping) => {
  2746. const newSidxMapping = {};
  2747. for (const id in playlists) {
  2748. const playlist = playlists[id];
  2749. const currentSidxInfo = playlist.sidx;
  2750. if (currentSidxInfo) {
  2751. const key = generateSidxKey(currentSidxInfo);
  2752. if (!oldSidxMapping[key]) {
  2753. break;
  2754. }
  2755. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  2756. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  2757. newSidxMapping[key] = oldSidxMapping[key];
  2758. }
  2759. }
  2760. }
  2761. return newSidxMapping;
  2762. };
  2763. /**
  2764. * A function that filters out changed items as they need to be requested separately.
  2765. *
  2766. * The method is exported for testing
  2767. *
  2768. * @param {Object} main the parsed mpd XML returned via mpd-parser
  2769. * @param {Object} oldSidxMapping the SIDX to compare against
  2770. */
  2771. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  2772. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  2773. let mediaGroupSidx = videoSidx;
  2774. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  2775. if (properties.playlists && properties.playlists.length) {
  2776. const playlists = properties.playlists;
  2777. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  2778. }
  2779. });
  2780. return mediaGroupSidx;
  2781. };
  2782. class DashPlaylistLoader extends EventTarget {
  2783. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  2784. // playlist loader setups from media groups will expect to be able to pass a playlist
  2785. // (since there aren't external URLs to media playlists with DASH)
  2786. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  2787. super();
  2788. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  2789. if (!mainPlaylistLoader) {
  2790. this.isMain_ = true;
  2791. }
  2792. const {
  2793. withCredentials = false
  2794. } = options;
  2795. this.vhs_ = vhs;
  2796. this.withCredentials = withCredentials;
  2797. if (!srcUrlOrPlaylist) {
  2798. throw new Error('A non-empty playlist URL or object is required');
  2799. } // event naming?
  2800. this.on('minimumUpdatePeriod', () => {
  2801. this.refreshXml_();
  2802. }); // live playlist staleness timeout
  2803. this.on('mediaupdatetimeout', () => {
  2804. this.refreshMedia_(this.media().id);
  2805. });
  2806. this.state = 'HAVE_NOTHING';
  2807. this.loadedPlaylists_ = {};
  2808. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  2809. // The mainPlaylistLoader will be created with a string
  2810. if (this.isMain_) {
  2811. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  2812. // once multi-period is refactored
  2813. this.mainPlaylistLoader_.sidxMapping_ = {};
  2814. } else {
  2815. this.childPlaylist_ = srcUrlOrPlaylist;
  2816. }
  2817. }
  2818. requestErrored_(err, request, startingState) {
  2819. // disposed
  2820. if (!this.request) {
  2821. return true;
  2822. } // pending request is cleared
  2823. this.request = null;
  2824. if (err) {
  2825. // use the provided error object or create one
  2826. // based on the request/response
  2827. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  2828. status: request.status,
  2829. message: 'DASH request error at URL: ' + request.uri,
  2830. response: request.response,
  2831. // MEDIA_ERR_NETWORK
  2832. code: 2
  2833. };
  2834. if (startingState) {
  2835. this.state = startingState;
  2836. }
  2837. this.trigger('error');
  2838. return true;
  2839. }
  2840. }
  2841. /**
  2842. * Verify that the container of the sidx segment can be parsed
  2843. * and if it can, get and parse that segment.
  2844. */
  2845. addSidxSegments_(playlist, startingState, cb) {
  2846. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  2847. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  2848. // keep this function async
  2849. this.mediaRequest_ = window$1.setTimeout(() => cb(false), 0);
  2850. return;
  2851. } // resolve the segment URL relative to the playlist
  2852. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  2853. const fin = (err, request) => {
  2854. if (this.requestErrored_(err, request, startingState)) {
  2855. return;
  2856. }
  2857. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  2858. let sidx;
  2859. try {
  2860. sidx = parseSidx(toUint8(request.response).subarray(8));
  2861. } catch (e) {
  2862. // sidx parsing failed.
  2863. this.requestErrored_(e, request, startingState);
  2864. return;
  2865. }
  2866. sidxMapping[sidxKey] = {
  2867. sidxInfo: playlist.sidx,
  2868. sidx
  2869. };
  2870. addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  2871. return cb(true);
  2872. };
  2873. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  2874. if (err) {
  2875. return fin(err, request);
  2876. }
  2877. if (!container || container !== 'mp4') {
  2878. return fin({
  2879. status: request.status,
  2880. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  2881. // response is just bytes in this case
  2882. // but we really don't want to return that.
  2883. response: '',
  2884. playlist,
  2885. internal: true,
  2886. playlistExclusionDuration: Infinity,
  2887. // MEDIA_ERR_NETWORK
  2888. code: 2
  2889. }, request);
  2890. } // if we already downloaded the sidx bytes in the container request, use them
  2891. const {
  2892. offset,
  2893. length
  2894. } = playlist.sidx.byterange;
  2895. if (bytes.length >= length + offset) {
  2896. return fin(err, {
  2897. response: bytes.subarray(offset, offset + length),
  2898. status: request.status,
  2899. uri: request.uri
  2900. });
  2901. } // otherwise request sidx bytes
  2902. this.request = this.vhs_.xhr({
  2903. uri,
  2904. responseType: 'arraybuffer',
  2905. headers: segmentXhrHeaders({
  2906. byterange: playlist.sidx.byterange
  2907. })
  2908. }, fin);
  2909. });
  2910. }
  2911. dispose() {
  2912. this.trigger('dispose');
  2913. this.stopRequest();
  2914. this.loadedPlaylists_ = {};
  2915. window$1.clearTimeout(this.minimumUpdatePeriodTimeout_);
  2916. window$1.clearTimeout(this.mediaRequest_);
  2917. window$1.clearTimeout(this.mediaUpdateTimeout);
  2918. this.mediaUpdateTimeout = null;
  2919. this.mediaRequest_ = null;
  2920. this.minimumUpdatePeriodTimeout_ = null;
  2921. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  2922. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  2923. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  2924. }
  2925. this.off();
  2926. }
  2927. hasPendingRequest() {
  2928. return this.request || this.mediaRequest_;
  2929. }
  2930. stopRequest() {
  2931. if (this.request) {
  2932. const oldRequest = this.request;
  2933. this.request = null;
  2934. oldRequest.onreadystatechange = null;
  2935. oldRequest.abort();
  2936. }
  2937. }
  2938. media(playlist) {
  2939. // getter
  2940. if (!playlist) {
  2941. return this.media_;
  2942. } // setter
  2943. if (this.state === 'HAVE_NOTHING') {
  2944. throw new Error('Cannot switch media playlist from ' + this.state);
  2945. }
  2946. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  2947. if (typeof playlist === 'string') {
  2948. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  2949. throw new Error('Unknown playlist URI: ' + playlist);
  2950. }
  2951. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  2952. }
  2953. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  2954. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  2955. this.state = 'HAVE_METADATA';
  2956. this.media_ = playlist; // trigger media change if the active media has been updated
  2957. if (mediaChange) {
  2958. this.trigger('mediachanging');
  2959. this.trigger('mediachange');
  2960. }
  2961. return;
  2962. } // switching to the active playlist is a no-op
  2963. if (!mediaChange) {
  2964. return;
  2965. } // switching from an already loaded playlist
  2966. if (this.media_) {
  2967. this.trigger('mediachanging');
  2968. }
  2969. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  2970. // everything is ready just continue to haveMetadata
  2971. this.haveMetadata({
  2972. startingState,
  2973. playlist
  2974. });
  2975. });
  2976. }
  2977. haveMetadata({
  2978. startingState,
  2979. playlist
  2980. }) {
  2981. this.state = 'HAVE_METADATA';
  2982. this.loadedPlaylists_[playlist.id] = playlist;
  2983. this.mediaRequest_ = null; // This will trigger loadedplaylist
  2984. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  2985. // to resolve setup of media groups
  2986. if (startingState === 'HAVE_MAIN_MANIFEST') {
  2987. this.trigger('loadedmetadata');
  2988. } else {
  2989. // trigger media change if the active media has been updated
  2990. this.trigger('mediachange');
  2991. }
  2992. }
  2993. pause() {
  2994. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  2995. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  2996. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  2997. }
  2998. this.stopRequest();
  2999. window$1.clearTimeout(this.mediaUpdateTimeout);
  3000. this.mediaUpdateTimeout = null;
  3001. if (this.isMain_) {
  3002. window$1.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  3003. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  3004. }
  3005. if (this.state === 'HAVE_NOTHING') {
  3006. // If we pause the loader before any data has been retrieved, its as if we never
  3007. // started, so reset to an unstarted state.
  3008. this.started = false;
  3009. }
  3010. }
  3011. load(isFinalRendition) {
  3012. window$1.clearTimeout(this.mediaUpdateTimeout);
  3013. this.mediaUpdateTimeout = null;
  3014. const media = this.media();
  3015. if (isFinalRendition) {
  3016. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  3017. this.mediaUpdateTimeout = window$1.setTimeout(() => this.load(), delay);
  3018. return;
  3019. } // because the playlists are internal to the manifest, load should either load the
  3020. // main manifest, or do nothing but trigger an event
  3021. if (!this.started) {
  3022. this.start();
  3023. return;
  3024. }
  3025. if (media && !media.endList) {
  3026. // Check to see if this is the main loader and the MUP was cleared (this happens
  3027. // when the loader was paused). `media` should be set at this point since one is always
  3028. // set during `start()`.
  3029. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  3030. // Trigger minimumUpdatePeriod to refresh the main manifest
  3031. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  3032. this.updateMinimumUpdatePeriodTimeout_();
  3033. }
  3034. this.trigger('mediaupdatetimeout');
  3035. } else {
  3036. this.trigger('loadedplaylist');
  3037. }
  3038. }
  3039. start() {
  3040. this.started = true; // We don't need to request the main manifest again
  3041. // Call this asynchronously to match the xhr request behavior below
  3042. if (!this.isMain_) {
  3043. this.mediaRequest_ = window$1.setTimeout(() => this.haveMain_(), 0);
  3044. return;
  3045. }
  3046. this.requestMain_((req, mainChanged) => {
  3047. this.haveMain_();
  3048. if (!this.hasPendingRequest() && !this.media_) {
  3049. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  3050. }
  3051. });
  3052. }
  3053. requestMain_(cb) {
  3054. this.request = this.vhs_.xhr({
  3055. uri: this.mainPlaylistLoader_.srcUrl,
  3056. withCredentials: this.withCredentials
  3057. }, (error, req) => {
  3058. if (this.requestErrored_(error, req)) {
  3059. if (this.state === 'HAVE_NOTHING') {
  3060. this.started = false;
  3061. }
  3062. return;
  3063. }
  3064. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  3065. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  3066. if (req.responseHeaders && req.responseHeaders.date) {
  3067. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  3068. } else {
  3069. this.mainLoaded_ = Date.now();
  3070. }
  3071. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  3072. if (mainChanged) {
  3073. this.handleMain_();
  3074. this.syncClientServerClock_(() => {
  3075. return cb(req, mainChanged);
  3076. });
  3077. return;
  3078. }
  3079. return cb(req, mainChanged);
  3080. });
  3081. }
  3082. /**
  3083. * Parses the main xml for UTCTiming node to sync the client clock to the server
  3084. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  3085. *
  3086. * @param {Function} done
  3087. * Function to call when clock sync has completed
  3088. */
  3089. syncClientServerClock_(done) {
  3090. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  3091. // server clock
  3092. if (utcTiming === null) {
  3093. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3094. return done();
  3095. }
  3096. if (utcTiming.method === 'DIRECT') {
  3097. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  3098. return done();
  3099. }
  3100. this.request = this.vhs_.xhr({
  3101. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  3102. method: utcTiming.method,
  3103. withCredentials: this.withCredentials
  3104. }, (error, req) => {
  3105. // disposed
  3106. if (!this.request) {
  3107. return;
  3108. }
  3109. if (error) {
  3110. // sync request failed, fall back to using date header from mpd
  3111. // TODO: log warning
  3112. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3113. return done();
  3114. }
  3115. let serverTime;
  3116. if (utcTiming.method === 'HEAD') {
  3117. if (!req.responseHeaders || !req.responseHeaders.date) {
  3118. // expected date header not preset, fall back to using date header from mpd
  3119. // TODO: log warning
  3120. serverTime = this.mainLoaded_;
  3121. } else {
  3122. serverTime = Date.parse(req.responseHeaders.date);
  3123. }
  3124. } else {
  3125. serverTime = Date.parse(req.responseText);
  3126. }
  3127. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  3128. done();
  3129. });
  3130. }
  3131. haveMain_() {
  3132. this.state = 'HAVE_MAIN_MANIFEST';
  3133. if (this.isMain_) {
  3134. // We have the main playlist at this point, so
  3135. // trigger this to allow PlaylistController
  3136. // to make an initial playlist selection
  3137. this.trigger('loadedplaylist');
  3138. } else if (!this.media_) {
  3139. // no media playlist was specifically selected so select
  3140. // the one the child playlist loader was created with
  3141. this.media(this.childPlaylist_);
  3142. }
  3143. }
  3144. handleMain_() {
  3145. // clear media request
  3146. this.mediaRequest_ = null;
  3147. const oldMain = this.mainPlaylistLoader_.main;
  3148. let newMain = parseMainXml({
  3149. mainXml: this.mainPlaylistLoader_.mainXml_,
  3150. srcUrl: this.mainPlaylistLoader_.srcUrl,
  3151. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  3152. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  3153. previousManifest: oldMain
  3154. }); // if we have an old main to compare the new main against
  3155. if (oldMain) {
  3156. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  3157. } // only update main if we have a new main
  3158. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  3159. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  3160. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  3161. this.mainPlaylistLoader_.srcUrl = location;
  3162. }
  3163. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  3164. this.updateMinimumUpdatePeriodTimeout_();
  3165. }
  3166. return Boolean(newMain);
  3167. }
  3168. updateMinimumUpdatePeriodTimeout_() {
  3169. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  3170. // a new one will be added if needed.
  3171. if (mpl.createMupOnMedia_) {
  3172. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  3173. mpl.createMupOnMedia_ = null;
  3174. } // clear any pending timeouts
  3175. if (mpl.minimumUpdatePeriodTimeout_) {
  3176. window$1.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  3177. mpl.minimumUpdatePeriodTimeout_ = null;
  3178. }
  3179. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  3180. // MPD has no future validity, so a new one will need to be acquired when new
  3181. // media segments are to be made available. Thus, we use the target duration
  3182. // in this case
  3183. if (mup === 0) {
  3184. if (mpl.media()) {
  3185. mup = mpl.media().targetDuration * 1000;
  3186. } else {
  3187. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  3188. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  3189. }
  3190. } // if minimumUpdatePeriod is invalid or <= zero, which
  3191. // can happen when a live video becomes VOD. skip timeout
  3192. // creation.
  3193. if (typeof mup !== 'number' || mup <= 0) {
  3194. if (mup < 0) {
  3195. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  3196. }
  3197. return;
  3198. }
  3199. this.createMUPTimeout_(mup);
  3200. }
  3201. createMUPTimeout_(mup) {
  3202. const mpl = this.mainPlaylistLoader_;
  3203. mpl.minimumUpdatePeriodTimeout_ = window$1.setTimeout(() => {
  3204. mpl.minimumUpdatePeriodTimeout_ = null;
  3205. mpl.trigger('minimumUpdatePeriod');
  3206. mpl.createMUPTimeout_(mup);
  3207. }, mup);
  3208. }
  3209. /**
  3210. * Sends request to refresh the main xml and updates the parsed main manifest
  3211. */
  3212. refreshXml_() {
  3213. this.requestMain_((req, mainChanged) => {
  3214. if (!mainChanged) {
  3215. return;
  3216. }
  3217. if (this.media_) {
  3218. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  3219. } // This will filter out updated sidx info from the mapping
  3220. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  3221. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  3222. // TODO: do we need to reload the current playlist?
  3223. this.refreshMedia_(this.media().id);
  3224. });
  3225. });
  3226. }
  3227. /**
  3228. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  3229. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  3230. * from the main loader.
  3231. */
  3232. refreshMedia_(mediaID) {
  3233. if (!mediaID) {
  3234. throw new Error('refreshMedia_ must take a media id');
  3235. } // for main we have to reparse the main xml
  3236. // to re-create segments based on current timing values
  3237. // which may change media. We only skip updating the main manifest
  3238. // if this is the first time this.media_ is being set.
  3239. // as main was just parsed in that case.
  3240. if (this.media_ && this.isMain_) {
  3241. this.handleMain_();
  3242. }
  3243. const playlists = this.mainPlaylistLoader_.main.playlists;
  3244. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  3245. if (mediaChanged) {
  3246. this.media_ = playlists[mediaID];
  3247. } else {
  3248. this.trigger('playlistunchanged');
  3249. }
  3250. if (!this.mediaUpdateTimeout) {
  3251. const createMediaUpdateTimeout = () => {
  3252. if (this.media().endList) {
  3253. return;
  3254. }
  3255. this.mediaUpdateTimeout = window$1.setTimeout(() => {
  3256. this.trigger('mediaupdatetimeout');
  3257. createMediaUpdateTimeout();
  3258. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  3259. };
  3260. createMediaUpdateTimeout();
  3261. }
  3262. this.trigger('loadedplaylist');
  3263. }
  3264. }
  3265. var Config = {
  3266. GOAL_BUFFER_LENGTH: 30,
  3267. MAX_GOAL_BUFFER_LENGTH: 60,
  3268. BACK_BUFFER_LENGTH: 30,
  3269. GOAL_BUFFER_LENGTH_RATE: 1,
  3270. // 0.5 MB/s
  3271. INITIAL_BANDWIDTH: 4194304,
  3272. // A fudge factor to apply to advertised playlist bitrates to account for
  3273. // temporary flucations in client bandwidth
  3274. BANDWIDTH_VARIANCE: 1.2,
  3275. // How much of the buffer must be filled before we consider upswitching
  3276. BUFFER_LOW_WATER_LINE: 0,
  3277. MAX_BUFFER_LOW_WATER_LINE: 30,
  3278. // TODO: Remove this when experimentalBufferBasedABR is removed
  3279. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  3280. BUFFER_LOW_WATER_LINE_RATE: 1,
  3281. // If the buffer is greater than the high water line, we won't switch down
  3282. BUFFER_HIGH_WATER_LINE: 30
  3283. };
  3284. const stringToArrayBuffer = string => {
  3285. const view = new Uint8Array(new ArrayBuffer(string.length));
  3286. for (let i = 0; i < string.length; i++) {
  3287. view[i] = string.charCodeAt(i);
  3288. }
  3289. return view.buffer;
  3290. };
  3291. /* global Blob, BlobBuilder, Worker */
  3292. // unify worker interface
  3293. const browserWorkerPolyFill = function (workerObj) {
  3294. // node only supports on/off
  3295. workerObj.on = workerObj.addEventListener;
  3296. workerObj.off = workerObj.removeEventListener;
  3297. return workerObj;
  3298. };
  3299. const createObjectURL = function (str) {
  3300. try {
  3301. return URL.createObjectURL(new Blob([str], {
  3302. type: 'application/javascript'
  3303. }));
  3304. } catch (e) {
  3305. const blob = new BlobBuilder();
  3306. blob.append(str);
  3307. return URL.createObjectURL(blob.getBlob());
  3308. }
  3309. };
  3310. const factory = function (code) {
  3311. return function () {
  3312. const objectUrl = createObjectURL(code);
  3313. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  3314. worker.objURL = objectUrl;
  3315. const terminate = worker.terminate;
  3316. worker.on = worker.addEventListener;
  3317. worker.off = worker.removeEventListener;
  3318. worker.terminate = function () {
  3319. URL.revokeObjectURL(objectUrl);
  3320. return terminate.call(this);
  3321. };
  3322. return worker;
  3323. };
  3324. };
  3325. const transform = function (code) {
  3326. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  3327. };
  3328. const getWorkerString = function (fn) {
  3329. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  3330. };
  3331. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  3332. const workerCode$1 = transform(getWorkerString(function () {
  3333. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3334. /**
  3335. * mux.js
  3336. *
  3337. * Copyright (c) Brightcove
  3338. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3339. *
  3340. * A lightweight readable stream implemention that handles event dispatching.
  3341. * Objects that inherit from streams should call init in their constructors.
  3342. */
  3343. var Stream$8 = function () {
  3344. this.init = function () {
  3345. var listeners = {};
  3346. /**
  3347. * Add a listener for a specified event type.
  3348. * @param type {string} the event name
  3349. * @param listener {function} the callback to be invoked when an event of
  3350. * the specified type occurs
  3351. */
  3352. this.on = function (type, listener) {
  3353. if (!listeners[type]) {
  3354. listeners[type] = [];
  3355. }
  3356. listeners[type] = listeners[type].concat(listener);
  3357. };
  3358. /**
  3359. * Remove a listener for a specified event type.
  3360. * @param type {string} the event name
  3361. * @param listener {function} a function previously registered for this
  3362. * type of event through `on`
  3363. */
  3364. this.off = function (type, listener) {
  3365. var index;
  3366. if (!listeners[type]) {
  3367. return false;
  3368. }
  3369. index = listeners[type].indexOf(listener);
  3370. listeners[type] = listeners[type].slice();
  3371. listeners[type].splice(index, 1);
  3372. return index > -1;
  3373. };
  3374. /**
  3375. * Trigger an event of the specified type on this stream. Any additional
  3376. * arguments to this function are passed as parameters to event listeners.
  3377. * @param type {string} the event name
  3378. */
  3379. this.trigger = function (type) {
  3380. var callbacks, i, length, args;
  3381. callbacks = listeners[type];
  3382. if (!callbacks) {
  3383. return;
  3384. } // Slicing the arguments on every invocation of this method
  3385. // can add a significant amount of overhead. Avoid the
  3386. // intermediate object creation for the common case of a
  3387. // single callback argument
  3388. if (arguments.length === 2) {
  3389. length = callbacks.length;
  3390. for (i = 0; i < length; ++i) {
  3391. callbacks[i].call(this, arguments[1]);
  3392. }
  3393. } else {
  3394. args = [];
  3395. i = arguments.length;
  3396. for (i = 1; i < arguments.length; ++i) {
  3397. args.push(arguments[i]);
  3398. }
  3399. length = callbacks.length;
  3400. for (i = 0; i < length; ++i) {
  3401. callbacks[i].apply(this, args);
  3402. }
  3403. }
  3404. };
  3405. /**
  3406. * Destroys the stream and cleans up.
  3407. */
  3408. this.dispose = function () {
  3409. listeners = {};
  3410. };
  3411. };
  3412. };
  3413. /**
  3414. * Forwards all `data` events on this stream to the destination stream. The
  3415. * destination stream should provide a method `push` to receive the data
  3416. * events as they arrive.
  3417. * @param destination {stream} the stream that will receive all `data` events
  3418. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  3419. * when the current stream emits a 'done' event
  3420. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  3421. */
  3422. Stream$8.prototype.pipe = function (destination) {
  3423. this.on('data', function (data) {
  3424. destination.push(data);
  3425. });
  3426. this.on('done', function (flushSource) {
  3427. destination.flush(flushSource);
  3428. });
  3429. this.on('partialdone', function (flushSource) {
  3430. destination.partialFlush(flushSource);
  3431. });
  3432. this.on('endedtimeline', function (flushSource) {
  3433. destination.endTimeline(flushSource);
  3434. });
  3435. this.on('reset', function (flushSource) {
  3436. destination.reset(flushSource);
  3437. });
  3438. return destination;
  3439. }; // Default stream functions that are expected to be overridden to perform
  3440. // actual work. These are provided by the prototype as a sort of no-op
  3441. // implementation so that we don't have to check for their existence in the
  3442. // `pipe` function above.
  3443. Stream$8.prototype.push = function (data) {
  3444. this.trigger('data', data);
  3445. };
  3446. Stream$8.prototype.flush = function (flushSource) {
  3447. this.trigger('done', flushSource);
  3448. };
  3449. Stream$8.prototype.partialFlush = function (flushSource) {
  3450. this.trigger('partialdone', flushSource);
  3451. };
  3452. Stream$8.prototype.endTimeline = function (flushSource) {
  3453. this.trigger('endedtimeline', flushSource);
  3454. };
  3455. Stream$8.prototype.reset = function (flushSource) {
  3456. this.trigger('reset', flushSource);
  3457. };
  3458. var stream = Stream$8;
  3459. var MAX_UINT32$1 = Math.pow(2, 32);
  3460. var getUint64$3 = function (uint8) {
  3461. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  3462. var value;
  3463. if (dv.getBigUint64) {
  3464. value = dv.getBigUint64(0);
  3465. if (value < Number.MAX_SAFE_INTEGER) {
  3466. return Number(value);
  3467. }
  3468. return value;
  3469. }
  3470. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  3471. };
  3472. var numbers = {
  3473. getUint64: getUint64$3,
  3474. MAX_UINT32: MAX_UINT32$1
  3475. };
  3476. /**
  3477. * mux.js
  3478. *
  3479. * Copyright (c) Brightcove
  3480. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3481. *
  3482. * Functions that generate fragmented MP4s suitable for use with Media
  3483. * Source Extensions.
  3484. */
  3485. var MAX_UINT32 = numbers.MAX_UINT32;
  3486. 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
  3487. (function () {
  3488. var i;
  3489. types = {
  3490. avc1: [],
  3491. // codingname
  3492. avcC: [],
  3493. btrt: [],
  3494. dinf: [],
  3495. dref: [],
  3496. esds: [],
  3497. ftyp: [],
  3498. hdlr: [],
  3499. mdat: [],
  3500. mdhd: [],
  3501. mdia: [],
  3502. mfhd: [],
  3503. minf: [],
  3504. moof: [],
  3505. moov: [],
  3506. mp4a: [],
  3507. // codingname
  3508. mvex: [],
  3509. mvhd: [],
  3510. pasp: [],
  3511. sdtp: [],
  3512. smhd: [],
  3513. stbl: [],
  3514. stco: [],
  3515. stsc: [],
  3516. stsd: [],
  3517. stsz: [],
  3518. stts: [],
  3519. styp: [],
  3520. tfdt: [],
  3521. tfhd: [],
  3522. traf: [],
  3523. trak: [],
  3524. trun: [],
  3525. trex: [],
  3526. tkhd: [],
  3527. vmhd: []
  3528. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  3529. // don't throw an error
  3530. if (typeof Uint8Array === 'undefined') {
  3531. return;
  3532. }
  3533. for (i in types) {
  3534. if (types.hasOwnProperty(i)) {
  3535. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  3536. }
  3537. }
  3538. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  3539. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  3540. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  3541. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  3542. 0x00, 0x00, 0x00, // flags
  3543. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3544. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3545. 0x00, 0x00, 0x00, 0x00, // reserved
  3546. 0x00, 0x00, 0x00, 0x00, // reserved
  3547. 0x00, 0x00, 0x00, 0x00, // reserved
  3548. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3549. ]);
  3550. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  3551. 0x00, 0x00, 0x00, // flags
  3552. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3553. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3554. 0x00, 0x00, 0x00, 0x00, // reserved
  3555. 0x00, 0x00, 0x00, 0x00, // reserved
  3556. 0x00, 0x00, 0x00, 0x00, // reserved
  3557. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3558. ]);
  3559. HDLR_TYPES = {
  3560. video: VIDEO_HDLR,
  3561. audio: AUDIO_HDLR
  3562. };
  3563. DREF = new Uint8Array([0x00, // version 0
  3564. 0x00, 0x00, 0x00, // flags
  3565. 0x00, 0x00, 0x00, 0x01, // entry_count
  3566. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3567. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3568. 0x00, // version 0
  3569. 0x00, 0x00, 0x01 // entry_flags
  3570. ]);
  3571. SMHD = new Uint8Array([0x00, // version
  3572. 0x00, 0x00, 0x00, // flags
  3573. 0x00, 0x00, // balance, 0 means centered
  3574. 0x00, 0x00 // reserved
  3575. ]);
  3576. STCO = new Uint8Array([0x00, // version
  3577. 0x00, 0x00, 0x00, // flags
  3578. 0x00, 0x00, 0x00, 0x00 // entry_count
  3579. ]);
  3580. STSC = STCO;
  3581. STSZ = new Uint8Array([0x00, // version
  3582. 0x00, 0x00, 0x00, // flags
  3583. 0x00, 0x00, 0x00, 0x00, // sample_size
  3584. 0x00, 0x00, 0x00, 0x00 // sample_count
  3585. ]);
  3586. STTS = STCO;
  3587. VMHD = new Uint8Array([0x00, // version
  3588. 0x00, 0x00, 0x01, // flags
  3589. 0x00, 0x00, // graphicsmode
  3590. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  3591. ]);
  3592. })();
  3593. box = function (type) {
  3594. var payload = [],
  3595. size = 0,
  3596. i,
  3597. result,
  3598. view;
  3599. for (i = 1; i < arguments.length; i++) {
  3600. payload.push(arguments[i]);
  3601. }
  3602. i = payload.length; // calculate the total size we need to allocate
  3603. while (i--) {
  3604. size += payload[i].byteLength;
  3605. }
  3606. result = new Uint8Array(size + 8);
  3607. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  3608. view.setUint32(0, result.byteLength);
  3609. result.set(type, 4); // copy the payload into the result
  3610. for (i = 0, size = 8; i < payload.length; i++) {
  3611. result.set(payload[i], size);
  3612. size += payload[i].byteLength;
  3613. }
  3614. return result;
  3615. };
  3616. dinf = function () {
  3617. return box(types.dinf, box(types.dref, DREF));
  3618. };
  3619. esds = function (track) {
  3620. return box(types.esds, new Uint8Array([0x00, // version
  3621. 0x00, 0x00, 0x00, // flags
  3622. // ES_Descriptor
  3623. 0x03, // tag, ES_DescrTag
  3624. 0x19, // length
  3625. 0x00, 0x00, // ES_ID
  3626. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  3627. // DecoderConfigDescriptor
  3628. 0x04, // tag, DecoderConfigDescrTag
  3629. 0x11, // length
  3630. 0x40, // object type
  3631. 0x15, // streamType
  3632. 0x00, 0x06, 0x00, // bufferSizeDB
  3633. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  3634. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  3635. // DecoderSpecificInfo
  3636. 0x05, // tag, DecoderSpecificInfoTag
  3637. 0x02, // length
  3638. // ISO/IEC 14496-3, AudioSpecificConfig
  3639. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  3640. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  3641. ]));
  3642. };
  3643. ftyp = function () {
  3644. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  3645. };
  3646. hdlr = function (type) {
  3647. return box(types.hdlr, HDLR_TYPES[type]);
  3648. };
  3649. mdat = function (data) {
  3650. return box(types.mdat, data);
  3651. };
  3652. mdhd = function (track) {
  3653. var result = new Uint8Array([0x00, // version 0
  3654. 0x00, 0x00, 0x00, // flags
  3655. 0x00, 0x00, 0x00, 0x02, // creation_time
  3656. 0x00, 0x00, 0x00, 0x03, // modification_time
  3657. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3658. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  3659. 0x55, 0xc4, // 'und' language (undetermined)
  3660. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  3661. // defined. The sample rate can be parsed out of an ADTS header, for
  3662. // instance.
  3663. if (track.samplerate) {
  3664. result[12] = track.samplerate >>> 24 & 0xFF;
  3665. result[13] = track.samplerate >>> 16 & 0xFF;
  3666. result[14] = track.samplerate >>> 8 & 0xFF;
  3667. result[15] = track.samplerate & 0xFF;
  3668. }
  3669. return box(types.mdhd, result);
  3670. };
  3671. mdia = function (track) {
  3672. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  3673. };
  3674. mfhd = function (sequenceNumber) {
  3675. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  3676. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  3677. ]));
  3678. };
  3679. minf = function (track) {
  3680. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  3681. };
  3682. moof = function (sequenceNumber, tracks) {
  3683. var trackFragments = [],
  3684. i = tracks.length; // build traf boxes for each track fragment
  3685. while (i--) {
  3686. trackFragments[i] = traf(tracks[i]);
  3687. }
  3688. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  3689. };
  3690. /**
  3691. * Returns a movie box.
  3692. * @param tracks {array} the tracks associated with this movie
  3693. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  3694. */
  3695. moov = function (tracks) {
  3696. var i = tracks.length,
  3697. boxes = [];
  3698. while (i--) {
  3699. boxes[i] = trak(tracks[i]);
  3700. }
  3701. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  3702. };
  3703. mvex = function (tracks) {
  3704. var i = tracks.length,
  3705. boxes = [];
  3706. while (i--) {
  3707. boxes[i] = trex(tracks[i]);
  3708. }
  3709. return box.apply(null, [types.mvex].concat(boxes));
  3710. };
  3711. mvhd = function (duration) {
  3712. var bytes = new Uint8Array([0x00, // version 0
  3713. 0x00, 0x00, 0x00, // flags
  3714. 0x00, 0x00, 0x00, 0x01, // creation_time
  3715. 0x00, 0x00, 0x00, 0x02, // modification_time
  3716. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3717. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  3718. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  3719. 0x01, 0x00, // 1.0 volume
  3720. 0x00, 0x00, // reserved
  3721. 0x00, 0x00, 0x00, 0x00, // reserved
  3722. 0x00, 0x00, 0x00, 0x00, // reserved
  3723. 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
  3724. 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
  3725. 0xff, 0xff, 0xff, 0xff // next_track_ID
  3726. ]);
  3727. return box(types.mvhd, bytes);
  3728. };
  3729. sdtp = function (track) {
  3730. var samples = track.samples || [],
  3731. bytes = new Uint8Array(4 + samples.length),
  3732. flags,
  3733. i; // leave the full box header (4 bytes) all zero
  3734. // write the sample table
  3735. for (i = 0; i < samples.length; i++) {
  3736. flags = samples[i].flags;
  3737. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  3738. }
  3739. return box(types.sdtp, bytes);
  3740. };
  3741. stbl = function (track) {
  3742. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  3743. };
  3744. (function () {
  3745. var videoSample, audioSample;
  3746. stsd = function (track) {
  3747. return box(types.stsd, new Uint8Array([0x00, // version 0
  3748. 0x00, 0x00, 0x00, // flags
  3749. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  3750. };
  3751. videoSample = function (track) {
  3752. var sps = track.sps || [],
  3753. pps = track.pps || [],
  3754. sequenceParameterSets = [],
  3755. pictureParameterSets = [],
  3756. i,
  3757. avc1Box; // assemble the SPSs
  3758. for (i = 0; i < sps.length; i++) {
  3759. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  3760. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  3761. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  3762. } // assemble the PPSs
  3763. for (i = 0; i < pps.length; i++) {
  3764. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  3765. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  3766. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  3767. }
  3768. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3769. 0x00, 0x01, // data_reference_index
  3770. 0x00, 0x00, // pre_defined
  3771. 0x00, 0x00, // reserved
  3772. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  3773. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  3774. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  3775. 0x00, 0x48, 0x00, 0x00, // horizresolution
  3776. 0x00, 0x48, 0x00, 0x00, // vertresolution
  3777. 0x00, 0x00, 0x00, 0x00, // reserved
  3778. 0x00, 0x01, // frame_count
  3779. 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
  3780. 0x00, 0x18, // depth = 24
  3781. 0x11, 0x11 // pre_defined = -1
  3782. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  3783. track.profileIdc, // AVCProfileIndication
  3784. track.profileCompatibility, // profile_compatibility
  3785. track.levelIdc, // AVCLevelIndication
  3786. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  3787. ].concat([sps.length], // numOfSequenceParameterSets
  3788. sequenceParameterSets, // "SPS"
  3789. [pps.length], // numOfPictureParameterSets
  3790. pictureParameterSets // "PPS"
  3791. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  3792. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  3793. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  3794. ]))];
  3795. if (track.sarRatio) {
  3796. var hSpacing = track.sarRatio[0],
  3797. vSpacing = track.sarRatio[1];
  3798. 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])));
  3799. }
  3800. return box.apply(null, avc1Box);
  3801. };
  3802. audioSample = function (track) {
  3803. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  3804. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3805. 0x00, 0x01, // data_reference_index
  3806. // AudioSampleEntry, ISO/IEC 14496-12
  3807. 0x00, 0x00, 0x00, 0x00, // reserved
  3808. 0x00, 0x00, 0x00, 0x00, // reserved
  3809. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  3810. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  3811. 0x00, 0x00, // pre_defined
  3812. 0x00, 0x00, // reserved
  3813. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  3814. // MP4AudioSampleEntry, ISO/IEC 14496-14
  3815. ]), esds(track));
  3816. };
  3817. })();
  3818. tkhd = function (track) {
  3819. var result = new Uint8Array([0x00, // version 0
  3820. 0x00, 0x00, 0x07, // flags
  3821. 0x00, 0x00, 0x00, 0x00, // creation_time
  3822. 0x00, 0x00, 0x00, 0x00, // modification_time
  3823. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3824. 0x00, 0x00, 0x00, 0x00, // reserved
  3825. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  3826. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3827. 0x00, 0x00, // layer
  3828. 0x00, 0x00, // alternate_group
  3829. 0x01, 0x00, // non-audio track volume
  3830. 0x00, 0x00, // reserved
  3831. 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
  3832. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  3833. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  3834. ]);
  3835. return box(types.tkhd, result);
  3836. };
  3837. /**
  3838. * Generate a track fragment (traf) box. A traf box collects metadata
  3839. * about tracks in a movie fragment (moof) box.
  3840. */
  3841. traf = function (track) {
  3842. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  3843. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  3844. 0x00, 0x00, 0x3a, // flags
  3845. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3846. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  3847. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3848. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3849. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  3850. ]));
  3851. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  3852. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  3853. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  3854. 0x00, 0x00, 0x00, // flags
  3855. // baseMediaDecodeTime
  3856. 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
  3857. // the containing moof to the first payload byte of the associated
  3858. // mdat
  3859. dataOffset = 32 + // tfhd
  3860. 20 + // tfdt
  3861. 8 + // traf header
  3862. 16 + // mfhd
  3863. 8 + // moof header
  3864. 8; // mdat header
  3865. // audio tracks require less metadata
  3866. if (track.type === 'audio') {
  3867. trackFragmentRun = trun$1(track, dataOffset);
  3868. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  3869. } // video tracks should contain an independent and disposable samples
  3870. // box (sdtp)
  3871. // generate one and adjust offsets to match
  3872. sampleDependencyTable = sdtp(track);
  3873. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  3874. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  3875. };
  3876. /**
  3877. * Generate a track box.
  3878. * @param track {object} a track definition
  3879. * @return {Uint8Array} the track box
  3880. */
  3881. trak = function (track) {
  3882. track.duration = track.duration || 0xffffffff;
  3883. return box(types.trak, tkhd(track), mdia(track));
  3884. };
  3885. trex = function (track) {
  3886. var result = new Uint8Array([0x00, // version 0
  3887. 0x00, 0x00, 0x00, // flags
  3888. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3889. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  3890. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3891. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3892. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  3893. ]); // the last two bytes of default_sample_flags is the sample
  3894. // degradation priority, a hint about the importance of this sample
  3895. // relative to others. Lower the degradation priority for all sample
  3896. // types other than video.
  3897. if (track.type !== 'video') {
  3898. result[result.length - 1] = 0x00;
  3899. }
  3900. return box(types.trex, result);
  3901. };
  3902. (function () {
  3903. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  3904. // duration is present for the first sample, it will be present for
  3905. // all subsequent samples.
  3906. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  3907. trunHeader = function (samples, offset) {
  3908. var durationPresent = 0,
  3909. sizePresent = 0,
  3910. flagsPresent = 0,
  3911. compositionTimeOffset = 0; // trun flag constants
  3912. if (samples.length) {
  3913. if (samples[0].duration !== undefined) {
  3914. durationPresent = 0x1;
  3915. }
  3916. if (samples[0].size !== undefined) {
  3917. sizePresent = 0x2;
  3918. }
  3919. if (samples[0].flags !== undefined) {
  3920. flagsPresent = 0x4;
  3921. }
  3922. if (samples[0].compositionTimeOffset !== undefined) {
  3923. compositionTimeOffset = 0x8;
  3924. }
  3925. }
  3926. return [0x00, // version 0
  3927. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  3928. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  3929. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  3930. ];
  3931. };
  3932. videoTrun = function (track, offset) {
  3933. var bytesOffest, bytes, header, samples, sample, i;
  3934. samples = track.samples || [];
  3935. offset += 8 + 12 + 16 * samples.length;
  3936. header = trunHeader(samples, offset);
  3937. bytes = new Uint8Array(header.length + samples.length * 16);
  3938. bytes.set(header);
  3939. bytesOffest = header.length;
  3940. for (i = 0; i < samples.length; i++) {
  3941. sample = samples[i];
  3942. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  3943. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  3944. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  3945. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  3946. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  3947. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  3948. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  3949. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  3950. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  3951. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  3952. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  3953. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  3954. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  3955. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  3956. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  3957. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  3958. }
  3959. return box(types.trun, bytes);
  3960. };
  3961. audioTrun = function (track, offset) {
  3962. var bytes, bytesOffest, header, samples, sample, i;
  3963. samples = track.samples || [];
  3964. offset += 8 + 12 + 8 * samples.length;
  3965. header = trunHeader(samples, offset);
  3966. bytes = new Uint8Array(header.length + samples.length * 8);
  3967. bytes.set(header);
  3968. bytesOffest = header.length;
  3969. for (i = 0; i < samples.length; i++) {
  3970. sample = samples[i];
  3971. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  3972. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  3973. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  3974. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  3975. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  3976. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  3977. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  3978. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  3979. }
  3980. return box(types.trun, bytes);
  3981. };
  3982. trun$1 = function (track, offset) {
  3983. if (track.type === 'audio') {
  3984. return audioTrun(track, offset);
  3985. }
  3986. return videoTrun(track, offset);
  3987. };
  3988. })();
  3989. var mp4Generator = {
  3990. ftyp: ftyp,
  3991. mdat: mdat,
  3992. moof: moof,
  3993. moov: moov,
  3994. initSegment: function (tracks) {
  3995. var fileType = ftyp(),
  3996. movie = moov(tracks),
  3997. result;
  3998. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  3999. result.set(fileType);
  4000. result.set(movie, fileType.byteLength);
  4001. return result;
  4002. }
  4003. };
  4004. /**
  4005. * mux.js
  4006. *
  4007. * Copyright (c) Brightcove
  4008. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4009. */
  4010. // composed of the nal units that make up that frame
  4011. // Also keep track of cummulative data about the frame from the nal units such
  4012. // as the frame duration, starting pts, etc.
  4013. var groupNalsIntoFrames = function (nalUnits) {
  4014. var i,
  4015. currentNal,
  4016. currentFrame = [],
  4017. frames = []; // TODO added for LHLS, make sure this is OK
  4018. frames.byteLength = 0;
  4019. frames.nalCount = 0;
  4020. frames.duration = 0;
  4021. currentFrame.byteLength = 0;
  4022. for (i = 0; i < nalUnits.length; i++) {
  4023. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  4024. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  4025. // Since the very first nal unit is expected to be an AUD
  4026. // only push to the frames array when currentFrame is not empty
  4027. if (currentFrame.length) {
  4028. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  4029. frames.byteLength += currentFrame.byteLength;
  4030. frames.nalCount += currentFrame.length;
  4031. frames.duration += currentFrame.duration;
  4032. frames.push(currentFrame);
  4033. }
  4034. currentFrame = [currentNal];
  4035. currentFrame.byteLength = currentNal.data.byteLength;
  4036. currentFrame.pts = currentNal.pts;
  4037. currentFrame.dts = currentNal.dts;
  4038. } else {
  4039. // Specifically flag key frames for ease of use later
  4040. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  4041. currentFrame.keyFrame = true;
  4042. }
  4043. currentFrame.duration = currentNal.dts - currentFrame.dts;
  4044. currentFrame.byteLength += currentNal.data.byteLength;
  4045. currentFrame.push(currentNal);
  4046. }
  4047. } // For the last frame, use the duration of the previous frame if we
  4048. // have nothing better to go on
  4049. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  4050. currentFrame.duration = frames[frames.length - 1].duration;
  4051. } // Push the final frame
  4052. // TODO added for LHLS, make sure this is OK
  4053. frames.byteLength += currentFrame.byteLength;
  4054. frames.nalCount += currentFrame.length;
  4055. frames.duration += currentFrame.duration;
  4056. frames.push(currentFrame);
  4057. return frames;
  4058. }; // Convert an array of frames into an array of Gop with each Gop being composed
  4059. // of the frames that make up that Gop
  4060. // Also keep track of cummulative data about the Gop from the frames such as the
  4061. // Gop duration, starting pts, etc.
  4062. var groupFramesIntoGops = function (frames) {
  4063. var i,
  4064. currentFrame,
  4065. currentGop = [],
  4066. gops = []; // We must pre-set some of the values on the Gop since we
  4067. // keep running totals of these values
  4068. currentGop.byteLength = 0;
  4069. currentGop.nalCount = 0;
  4070. currentGop.duration = 0;
  4071. currentGop.pts = frames[0].pts;
  4072. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  4073. gops.byteLength = 0;
  4074. gops.nalCount = 0;
  4075. gops.duration = 0;
  4076. gops.pts = frames[0].pts;
  4077. gops.dts = frames[0].dts;
  4078. for (i = 0; i < frames.length; i++) {
  4079. currentFrame = frames[i];
  4080. if (currentFrame.keyFrame) {
  4081. // Since the very first frame is expected to be an keyframe
  4082. // only push to the gops array when currentGop is not empty
  4083. if (currentGop.length) {
  4084. gops.push(currentGop);
  4085. gops.byteLength += currentGop.byteLength;
  4086. gops.nalCount += currentGop.nalCount;
  4087. gops.duration += currentGop.duration;
  4088. }
  4089. currentGop = [currentFrame];
  4090. currentGop.nalCount = currentFrame.length;
  4091. currentGop.byteLength = currentFrame.byteLength;
  4092. currentGop.pts = currentFrame.pts;
  4093. currentGop.dts = currentFrame.dts;
  4094. currentGop.duration = currentFrame.duration;
  4095. } else {
  4096. currentGop.duration += currentFrame.duration;
  4097. currentGop.nalCount += currentFrame.length;
  4098. currentGop.byteLength += currentFrame.byteLength;
  4099. currentGop.push(currentFrame);
  4100. }
  4101. }
  4102. if (gops.length && currentGop.duration <= 0) {
  4103. currentGop.duration = gops[gops.length - 1].duration;
  4104. }
  4105. gops.byteLength += currentGop.byteLength;
  4106. gops.nalCount += currentGop.nalCount;
  4107. gops.duration += currentGop.duration; // push the final Gop
  4108. gops.push(currentGop);
  4109. return gops;
  4110. };
  4111. /*
  4112. * Search for the first keyframe in the GOPs and throw away all frames
  4113. * until that keyframe. Then extend the duration of the pulled keyframe
  4114. * and pull the PTS and DTS of the keyframe so that it covers the time
  4115. * range of the frames that were disposed.
  4116. *
  4117. * @param {Array} gops video GOPs
  4118. * @returns {Array} modified video GOPs
  4119. */
  4120. var extendFirstKeyFrame = function (gops) {
  4121. var currentGop;
  4122. if (!gops[0][0].keyFrame && gops.length > 1) {
  4123. // Remove the first GOP
  4124. currentGop = gops.shift();
  4125. gops.byteLength -= currentGop.byteLength;
  4126. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  4127. // first gop to cover the time period of the
  4128. // frames we just removed
  4129. gops[0][0].dts = currentGop.dts;
  4130. gops[0][0].pts = currentGop.pts;
  4131. gops[0][0].duration += currentGop.duration;
  4132. }
  4133. return gops;
  4134. };
  4135. /**
  4136. * Default sample object
  4137. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  4138. */
  4139. var createDefaultSample = function () {
  4140. return {
  4141. size: 0,
  4142. flags: {
  4143. isLeading: 0,
  4144. dependsOn: 1,
  4145. isDependedOn: 0,
  4146. hasRedundancy: 0,
  4147. degradationPriority: 0,
  4148. isNonSyncSample: 1
  4149. }
  4150. };
  4151. };
  4152. /*
  4153. * Collates information from a video frame into an object for eventual
  4154. * entry into an MP4 sample table.
  4155. *
  4156. * @param {Object} frame the video frame
  4157. * @param {Number} dataOffset the byte offset to position the sample
  4158. * @return {Object} object containing sample table info for a frame
  4159. */
  4160. var sampleForFrame = function (frame, dataOffset) {
  4161. var sample = createDefaultSample();
  4162. sample.dataOffset = dataOffset;
  4163. sample.compositionTimeOffset = frame.pts - frame.dts;
  4164. sample.duration = frame.duration;
  4165. sample.size = 4 * frame.length; // Space for nal unit size
  4166. sample.size += frame.byteLength;
  4167. if (frame.keyFrame) {
  4168. sample.flags.dependsOn = 2;
  4169. sample.flags.isNonSyncSample = 0;
  4170. }
  4171. return sample;
  4172. }; // generate the track's sample table from an array of gops
  4173. var generateSampleTable$1 = function (gops, baseDataOffset) {
  4174. var h,
  4175. i,
  4176. sample,
  4177. currentGop,
  4178. currentFrame,
  4179. dataOffset = baseDataOffset || 0,
  4180. samples = [];
  4181. for (h = 0; h < gops.length; h++) {
  4182. currentGop = gops[h];
  4183. for (i = 0; i < currentGop.length; i++) {
  4184. currentFrame = currentGop[i];
  4185. sample = sampleForFrame(currentFrame, dataOffset);
  4186. dataOffset += sample.size;
  4187. samples.push(sample);
  4188. }
  4189. }
  4190. return samples;
  4191. }; // generate the track's raw mdat data from an array of gops
  4192. var concatenateNalData = function (gops) {
  4193. var h,
  4194. i,
  4195. j,
  4196. currentGop,
  4197. currentFrame,
  4198. currentNal,
  4199. dataOffset = 0,
  4200. nalsByteLength = gops.byteLength,
  4201. numberOfNals = gops.nalCount,
  4202. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4203. data = new Uint8Array(totalByteLength),
  4204. view = new DataView(data.buffer); // For each Gop..
  4205. for (h = 0; h < gops.length; h++) {
  4206. currentGop = gops[h]; // For each Frame..
  4207. for (i = 0; i < currentGop.length; i++) {
  4208. currentFrame = currentGop[i]; // For each NAL..
  4209. for (j = 0; j < currentFrame.length; j++) {
  4210. currentNal = currentFrame[j];
  4211. view.setUint32(dataOffset, currentNal.data.byteLength);
  4212. dataOffset += 4;
  4213. data.set(currentNal.data, dataOffset);
  4214. dataOffset += currentNal.data.byteLength;
  4215. }
  4216. }
  4217. }
  4218. return data;
  4219. }; // generate the track's sample table from a frame
  4220. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  4221. var sample,
  4222. dataOffset = baseDataOffset || 0,
  4223. samples = [];
  4224. sample = sampleForFrame(frame, dataOffset);
  4225. samples.push(sample);
  4226. return samples;
  4227. }; // generate the track's raw mdat data from a frame
  4228. var concatenateNalDataForFrame = function (frame) {
  4229. var i,
  4230. currentNal,
  4231. dataOffset = 0,
  4232. nalsByteLength = frame.byteLength,
  4233. numberOfNals = frame.length,
  4234. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4235. data = new Uint8Array(totalByteLength),
  4236. view = new DataView(data.buffer); // For each NAL..
  4237. for (i = 0; i < frame.length; i++) {
  4238. currentNal = frame[i];
  4239. view.setUint32(dataOffset, currentNal.data.byteLength);
  4240. dataOffset += 4;
  4241. data.set(currentNal.data, dataOffset);
  4242. dataOffset += currentNal.data.byteLength;
  4243. }
  4244. return data;
  4245. };
  4246. var frameUtils$1 = {
  4247. groupNalsIntoFrames: groupNalsIntoFrames,
  4248. groupFramesIntoGops: groupFramesIntoGops,
  4249. extendFirstKeyFrame: extendFirstKeyFrame,
  4250. generateSampleTable: generateSampleTable$1,
  4251. concatenateNalData: concatenateNalData,
  4252. generateSampleTableForFrame: generateSampleTableForFrame,
  4253. concatenateNalDataForFrame: concatenateNalDataForFrame
  4254. };
  4255. /**
  4256. * mux.js
  4257. *
  4258. * Copyright (c) Brightcove
  4259. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4260. */
  4261. var highPrefix = [33, 16, 5, 32, 164, 27];
  4262. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  4263. var zeroFill = function (count) {
  4264. var a = [];
  4265. while (count--) {
  4266. a.push(0);
  4267. }
  4268. return a;
  4269. };
  4270. var makeTable = function (metaTable) {
  4271. return Object.keys(metaTable).reduce(function (obj, key) {
  4272. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  4273. return arr.concat(part);
  4274. }, []));
  4275. return obj;
  4276. }, {});
  4277. };
  4278. var silence;
  4279. var silence_1 = function () {
  4280. if (!silence) {
  4281. // Frames-of-silence to use for filling in missing AAC frames
  4282. var coneOfSilence = {
  4283. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  4284. 88200: [highPrefix, [231], zeroFill(170), [56]],
  4285. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  4286. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  4287. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  4288. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  4289. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  4290. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  4291. 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]],
  4292. 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]],
  4293. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  4294. };
  4295. silence = makeTable(coneOfSilence);
  4296. }
  4297. return silence;
  4298. };
  4299. /**
  4300. * mux.js
  4301. *
  4302. * Copyright (c) Brightcove
  4303. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4304. */
  4305. var ONE_SECOND_IN_TS$4 = 90000,
  4306. // 90kHz clock
  4307. secondsToVideoTs,
  4308. secondsToAudioTs,
  4309. videoTsToSeconds,
  4310. audioTsToSeconds,
  4311. audioTsToVideoTs,
  4312. videoTsToAudioTs,
  4313. metadataTsToSeconds;
  4314. secondsToVideoTs = function (seconds) {
  4315. return seconds * ONE_SECOND_IN_TS$4;
  4316. };
  4317. secondsToAudioTs = function (seconds, sampleRate) {
  4318. return seconds * sampleRate;
  4319. };
  4320. videoTsToSeconds = function (timestamp) {
  4321. return timestamp / ONE_SECOND_IN_TS$4;
  4322. };
  4323. audioTsToSeconds = function (timestamp, sampleRate) {
  4324. return timestamp / sampleRate;
  4325. };
  4326. audioTsToVideoTs = function (timestamp, sampleRate) {
  4327. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  4328. };
  4329. videoTsToAudioTs = function (timestamp, sampleRate) {
  4330. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  4331. };
  4332. /**
  4333. * Adjust ID3 tag or caption timing information by the timeline pts values
  4334. * (if keepOriginalTimestamps is false) and convert to seconds
  4335. */
  4336. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  4337. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  4338. };
  4339. var clock$2 = {
  4340. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  4341. secondsToVideoTs: secondsToVideoTs,
  4342. secondsToAudioTs: secondsToAudioTs,
  4343. videoTsToSeconds: videoTsToSeconds,
  4344. audioTsToSeconds: audioTsToSeconds,
  4345. audioTsToVideoTs: audioTsToVideoTs,
  4346. videoTsToAudioTs: videoTsToAudioTs,
  4347. metadataTsToSeconds: metadataTsToSeconds
  4348. };
  4349. /**
  4350. * mux.js
  4351. *
  4352. * Copyright (c) Brightcove
  4353. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4354. */
  4355. var coneOfSilence = silence_1;
  4356. var clock$1 = clock$2;
  4357. /**
  4358. * Sum the `byteLength` properties of the data in each AAC frame
  4359. */
  4360. var sumFrameByteLengths = function (array) {
  4361. var i,
  4362. currentObj,
  4363. sum = 0; // sum the byteLength's all each nal unit in the frame
  4364. for (i = 0; i < array.length; i++) {
  4365. currentObj = array[i];
  4366. sum += currentObj.data.byteLength;
  4367. }
  4368. return sum;
  4369. }; // Possibly pad (prefix) the audio track with silence if appending this track
  4370. // would lead to the introduction of a gap in the audio buffer
  4371. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  4372. var baseMediaDecodeTimeTs,
  4373. frameDuration = 0,
  4374. audioGapDuration = 0,
  4375. audioFillFrameCount = 0,
  4376. audioFillDuration = 0,
  4377. silentFrame,
  4378. i,
  4379. firstFrame;
  4380. if (!frames.length) {
  4381. return;
  4382. }
  4383. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  4384. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  4385. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  4386. // insert the shortest possible amount (audio gap or audio to video gap)
  4387. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  4388. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  4389. audioFillDuration = audioFillFrameCount * frameDuration;
  4390. } // don't attempt to fill gaps smaller than a single frame or larger
  4391. // than a half second
  4392. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  4393. return;
  4394. }
  4395. silentFrame = coneOfSilence()[track.samplerate];
  4396. if (!silentFrame) {
  4397. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  4398. // from the content instead
  4399. silentFrame = frames[0].data;
  4400. }
  4401. for (i = 0; i < audioFillFrameCount; i++) {
  4402. firstFrame = frames[0];
  4403. frames.splice(0, 0, {
  4404. data: silentFrame,
  4405. dts: firstFrame.dts - frameDuration,
  4406. pts: firstFrame.pts - frameDuration
  4407. });
  4408. }
  4409. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  4410. return audioFillDuration;
  4411. }; // If the audio segment extends before the earliest allowed dts
  4412. // value, remove AAC frames until starts at or after the earliest
  4413. // allowed DTS so that we don't end up with a negative baseMedia-
  4414. // DecodeTime for the audio track
  4415. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  4416. if (track.minSegmentDts >= earliestAllowedDts) {
  4417. return adtsFrames;
  4418. } // We will need to recalculate the earliest segment Dts
  4419. track.minSegmentDts = Infinity;
  4420. return adtsFrames.filter(function (currentFrame) {
  4421. // If this is an allowed frame, keep it and record it's Dts
  4422. if (currentFrame.dts >= earliestAllowedDts) {
  4423. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  4424. track.minSegmentPts = track.minSegmentDts;
  4425. return true;
  4426. } // Otherwise, discard it
  4427. return false;
  4428. });
  4429. }; // generate the track's raw mdat data from an array of frames
  4430. var generateSampleTable = function (frames) {
  4431. var i,
  4432. currentFrame,
  4433. samples = [];
  4434. for (i = 0; i < frames.length; i++) {
  4435. currentFrame = frames[i];
  4436. samples.push({
  4437. size: currentFrame.data.byteLength,
  4438. duration: 1024 // For AAC audio, all samples contain 1024 samples
  4439. });
  4440. }
  4441. return samples;
  4442. }; // generate the track's sample table from an array of frames
  4443. var concatenateFrameData = function (frames) {
  4444. var i,
  4445. currentFrame,
  4446. dataOffset = 0,
  4447. data = new Uint8Array(sumFrameByteLengths(frames));
  4448. for (i = 0; i < frames.length; i++) {
  4449. currentFrame = frames[i];
  4450. data.set(currentFrame.data, dataOffset);
  4451. dataOffset += currentFrame.data.byteLength;
  4452. }
  4453. return data;
  4454. };
  4455. var audioFrameUtils$1 = {
  4456. prefixWithSilence: prefixWithSilence,
  4457. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  4458. generateSampleTable: generateSampleTable,
  4459. concatenateFrameData: concatenateFrameData
  4460. };
  4461. /**
  4462. * mux.js
  4463. *
  4464. * Copyright (c) Brightcove
  4465. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4466. */
  4467. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  4468. /**
  4469. * Store information about the start and end of the track and the
  4470. * duration for each frame/sample we process in order to calculate
  4471. * the baseMediaDecodeTime
  4472. */
  4473. var collectDtsInfo = function (track, data) {
  4474. if (typeof data.pts === 'number') {
  4475. if (track.timelineStartInfo.pts === undefined) {
  4476. track.timelineStartInfo.pts = data.pts;
  4477. }
  4478. if (track.minSegmentPts === undefined) {
  4479. track.minSegmentPts = data.pts;
  4480. } else {
  4481. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  4482. }
  4483. if (track.maxSegmentPts === undefined) {
  4484. track.maxSegmentPts = data.pts;
  4485. } else {
  4486. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  4487. }
  4488. }
  4489. if (typeof data.dts === 'number') {
  4490. if (track.timelineStartInfo.dts === undefined) {
  4491. track.timelineStartInfo.dts = data.dts;
  4492. }
  4493. if (track.minSegmentDts === undefined) {
  4494. track.minSegmentDts = data.dts;
  4495. } else {
  4496. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  4497. }
  4498. if (track.maxSegmentDts === undefined) {
  4499. track.maxSegmentDts = data.dts;
  4500. } else {
  4501. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  4502. }
  4503. }
  4504. };
  4505. /**
  4506. * Clear values used to calculate the baseMediaDecodeTime between
  4507. * tracks
  4508. */
  4509. var clearDtsInfo = function (track) {
  4510. delete track.minSegmentDts;
  4511. delete track.maxSegmentDts;
  4512. delete track.minSegmentPts;
  4513. delete track.maxSegmentPts;
  4514. };
  4515. /**
  4516. * Calculate the track's baseMediaDecodeTime based on the earliest
  4517. * DTS the transmuxer has ever seen and the minimum DTS for the
  4518. * current track
  4519. * @param track {object} track metadata configuration
  4520. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  4521. * in the source; false to adjust the first segment to start at 0.
  4522. */
  4523. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  4524. var baseMediaDecodeTime,
  4525. scale,
  4526. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  4527. if (!keepOriginalTimestamps) {
  4528. minSegmentDts -= track.timelineStartInfo.dts;
  4529. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  4530. // we want the start of the first segment to be placed
  4531. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  4532. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  4533. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  4534. if (track.type === 'audio') {
  4535. // Audio has a different clock equal to the sampling_rate so we need to
  4536. // scale the PTS values into the clock rate of the track
  4537. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  4538. baseMediaDecodeTime *= scale;
  4539. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  4540. }
  4541. return baseMediaDecodeTime;
  4542. };
  4543. var trackDecodeInfo$1 = {
  4544. clearDtsInfo: clearDtsInfo,
  4545. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  4546. collectDtsInfo: collectDtsInfo
  4547. };
  4548. /**
  4549. * mux.js
  4550. *
  4551. * Copyright (c) Brightcove
  4552. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4553. *
  4554. * Reads in-band caption information from a video elementary
  4555. * stream. Captions must follow the CEA-708 standard for injection
  4556. * into an MPEG-2 transport streams.
  4557. * @see https://en.wikipedia.org/wiki/CEA-708
  4558. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  4559. */
  4560. // payload type field to indicate how they are to be
  4561. // interpreted. CEAS-708 caption content is always transmitted with
  4562. // payload type 0x04.
  4563. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  4564. RBSP_TRAILING_BITS = 128;
  4565. /**
  4566. * Parse a supplemental enhancement information (SEI) NAL unit.
  4567. * Stops parsing once a message of type ITU T T35 has been found.
  4568. *
  4569. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  4570. * @return {object} the parsed SEI payload
  4571. * @see Rec. ITU-T H.264, 7.3.2.3.1
  4572. */
  4573. var parseSei = function (bytes) {
  4574. var i = 0,
  4575. result = {
  4576. payloadType: -1,
  4577. payloadSize: 0
  4578. },
  4579. payloadType = 0,
  4580. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  4581. while (i < bytes.byteLength) {
  4582. // stop once we have hit the end of the sei_rbsp
  4583. if (bytes[i] === RBSP_TRAILING_BITS) {
  4584. break;
  4585. } // Parse payload type
  4586. while (bytes[i] === 0xFF) {
  4587. payloadType += 255;
  4588. i++;
  4589. }
  4590. payloadType += bytes[i++]; // Parse payload size
  4591. while (bytes[i] === 0xFF) {
  4592. payloadSize += 255;
  4593. i++;
  4594. }
  4595. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  4596. // there can only ever be one caption message in a frame's sei
  4597. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  4598. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  4599. if (userIdentifier === 'GA94') {
  4600. result.payloadType = payloadType;
  4601. result.payloadSize = payloadSize;
  4602. result.payload = bytes.subarray(i, i + payloadSize);
  4603. break;
  4604. } else {
  4605. result.payload = void 0;
  4606. }
  4607. } // skip the payload and parse the next message
  4608. i += payloadSize;
  4609. payloadType = 0;
  4610. payloadSize = 0;
  4611. }
  4612. return result;
  4613. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  4614. var parseUserData = function (sei) {
  4615. // itu_t_t35_contry_code must be 181 (United States) for
  4616. // captions
  4617. if (sei.payload[0] !== 181) {
  4618. return null;
  4619. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  4620. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  4621. return null;
  4622. } // the user_identifier should be "GA94" to indicate ATSC1 data
  4623. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  4624. return null;
  4625. } // finally, user_data_type_code should be 0x03 for caption data
  4626. if (sei.payload[7] !== 0x03) {
  4627. return null;
  4628. } // return the user_data_type_structure and strip the trailing
  4629. // marker bits
  4630. return sei.payload.subarray(8, sei.payload.length - 1);
  4631. }; // see CEA-708-D, section 4.4
  4632. var parseCaptionPackets = function (pts, userData) {
  4633. var results = [],
  4634. i,
  4635. count,
  4636. offset,
  4637. data; // if this is just filler, return immediately
  4638. if (!(userData[0] & 0x40)) {
  4639. return results;
  4640. } // parse out the cc_data_1 and cc_data_2 fields
  4641. count = userData[0] & 0x1f;
  4642. for (i = 0; i < count; i++) {
  4643. offset = i * 3;
  4644. data = {
  4645. type: userData[offset + 2] & 0x03,
  4646. pts: pts
  4647. }; // capture cc data when cc_valid is 1
  4648. if (userData[offset + 2] & 0x04) {
  4649. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  4650. results.push(data);
  4651. }
  4652. }
  4653. return results;
  4654. };
  4655. var discardEmulationPreventionBytes$1 = function (data) {
  4656. var length = data.byteLength,
  4657. emulationPreventionBytesPositions = [],
  4658. i = 1,
  4659. newLength,
  4660. newData; // Find all `Emulation Prevention Bytes`
  4661. while (i < length - 2) {
  4662. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  4663. emulationPreventionBytesPositions.push(i + 2);
  4664. i += 2;
  4665. } else {
  4666. i++;
  4667. }
  4668. } // If no Emulation Prevention Bytes were found just return the original
  4669. // array
  4670. if (emulationPreventionBytesPositions.length === 0) {
  4671. return data;
  4672. } // Create a new array to hold the NAL unit data
  4673. newLength = length - emulationPreventionBytesPositions.length;
  4674. newData = new Uint8Array(newLength);
  4675. var sourceIndex = 0;
  4676. for (i = 0; i < newLength; sourceIndex++, i++) {
  4677. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  4678. // Skip this byte
  4679. sourceIndex++; // Remove this position index
  4680. emulationPreventionBytesPositions.shift();
  4681. }
  4682. newData[i] = data[sourceIndex];
  4683. }
  4684. return newData;
  4685. }; // exports
  4686. var captionPacketParser = {
  4687. parseSei: parseSei,
  4688. parseUserData: parseUserData,
  4689. parseCaptionPackets: parseCaptionPackets,
  4690. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  4691. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  4692. };
  4693. /**
  4694. * mux.js
  4695. *
  4696. * Copyright (c) Brightcove
  4697. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4698. *
  4699. * Reads in-band caption information from a video elementary
  4700. * stream. Captions must follow the CEA-708 standard for injection
  4701. * into an MPEG-2 transport streams.
  4702. * @see https://en.wikipedia.org/wiki/CEA-708
  4703. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  4704. */
  4705. // Link To Transport
  4706. // -----------------
  4707. var Stream$7 = stream;
  4708. var cea708Parser = captionPacketParser;
  4709. var CaptionStream$2 = function (options) {
  4710. options = options || {};
  4711. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  4712. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  4713. this.captionPackets_ = [];
  4714. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  4715. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  4716. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  4717. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  4718. ];
  4719. if (this.parse708captions_) {
  4720. this.cc708Stream_ = new Cea708Stream({
  4721. captionServices: options.captionServices
  4722. }); // eslint-disable-line no-use-before-define
  4723. }
  4724. this.reset(); // forward data and done events from CCs to this CaptionStream
  4725. this.ccStreams_.forEach(function (cc) {
  4726. cc.on('data', this.trigger.bind(this, 'data'));
  4727. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  4728. cc.on('done', this.trigger.bind(this, 'done'));
  4729. }, this);
  4730. if (this.parse708captions_) {
  4731. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  4732. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  4733. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  4734. }
  4735. };
  4736. CaptionStream$2.prototype = new Stream$7();
  4737. CaptionStream$2.prototype.push = function (event) {
  4738. var sei, userData, newCaptionPackets; // only examine SEI NALs
  4739. if (event.nalUnitType !== 'sei_rbsp') {
  4740. return;
  4741. } // parse the sei
  4742. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  4743. if (!sei.payload) {
  4744. return;
  4745. } // ignore everything but user_data_registered_itu_t_t35
  4746. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  4747. return;
  4748. } // parse out the user data payload
  4749. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  4750. if (!userData) {
  4751. return;
  4752. } // Sometimes, the same segment # will be downloaded twice. To stop the
  4753. // caption data from being processed twice, we track the latest dts we've
  4754. // received and ignore everything with a dts before that. However, since
  4755. // data for a specific dts can be split across packets on either side of
  4756. // a segment boundary, we need to make sure we *don't* ignore the packets
  4757. // from the *next* segment that have dts === this.latestDts_. By constantly
  4758. // tracking the number of packets received with dts === this.latestDts_, we
  4759. // know how many should be ignored once we start receiving duplicates.
  4760. if (event.dts < this.latestDts_) {
  4761. // We've started getting older data, so set the flag.
  4762. this.ignoreNextEqualDts_ = true;
  4763. return;
  4764. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  4765. this.numSameDts_--;
  4766. if (!this.numSameDts_) {
  4767. // We've received the last duplicate packet, time to start processing again
  4768. this.ignoreNextEqualDts_ = false;
  4769. }
  4770. return;
  4771. } // parse out CC data packets and save them for later
  4772. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  4773. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  4774. if (this.latestDts_ !== event.dts) {
  4775. this.numSameDts_ = 0;
  4776. }
  4777. this.numSameDts_++;
  4778. this.latestDts_ = event.dts;
  4779. };
  4780. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  4781. this.ccStreams_.forEach(function (cc) {
  4782. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  4783. }, this);
  4784. };
  4785. CaptionStream$2.prototype.flushStream = function (flushType) {
  4786. // make sure we actually parsed captions before proceeding
  4787. if (!this.captionPackets_.length) {
  4788. this.flushCCStreams(flushType);
  4789. return;
  4790. } // In Chrome, the Array#sort function is not stable so add a
  4791. // presortIndex that we can use to ensure we get a stable-sort
  4792. this.captionPackets_.forEach(function (elem, idx) {
  4793. elem.presortIndex = idx;
  4794. }); // sort caption byte-pairs based on their PTS values
  4795. this.captionPackets_.sort(function (a, b) {
  4796. if (a.pts === b.pts) {
  4797. return a.presortIndex - b.presortIndex;
  4798. }
  4799. return a.pts - b.pts;
  4800. });
  4801. this.captionPackets_.forEach(function (packet) {
  4802. if (packet.type < 2) {
  4803. // Dispatch packet to the right Cea608Stream
  4804. this.dispatchCea608Packet(packet);
  4805. } else {
  4806. // Dispatch packet to the Cea708Stream
  4807. this.dispatchCea708Packet(packet);
  4808. }
  4809. }, this);
  4810. this.captionPackets_.length = 0;
  4811. this.flushCCStreams(flushType);
  4812. };
  4813. CaptionStream$2.prototype.flush = function () {
  4814. return this.flushStream('flush');
  4815. }; // Only called if handling partial data
  4816. CaptionStream$2.prototype.partialFlush = function () {
  4817. return this.flushStream('partialFlush');
  4818. };
  4819. CaptionStream$2.prototype.reset = function () {
  4820. this.latestDts_ = null;
  4821. this.ignoreNextEqualDts_ = false;
  4822. this.numSameDts_ = 0;
  4823. this.activeCea608Channel_ = [null, null];
  4824. this.ccStreams_.forEach(function (ccStream) {
  4825. ccStream.reset();
  4826. });
  4827. }; // From the CEA-608 spec:
  4828. /*
  4829. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  4830. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  4831. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  4832. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  4833. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  4834. * to switch to captioning or Text.
  4835. */
  4836. // With that in mind, we ignore any data between an XDS control code and a
  4837. // subsequent closed-captioning control code.
  4838. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  4839. // NOTE: packet.type is the CEA608 field
  4840. if (this.setsTextOrXDSActive(packet)) {
  4841. this.activeCea608Channel_[packet.type] = null;
  4842. } else if (this.setsChannel1Active(packet)) {
  4843. this.activeCea608Channel_[packet.type] = 0;
  4844. } else if (this.setsChannel2Active(packet)) {
  4845. this.activeCea608Channel_[packet.type] = 1;
  4846. }
  4847. if (this.activeCea608Channel_[packet.type] === null) {
  4848. // If we haven't received anything to set the active channel, or the
  4849. // packets are Text/XDS data, discard the data; we don't want jumbled
  4850. // captions
  4851. return;
  4852. }
  4853. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  4854. };
  4855. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  4856. return (packet.ccData & 0x7800) === 0x1000;
  4857. };
  4858. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  4859. return (packet.ccData & 0x7800) === 0x1800;
  4860. };
  4861. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  4862. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  4863. };
  4864. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  4865. if (this.parse708captions_) {
  4866. this.cc708Stream_.push(packet);
  4867. }
  4868. }; // ----------------------
  4869. // Session to Application
  4870. // ----------------------
  4871. // This hash maps special and extended character codes to their
  4872. // proper Unicode equivalent. The first one-byte key is just a
  4873. // non-standard character code. The two-byte keys that follow are
  4874. // the extended CEA708 character codes, along with the preceding
  4875. // 0x10 extended character byte to distinguish these codes from
  4876. // non-extended character codes. Every CEA708 character code that
  4877. // is not in this object maps directly to a standard unicode
  4878. // character code.
  4879. // The transparent space and non-breaking transparent space are
  4880. // technically not fully supported since there is no code to
  4881. // make them transparent, so they have normal non-transparent
  4882. // stand-ins.
  4883. // The special closed caption (CC) character isn't a standard
  4884. // unicode character, so a fairly similar unicode character was
  4885. // chosen in it's place.
  4886. var CHARACTER_TRANSLATION_708 = {
  4887. 0x7f: 0x266a,
  4888. // ♪
  4889. 0x1020: 0x20,
  4890. // Transparent Space
  4891. 0x1021: 0xa0,
  4892. // Nob-breaking Transparent Space
  4893. 0x1025: 0x2026,
  4894. // …
  4895. 0x102a: 0x0160,
  4896. // Š
  4897. 0x102c: 0x0152,
  4898. // Œ
  4899. 0x1030: 0x2588,
  4900. // █
  4901. 0x1031: 0x2018,
  4902. // ‘
  4903. 0x1032: 0x2019,
  4904. // ’
  4905. 0x1033: 0x201c,
  4906. // “
  4907. 0x1034: 0x201d,
  4908. // ”
  4909. 0x1035: 0x2022,
  4910. // •
  4911. 0x1039: 0x2122,
  4912. // ™
  4913. 0x103a: 0x0161,
  4914. // š
  4915. 0x103c: 0x0153,
  4916. // œ
  4917. 0x103d: 0x2120,
  4918. // ℠
  4919. 0x103f: 0x0178,
  4920. // Ÿ
  4921. 0x1076: 0x215b,
  4922. // ⅛
  4923. 0x1077: 0x215c,
  4924. // ⅜
  4925. 0x1078: 0x215d,
  4926. // ⅝
  4927. 0x1079: 0x215e,
  4928. // ⅞
  4929. 0x107a: 0x23d0,
  4930. // ⏐
  4931. 0x107b: 0x23a4,
  4932. // ⎤
  4933. 0x107c: 0x23a3,
  4934. // ⎣
  4935. 0x107d: 0x23af,
  4936. // ⎯
  4937. 0x107e: 0x23a6,
  4938. // ⎦
  4939. 0x107f: 0x23a1,
  4940. // ⎡
  4941. 0x10a0: 0x3138 // ㄸ (CC char)
  4942. };
  4943. var get708CharFromCode = function (code) {
  4944. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  4945. if (code & 0x1000 && code === newCode) {
  4946. // Invalid extended code
  4947. return '';
  4948. }
  4949. return String.fromCharCode(newCode);
  4950. };
  4951. var within708TextBlock = function (b) {
  4952. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  4953. };
  4954. var Cea708Window = function (windowNum) {
  4955. this.windowNum = windowNum;
  4956. this.reset();
  4957. };
  4958. Cea708Window.prototype.reset = function () {
  4959. this.clearText();
  4960. this.pendingNewLine = false;
  4961. this.winAttr = {};
  4962. this.penAttr = {};
  4963. this.penLoc = {};
  4964. this.penColor = {}; // These default values are arbitrary,
  4965. // defineWindow will usually override them
  4966. this.visible = 0;
  4967. this.rowLock = 0;
  4968. this.columnLock = 0;
  4969. this.priority = 0;
  4970. this.relativePositioning = 0;
  4971. this.anchorVertical = 0;
  4972. this.anchorHorizontal = 0;
  4973. this.anchorPoint = 0;
  4974. this.rowCount = 1;
  4975. this.virtualRowCount = this.rowCount + 1;
  4976. this.columnCount = 41;
  4977. this.windowStyle = 0;
  4978. this.penStyle = 0;
  4979. };
  4980. Cea708Window.prototype.getText = function () {
  4981. return this.rows.join('\n');
  4982. };
  4983. Cea708Window.prototype.clearText = function () {
  4984. this.rows = [''];
  4985. this.rowIdx = 0;
  4986. };
  4987. Cea708Window.prototype.newLine = function (pts) {
  4988. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  4989. this.beforeRowOverflow(pts);
  4990. }
  4991. if (this.rows.length > 0) {
  4992. this.rows.push('');
  4993. this.rowIdx++;
  4994. } // Show all virtual rows since there's no visible scrolling
  4995. while (this.rows.length > this.virtualRowCount) {
  4996. this.rows.shift();
  4997. this.rowIdx--;
  4998. }
  4999. };
  5000. Cea708Window.prototype.isEmpty = function () {
  5001. if (this.rows.length === 0) {
  5002. return true;
  5003. } else if (this.rows.length === 1) {
  5004. return this.rows[0] === '';
  5005. }
  5006. return false;
  5007. };
  5008. Cea708Window.prototype.addText = function (text) {
  5009. this.rows[this.rowIdx] += text;
  5010. };
  5011. Cea708Window.prototype.backspace = function () {
  5012. if (!this.isEmpty()) {
  5013. var row = this.rows[this.rowIdx];
  5014. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  5015. }
  5016. };
  5017. var Cea708Service = function (serviceNum, encoding, stream) {
  5018. this.serviceNum = serviceNum;
  5019. this.text = '';
  5020. this.currentWindow = new Cea708Window(-1);
  5021. this.windows = [];
  5022. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  5023. if (typeof encoding === 'string') {
  5024. this.createTextDecoder(encoding);
  5025. }
  5026. };
  5027. /**
  5028. * Initialize service windows
  5029. * Must be run before service use
  5030. *
  5031. * @param {Integer} pts PTS value
  5032. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  5033. */
  5034. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  5035. this.startPts = pts;
  5036. for (var win = 0; win < 8; win++) {
  5037. this.windows[win] = new Cea708Window(win);
  5038. if (typeof beforeRowOverflow === 'function') {
  5039. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  5040. }
  5041. }
  5042. };
  5043. /**
  5044. * Set current window of service to be affected by commands
  5045. *
  5046. * @param {Integer} windowNum Window number
  5047. */
  5048. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  5049. this.currentWindow = this.windows[windowNum];
  5050. };
  5051. /**
  5052. * Try to create a TextDecoder if it is natively supported
  5053. */
  5054. Cea708Service.prototype.createTextDecoder = function (encoding) {
  5055. if (typeof TextDecoder === 'undefined') {
  5056. this.stream.trigger('log', {
  5057. level: 'warn',
  5058. message: 'The `encoding` option is unsupported without TextDecoder support'
  5059. });
  5060. } else {
  5061. try {
  5062. this.textDecoder_ = new TextDecoder(encoding);
  5063. } catch (error) {
  5064. this.stream.trigger('log', {
  5065. level: 'warn',
  5066. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  5067. });
  5068. }
  5069. }
  5070. };
  5071. var Cea708Stream = function (options) {
  5072. options = options || {};
  5073. Cea708Stream.prototype.init.call(this);
  5074. var self = this;
  5075. var captionServices = options.captionServices || {};
  5076. var captionServiceEncodings = {};
  5077. var serviceProps; // Get service encodings from captionServices option block
  5078. Object.keys(captionServices).forEach(serviceName => {
  5079. serviceProps = captionServices[serviceName];
  5080. if (/^SERVICE/.test(serviceName)) {
  5081. captionServiceEncodings[serviceName] = serviceProps.encoding;
  5082. }
  5083. });
  5084. this.serviceEncodings = captionServiceEncodings;
  5085. this.current708Packet = null;
  5086. this.services = {};
  5087. this.push = function (packet) {
  5088. if (packet.type === 3) {
  5089. // 708 packet start
  5090. self.new708Packet();
  5091. self.add708Bytes(packet);
  5092. } else {
  5093. if (self.current708Packet === null) {
  5094. // This should only happen at the start of a file if there's no packet start.
  5095. self.new708Packet();
  5096. }
  5097. self.add708Bytes(packet);
  5098. }
  5099. };
  5100. };
  5101. Cea708Stream.prototype = new Stream$7();
  5102. /**
  5103. * Push current 708 packet, create new 708 packet.
  5104. */
  5105. Cea708Stream.prototype.new708Packet = function () {
  5106. if (this.current708Packet !== null) {
  5107. this.push708Packet();
  5108. }
  5109. this.current708Packet = {
  5110. data: [],
  5111. ptsVals: []
  5112. };
  5113. };
  5114. /**
  5115. * Add pts and both bytes from packet into current 708 packet.
  5116. */
  5117. Cea708Stream.prototype.add708Bytes = function (packet) {
  5118. var data = packet.ccData;
  5119. var byte0 = data >>> 8;
  5120. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  5121. // that service blocks will always line up with byte pairs.
  5122. this.current708Packet.ptsVals.push(packet.pts);
  5123. this.current708Packet.data.push(byte0);
  5124. this.current708Packet.data.push(byte1);
  5125. };
  5126. /**
  5127. * Parse completed 708 packet into service blocks and push each service block.
  5128. */
  5129. Cea708Stream.prototype.push708Packet = function () {
  5130. var packet708 = this.current708Packet;
  5131. var packetData = packet708.data;
  5132. var serviceNum = null;
  5133. var blockSize = null;
  5134. var i = 0;
  5135. var b = packetData[i++];
  5136. packet708.seq = b >> 6;
  5137. packet708.sizeCode = b & 0x3f; // 0b00111111;
  5138. for (; i < packetData.length; i++) {
  5139. b = packetData[i++];
  5140. serviceNum = b >> 5;
  5141. blockSize = b & 0x1f; // 0b00011111
  5142. if (serviceNum === 7 && blockSize > 0) {
  5143. // Extended service num
  5144. b = packetData[i++];
  5145. serviceNum = b;
  5146. }
  5147. this.pushServiceBlock(serviceNum, i, blockSize);
  5148. if (blockSize > 0) {
  5149. i += blockSize - 1;
  5150. }
  5151. }
  5152. };
  5153. /**
  5154. * Parse service block, execute commands, read text.
  5155. *
  5156. * Note: While many of these commands serve important purposes,
  5157. * many others just parse out the parameters or attributes, but
  5158. * nothing is done with them because this is not a full and complete
  5159. * implementation of the entire 708 spec.
  5160. *
  5161. * @param {Integer} serviceNum Service number
  5162. * @param {Integer} start Start index of the 708 packet data
  5163. * @param {Integer} size Block size
  5164. */
  5165. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  5166. var b;
  5167. var i = start;
  5168. var packetData = this.current708Packet.data;
  5169. var service = this.services[serviceNum];
  5170. if (!service) {
  5171. service = this.initService(serviceNum, i);
  5172. }
  5173. for (; i < start + size && i < packetData.length; i++) {
  5174. b = packetData[i];
  5175. if (within708TextBlock(b)) {
  5176. i = this.handleText(i, service);
  5177. } else if (b === 0x18) {
  5178. i = this.multiByteCharacter(i, service);
  5179. } else if (b === 0x10) {
  5180. i = this.extendedCommands(i, service);
  5181. } else if (0x80 <= b && b <= 0x87) {
  5182. i = this.setCurrentWindow(i, service);
  5183. } else if (0x98 <= b && b <= 0x9f) {
  5184. i = this.defineWindow(i, service);
  5185. } else if (b === 0x88) {
  5186. i = this.clearWindows(i, service);
  5187. } else if (b === 0x8c) {
  5188. i = this.deleteWindows(i, service);
  5189. } else if (b === 0x89) {
  5190. i = this.displayWindows(i, service);
  5191. } else if (b === 0x8a) {
  5192. i = this.hideWindows(i, service);
  5193. } else if (b === 0x8b) {
  5194. i = this.toggleWindows(i, service);
  5195. } else if (b === 0x97) {
  5196. i = this.setWindowAttributes(i, service);
  5197. } else if (b === 0x90) {
  5198. i = this.setPenAttributes(i, service);
  5199. } else if (b === 0x91) {
  5200. i = this.setPenColor(i, service);
  5201. } else if (b === 0x92) {
  5202. i = this.setPenLocation(i, service);
  5203. } else if (b === 0x8f) {
  5204. service = this.reset(i, service);
  5205. } else if (b === 0x08) {
  5206. // BS: Backspace
  5207. service.currentWindow.backspace();
  5208. } else if (b === 0x0c) {
  5209. // FF: Form feed
  5210. service.currentWindow.clearText();
  5211. } else if (b === 0x0d) {
  5212. // CR: Carriage return
  5213. service.currentWindow.pendingNewLine = true;
  5214. } else if (b === 0x0e) {
  5215. // HCR: Horizontal carriage return
  5216. service.currentWindow.clearText();
  5217. } else if (b === 0x8d) {
  5218. // DLY: Delay, nothing to do
  5219. i++;
  5220. } else ;
  5221. }
  5222. };
  5223. /**
  5224. * Execute an extended command
  5225. *
  5226. * @param {Integer} i Current index in the 708 packet
  5227. * @param {Service} service The service object to be affected
  5228. * @return {Integer} New index after parsing
  5229. */
  5230. Cea708Stream.prototype.extendedCommands = function (i, service) {
  5231. var packetData = this.current708Packet.data;
  5232. var b = packetData[++i];
  5233. if (within708TextBlock(b)) {
  5234. i = this.handleText(i, service, {
  5235. isExtended: true
  5236. });
  5237. }
  5238. return i;
  5239. };
  5240. /**
  5241. * Get PTS value of a given byte index
  5242. *
  5243. * @param {Integer} byteIndex Index of the byte
  5244. * @return {Integer} PTS
  5245. */
  5246. Cea708Stream.prototype.getPts = function (byteIndex) {
  5247. // There's 1 pts value per 2 bytes
  5248. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  5249. };
  5250. /**
  5251. * Initializes a service
  5252. *
  5253. * @param {Integer} serviceNum Service number
  5254. * @return {Service} Initialized service object
  5255. */
  5256. Cea708Stream.prototype.initService = function (serviceNum, i) {
  5257. var serviceName = 'SERVICE' + serviceNum;
  5258. var self = this;
  5259. var serviceName;
  5260. var encoding;
  5261. if (serviceName in this.serviceEncodings) {
  5262. encoding = this.serviceEncodings[serviceName];
  5263. }
  5264. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  5265. this.services[serviceNum].init(this.getPts(i), function (pts) {
  5266. self.flushDisplayed(pts, self.services[serviceNum]);
  5267. });
  5268. return this.services[serviceNum];
  5269. };
  5270. /**
  5271. * Execute text writing to current window
  5272. *
  5273. * @param {Integer} i Current index in the 708 packet
  5274. * @param {Service} service The service object to be affected
  5275. * @return {Integer} New index after parsing
  5276. */
  5277. Cea708Stream.prototype.handleText = function (i, service, options) {
  5278. var isExtended = options && options.isExtended;
  5279. var isMultiByte = options && options.isMultiByte;
  5280. var packetData = this.current708Packet.data;
  5281. var extended = isExtended ? 0x1000 : 0x0000;
  5282. var currentByte = packetData[i];
  5283. var nextByte = packetData[i + 1];
  5284. var win = service.currentWindow;
  5285. var char;
  5286. var charCodeArray; // Use the TextDecoder if one was created for this service
  5287. if (service.textDecoder_ && !isExtended) {
  5288. if (isMultiByte) {
  5289. charCodeArray = [currentByte, nextByte];
  5290. i++;
  5291. } else {
  5292. charCodeArray = [currentByte];
  5293. }
  5294. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  5295. } else {
  5296. char = get708CharFromCode(extended | currentByte);
  5297. }
  5298. if (win.pendingNewLine && !win.isEmpty()) {
  5299. win.newLine(this.getPts(i));
  5300. }
  5301. win.pendingNewLine = false;
  5302. win.addText(char);
  5303. return i;
  5304. };
  5305. /**
  5306. * Handle decoding of multibyte character
  5307. *
  5308. * @param {Integer} i Current index in the 708 packet
  5309. * @param {Service} service The service object to be affected
  5310. * @return {Integer} New index after parsing
  5311. */
  5312. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  5313. var packetData = this.current708Packet.data;
  5314. var firstByte = packetData[i + 1];
  5315. var secondByte = packetData[i + 2];
  5316. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  5317. i = this.handleText(++i, service, {
  5318. isMultiByte: true
  5319. });
  5320. }
  5321. return i;
  5322. };
  5323. /**
  5324. * Parse and execute the CW# command.
  5325. *
  5326. * Set the current window.
  5327. *
  5328. * @param {Integer} i Current index in the 708 packet
  5329. * @param {Service} service The service object to be affected
  5330. * @return {Integer} New index after parsing
  5331. */
  5332. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  5333. var packetData = this.current708Packet.data;
  5334. var b = packetData[i];
  5335. var windowNum = b & 0x07;
  5336. service.setCurrentWindow(windowNum);
  5337. return i;
  5338. };
  5339. /**
  5340. * Parse and execute the DF# command.
  5341. *
  5342. * Define a window and set it as the current window.
  5343. *
  5344. * @param {Integer} i Current index in the 708 packet
  5345. * @param {Service} service The service object to be affected
  5346. * @return {Integer} New index after parsing
  5347. */
  5348. Cea708Stream.prototype.defineWindow = function (i, service) {
  5349. var packetData = this.current708Packet.data;
  5350. var b = packetData[i];
  5351. var windowNum = b & 0x07;
  5352. service.setCurrentWindow(windowNum);
  5353. var win = service.currentWindow;
  5354. b = packetData[++i];
  5355. win.visible = (b & 0x20) >> 5; // v
  5356. win.rowLock = (b & 0x10) >> 4; // rl
  5357. win.columnLock = (b & 0x08) >> 3; // cl
  5358. win.priority = b & 0x07; // p
  5359. b = packetData[++i];
  5360. win.relativePositioning = (b & 0x80) >> 7; // rp
  5361. win.anchorVertical = b & 0x7f; // av
  5362. b = packetData[++i];
  5363. win.anchorHorizontal = b; // ah
  5364. b = packetData[++i];
  5365. win.anchorPoint = (b & 0xf0) >> 4; // ap
  5366. win.rowCount = b & 0x0f; // rc
  5367. b = packetData[++i];
  5368. win.columnCount = b & 0x3f; // cc
  5369. b = packetData[++i];
  5370. win.windowStyle = (b & 0x38) >> 3; // ws
  5371. win.penStyle = b & 0x07; // ps
  5372. // The spec says there are (rowCount+1) "virtual rows"
  5373. win.virtualRowCount = win.rowCount + 1;
  5374. return i;
  5375. };
  5376. /**
  5377. * Parse and execute the SWA command.
  5378. *
  5379. * Set attributes of the current window.
  5380. *
  5381. * @param {Integer} i Current index in the 708 packet
  5382. * @param {Service} service The service object to be affected
  5383. * @return {Integer} New index after parsing
  5384. */
  5385. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  5386. var packetData = this.current708Packet.data;
  5387. var b = packetData[i];
  5388. var winAttr = service.currentWindow.winAttr;
  5389. b = packetData[++i];
  5390. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  5391. winAttr.fillRed = (b & 0x30) >> 4; // fr
  5392. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  5393. winAttr.fillBlue = b & 0x03; // fb
  5394. b = packetData[++i];
  5395. winAttr.borderType = (b & 0xc0) >> 6; // bt
  5396. winAttr.borderRed = (b & 0x30) >> 4; // br
  5397. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  5398. winAttr.borderBlue = b & 0x03; // bb
  5399. b = packetData[++i];
  5400. winAttr.borderType += (b & 0x80) >> 5; // bt
  5401. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  5402. winAttr.printDirection = (b & 0x30) >> 4; // pd
  5403. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  5404. winAttr.justify = b & 0x03; // j
  5405. b = packetData[++i];
  5406. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  5407. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  5408. winAttr.displayEffect = b & 0x03; // de
  5409. return i;
  5410. };
  5411. /**
  5412. * Gather text from all displayed windows and push a caption to output.
  5413. *
  5414. * @param {Integer} i Current index in the 708 packet
  5415. * @param {Service} service The service object to be affected
  5416. */
  5417. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  5418. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  5419. // display text in the correct order, but sample files so far have not shown any issue.
  5420. for (var winId = 0; winId < 8; winId++) {
  5421. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  5422. displayedText.push(service.windows[winId].getText());
  5423. }
  5424. }
  5425. service.endPts = pts;
  5426. service.text = displayedText.join('\n\n');
  5427. this.pushCaption(service);
  5428. service.startPts = pts;
  5429. };
  5430. /**
  5431. * Push a caption to output if the caption contains text.
  5432. *
  5433. * @param {Service} service The service object to be affected
  5434. */
  5435. Cea708Stream.prototype.pushCaption = function (service) {
  5436. if (service.text !== '') {
  5437. this.trigger('data', {
  5438. startPts: service.startPts,
  5439. endPts: service.endPts,
  5440. text: service.text,
  5441. stream: 'cc708_' + service.serviceNum
  5442. });
  5443. service.text = '';
  5444. service.startPts = service.endPts;
  5445. }
  5446. };
  5447. /**
  5448. * Parse and execute the DSW command.
  5449. *
  5450. * Set visible property of windows based on the parsed bitmask.
  5451. *
  5452. * @param {Integer} i Current index in the 708 packet
  5453. * @param {Service} service The service object to be affected
  5454. * @return {Integer} New index after parsing
  5455. */
  5456. Cea708Stream.prototype.displayWindows = function (i, service) {
  5457. var packetData = this.current708Packet.data;
  5458. var b = packetData[++i];
  5459. var pts = this.getPts(i);
  5460. this.flushDisplayed(pts, service);
  5461. for (var winId = 0; winId < 8; winId++) {
  5462. if (b & 0x01 << winId) {
  5463. service.windows[winId].visible = 1;
  5464. }
  5465. }
  5466. return i;
  5467. };
  5468. /**
  5469. * Parse and execute the HDW command.
  5470. *
  5471. * Set visible property of windows based on the parsed bitmask.
  5472. *
  5473. * @param {Integer} i Current index in the 708 packet
  5474. * @param {Service} service The service object to be affected
  5475. * @return {Integer} New index after parsing
  5476. */
  5477. Cea708Stream.prototype.hideWindows = function (i, service) {
  5478. var packetData = this.current708Packet.data;
  5479. var b = packetData[++i];
  5480. var pts = this.getPts(i);
  5481. this.flushDisplayed(pts, service);
  5482. for (var winId = 0; winId < 8; winId++) {
  5483. if (b & 0x01 << winId) {
  5484. service.windows[winId].visible = 0;
  5485. }
  5486. }
  5487. return i;
  5488. };
  5489. /**
  5490. * Parse and execute the TGW command.
  5491. *
  5492. * Set visible property of windows based on the parsed bitmask.
  5493. *
  5494. * @param {Integer} i Current index in the 708 packet
  5495. * @param {Service} service The service object to be affected
  5496. * @return {Integer} New index after parsing
  5497. */
  5498. Cea708Stream.prototype.toggleWindows = function (i, service) {
  5499. var packetData = this.current708Packet.data;
  5500. var b = packetData[++i];
  5501. var pts = this.getPts(i);
  5502. this.flushDisplayed(pts, service);
  5503. for (var winId = 0; winId < 8; winId++) {
  5504. if (b & 0x01 << winId) {
  5505. service.windows[winId].visible ^= 1;
  5506. }
  5507. }
  5508. return i;
  5509. };
  5510. /**
  5511. * Parse and execute the CLW command.
  5512. *
  5513. * Clear text of windows based on the parsed bitmask.
  5514. *
  5515. * @param {Integer} i Current index in the 708 packet
  5516. * @param {Service} service The service object to be affected
  5517. * @return {Integer} New index after parsing
  5518. */
  5519. Cea708Stream.prototype.clearWindows = function (i, service) {
  5520. var packetData = this.current708Packet.data;
  5521. var b = packetData[++i];
  5522. var pts = this.getPts(i);
  5523. this.flushDisplayed(pts, service);
  5524. for (var winId = 0; winId < 8; winId++) {
  5525. if (b & 0x01 << winId) {
  5526. service.windows[winId].clearText();
  5527. }
  5528. }
  5529. return i;
  5530. };
  5531. /**
  5532. * Parse and execute the DLW command.
  5533. *
  5534. * Re-initialize windows based on the parsed bitmask.
  5535. *
  5536. * @param {Integer} i Current index in the 708 packet
  5537. * @param {Service} service The service object to be affected
  5538. * @return {Integer} New index after parsing
  5539. */
  5540. Cea708Stream.prototype.deleteWindows = function (i, service) {
  5541. var packetData = this.current708Packet.data;
  5542. var b = packetData[++i];
  5543. var pts = this.getPts(i);
  5544. this.flushDisplayed(pts, service);
  5545. for (var winId = 0; winId < 8; winId++) {
  5546. if (b & 0x01 << winId) {
  5547. service.windows[winId].reset();
  5548. }
  5549. }
  5550. return i;
  5551. };
  5552. /**
  5553. * Parse and execute the SPA command.
  5554. *
  5555. * Set pen attributes of the current window.
  5556. *
  5557. * @param {Integer} i Current index in the 708 packet
  5558. * @param {Service} service The service object to be affected
  5559. * @return {Integer} New index after parsing
  5560. */
  5561. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  5562. var packetData = this.current708Packet.data;
  5563. var b = packetData[i];
  5564. var penAttr = service.currentWindow.penAttr;
  5565. b = packetData[++i];
  5566. penAttr.textTag = (b & 0xf0) >> 4; // tt
  5567. penAttr.offset = (b & 0x0c) >> 2; // o
  5568. penAttr.penSize = b & 0x03; // s
  5569. b = packetData[++i];
  5570. penAttr.italics = (b & 0x80) >> 7; // i
  5571. penAttr.underline = (b & 0x40) >> 6; // u
  5572. penAttr.edgeType = (b & 0x38) >> 3; // et
  5573. penAttr.fontStyle = b & 0x07; // fs
  5574. return i;
  5575. };
  5576. /**
  5577. * Parse and execute the SPC command.
  5578. *
  5579. * Set pen color of the current window.
  5580. *
  5581. * @param {Integer} i Current index in the 708 packet
  5582. * @param {Service} service The service object to be affected
  5583. * @return {Integer} New index after parsing
  5584. */
  5585. Cea708Stream.prototype.setPenColor = function (i, service) {
  5586. var packetData = this.current708Packet.data;
  5587. var b = packetData[i];
  5588. var penColor = service.currentWindow.penColor;
  5589. b = packetData[++i];
  5590. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  5591. penColor.fgRed = (b & 0x30) >> 4; // fr
  5592. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  5593. penColor.fgBlue = b & 0x03; // fb
  5594. b = packetData[++i];
  5595. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  5596. penColor.bgRed = (b & 0x30) >> 4; // br
  5597. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  5598. penColor.bgBlue = b & 0x03; // bb
  5599. b = packetData[++i];
  5600. penColor.edgeRed = (b & 0x30) >> 4; // er
  5601. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  5602. penColor.edgeBlue = b & 0x03; // eb
  5603. return i;
  5604. };
  5605. /**
  5606. * Parse and execute the SPL command.
  5607. *
  5608. * Set pen location of the current window.
  5609. *
  5610. * @param {Integer} i Current index in the 708 packet
  5611. * @param {Service} service The service object to be affected
  5612. * @return {Integer} New index after parsing
  5613. */
  5614. Cea708Stream.prototype.setPenLocation = function (i, service) {
  5615. var packetData = this.current708Packet.data;
  5616. var b = packetData[i];
  5617. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  5618. service.currentWindow.pendingNewLine = true;
  5619. b = packetData[++i];
  5620. penLoc.row = b & 0x0f; // r
  5621. b = packetData[++i];
  5622. penLoc.column = b & 0x3f; // c
  5623. return i;
  5624. };
  5625. /**
  5626. * Execute the RST command.
  5627. *
  5628. * Reset service to a clean slate. Re-initialize.
  5629. *
  5630. * @param {Integer} i Current index in the 708 packet
  5631. * @param {Service} service The service object to be affected
  5632. * @return {Service} Re-initialized service
  5633. */
  5634. Cea708Stream.prototype.reset = function (i, service) {
  5635. var pts = this.getPts(i);
  5636. this.flushDisplayed(pts, service);
  5637. return this.initService(service.serviceNum, i);
  5638. }; // This hash maps non-ASCII, special, and extended character codes to their
  5639. // proper Unicode equivalent. The first keys that are only a single byte
  5640. // are the non-standard ASCII characters, which simply map the CEA608 byte
  5641. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  5642. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  5643. // can be performed regardless of the field and data channel on which the
  5644. // character code was received.
  5645. var CHARACTER_TRANSLATION = {
  5646. 0x2a: 0xe1,
  5647. // á
  5648. 0x5c: 0xe9,
  5649. // é
  5650. 0x5e: 0xed,
  5651. // í
  5652. 0x5f: 0xf3,
  5653. // ó
  5654. 0x60: 0xfa,
  5655. // ú
  5656. 0x7b: 0xe7,
  5657. // ç
  5658. 0x7c: 0xf7,
  5659. // ÷
  5660. 0x7d: 0xd1,
  5661. // Ñ
  5662. 0x7e: 0xf1,
  5663. // ñ
  5664. 0x7f: 0x2588,
  5665. // █
  5666. 0x0130: 0xae,
  5667. // ®
  5668. 0x0131: 0xb0,
  5669. // °
  5670. 0x0132: 0xbd,
  5671. // ½
  5672. 0x0133: 0xbf,
  5673. // ¿
  5674. 0x0134: 0x2122,
  5675. // ™
  5676. 0x0135: 0xa2,
  5677. // ¢
  5678. 0x0136: 0xa3,
  5679. // £
  5680. 0x0137: 0x266a,
  5681. // ♪
  5682. 0x0138: 0xe0,
  5683. // à
  5684. 0x0139: 0xa0,
  5685. //
  5686. 0x013a: 0xe8,
  5687. // è
  5688. 0x013b: 0xe2,
  5689. // â
  5690. 0x013c: 0xea,
  5691. // ê
  5692. 0x013d: 0xee,
  5693. // î
  5694. 0x013e: 0xf4,
  5695. // ô
  5696. 0x013f: 0xfb,
  5697. // û
  5698. 0x0220: 0xc1,
  5699. // Á
  5700. 0x0221: 0xc9,
  5701. // É
  5702. 0x0222: 0xd3,
  5703. // Ó
  5704. 0x0223: 0xda,
  5705. // Ú
  5706. 0x0224: 0xdc,
  5707. // Ü
  5708. 0x0225: 0xfc,
  5709. // ü
  5710. 0x0226: 0x2018,
  5711. // ‘
  5712. 0x0227: 0xa1,
  5713. // ¡
  5714. 0x0228: 0x2a,
  5715. // *
  5716. 0x0229: 0x27,
  5717. // '
  5718. 0x022a: 0x2014,
  5719. // —
  5720. 0x022b: 0xa9,
  5721. // ©
  5722. 0x022c: 0x2120,
  5723. // ℠
  5724. 0x022d: 0x2022,
  5725. // •
  5726. 0x022e: 0x201c,
  5727. // “
  5728. 0x022f: 0x201d,
  5729. // ”
  5730. 0x0230: 0xc0,
  5731. // À
  5732. 0x0231: 0xc2,
  5733. // Â
  5734. 0x0232: 0xc7,
  5735. // Ç
  5736. 0x0233: 0xc8,
  5737. // È
  5738. 0x0234: 0xca,
  5739. // Ê
  5740. 0x0235: 0xcb,
  5741. // Ë
  5742. 0x0236: 0xeb,
  5743. // ë
  5744. 0x0237: 0xce,
  5745. // Î
  5746. 0x0238: 0xcf,
  5747. // Ï
  5748. 0x0239: 0xef,
  5749. // ï
  5750. 0x023a: 0xd4,
  5751. // Ô
  5752. 0x023b: 0xd9,
  5753. // Ù
  5754. 0x023c: 0xf9,
  5755. // ù
  5756. 0x023d: 0xdb,
  5757. // Û
  5758. 0x023e: 0xab,
  5759. // «
  5760. 0x023f: 0xbb,
  5761. // »
  5762. 0x0320: 0xc3,
  5763. // Ã
  5764. 0x0321: 0xe3,
  5765. // ã
  5766. 0x0322: 0xcd,
  5767. // Í
  5768. 0x0323: 0xcc,
  5769. // Ì
  5770. 0x0324: 0xec,
  5771. // ì
  5772. 0x0325: 0xd2,
  5773. // Ò
  5774. 0x0326: 0xf2,
  5775. // ò
  5776. 0x0327: 0xd5,
  5777. // Õ
  5778. 0x0328: 0xf5,
  5779. // õ
  5780. 0x0329: 0x7b,
  5781. // {
  5782. 0x032a: 0x7d,
  5783. // }
  5784. 0x032b: 0x5c,
  5785. // \
  5786. 0x032c: 0x5e,
  5787. // ^
  5788. 0x032d: 0x5f,
  5789. // _
  5790. 0x032e: 0x7c,
  5791. // |
  5792. 0x032f: 0x7e,
  5793. // ~
  5794. 0x0330: 0xc4,
  5795. // Ä
  5796. 0x0331: 0xe4,
  5797. // ä
  5798. 0x0332: 0xd6,
  5799. // Ö
  5800. 0x0333: 0xf6,
  5801. // ö
  5802. 0x0334: 0xdf,
  5803. // ß
  5804. 0x0335: 0xa5,
  5805. // ¥
  5806. 0x0336: 0xa4,
  5807. // ¤
  5808. 0x0337: 0x2502,
  5809. // │
  5810. 0x0338: 0xc5,
  5811. // Å
  5812. 0x0339: 0xe5,
  5813. // å
  5814. 0x033a: 0xd8,
  5815. // Ø
  5816. 0x033b: 0xf8,
  5817. // ø
  5818. 0x033c: 0x250c,
  5819. // ┌
  5820. 0x033d: 0x2510,
  5821. // ┐
  5822. 0x033e: 0x2514,
  5823. // └
  5824. 0x033f: 0x2518 // ┘
  5825. };
  5826. var getCharFromCode = function (code) {
  5827. if (code === null) {
  5828. return '';
  5829. }
  5830. code = CHARACTER_TRANSLATION[code] || code;
  5831. return String.fromCharCode(code);
  5832. }; // the index of the last row in a CEA-608 display buffer
  5833. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  5834. // getting it through bit logic.
  5835. 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
  5836. // cells. The "bottom" row is the last element in the outer array.
  5837. var createDisplayBuffer = function () {
  5838. var result = [],
  5839. i = BOTTOM_ROW + 1;
  5840. while (i--) {
  5841. result.push('');
  5842. }
  5843. return result;
  5844. };
  5845. var Cea608Stream = function (field, dataChannel) {
  5846. Cea608Stream.prototype.init.call(this);
  5847. this.field_ = field || 0;
  5848. this.dataChannel_ = dataChannel || 0;
  5849. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  5850. this.setConstants();
  5851. this.reset();
  5852. this.push = function (packet) {
  5853. var data, swap, char0, char1, text; // remove the parity bits
  5854. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  5855. if (data === this.lastControlCode_) {
  5856. this.lastControlCode_ = null;
  5857. return;
  5858. } // Store control codes
  5859. if ((data & 0xf000) === 0x1000) {
  5860. this.lastControlCode_ = data;
  5861. } else if (data !== this.PADDING_) {
  5862. this.lastControlCode_ = null;
  5863. }
  5864. char0 = data >>> 8;
  5865. char1 = data & 0xff;
  5866. if (data === this.PADDING_) {
  5867. return;
  5868. } else if (data === this.RESUME_CAPTION_LOADING_) {
  5869. this.mode_ = 'popOn';
  5870. } else if (data === this.END_OF_CAPTION_) {
  5871. // If an EOC is received while in paint-on mode, the displayed caption
  5872. // text should be swapped to non-displayed memory as if it was a pop-on
  5873. // caption. Because of that, we should explicitly switch back to pop-on
  5874. // mode
  5875. this.mode_ = 'popOn';
  5876. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  5877. this.flushDisplayed(packet.pts); // flip memory
  5878. swap = this.displayed_;
  5879. this.displayed_ = this.nonDisplayed_;
  5880. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  5881. this.startPts_ = packet.pts;
  5882. } else if (data === this.ROLL_UP_2_ROWS_) {
  5883. this.rollUpRows_ = 2;
  5884. this.setRollUp(packet.pts);
  5885. } else if (data === this.ROLL_UP_3_ROWS_) {
  5886. this.rollUpRows_ = 3;
  5887. this.setRollUp(packet.pts);
  5888. } else if (data === this.ROLL_UP_4_ROWS_) {
  5889. this.rollUpRows_ = 4;
  5890. this.setRollUp(packet.pts);
  5891. } else if (data === this.CARRIAGE_RETURN_) {
  5892. this.clearFormatting(packet.pts);
  5893. this.flushDisplayed(packet.pts);
  5894. this.shiftRowsUp_();
  5895. this.startPts_ = packet.pts;
  5896. } else if (data === this.BACKSPACE_) {
  5897. if (this.mode_ === 'popOn') {
  5898. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  5899. } else {
  5900. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  5901. }
  5902. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  5903. this.flushDisplayed(packet.pts);
  5904. this.displayed_ = createDisplayBuffer();
  5905. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  5906. this.nonDisplayed_ = createDisplayBuffer();
  5907. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  5908. if (this.mode_ !== 'paintOn') {
  5909. // NOTE: This should be removed when proper caption positioning is
  5910. // implemented
  5911. this.flushDisplayed(packet.pts);
  5912. this.displayed_ = createDisplayBuffer();
  5913. }
  5914. this.mode_ = 'paintOn';
  5915. this.startPts_ = packet.pts; // Append special characters to caption text
  5916. } else if (this.isSpecialCharacter(char0, char1)) {
  5917. // Bitmask char0 so that we can apply character transformations
  5918. // regardless of field and data channel.
  5919. // Then byte-shift to the left and OR with char1 so we can pass the
  5920. // entire character code to `getCharFromCode`.
  5921. char0 = (char0 & 0x03) << 8;
  5922. text = getCharFromCode(char0 | char1);
  5923. this[this.mode_](packet.pts, text);
  5924. this.column_++; // Append extended characters to caption text
  5925. } else if (this.isExtCharacter(char0, char1)) {
  5926. // Extended characters always follow their "non-extended" equivalents.
  5927. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  5928. // decoders are supposed to drop the "è", while compliant decoders
  5929. // backspace the "e" and insert "è".
  5930. // Delete the previous character
  5931. if (this.mode_ === 'popOn') {
  5932. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  5933. } else {
  5934. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  5935. } // Bitmask char0 so that we can apply character transformations
  5936. // regardless of field and data channel.
  5937. // Then byte-shift to the left and OR with char1 so we can pass the
  5938. // entire character code to `getCharFromCode`.
  5939. char0 = (char0 & 0x03) << 8;
  5940. text = getCharFromCode(char0 | char1);
  5941. this[this.mode_](packet.pts, text);
  5942. this.column_++; // Process mid-row codes
  5943. } else if (this.isMidRowCode(char0, char1)) {
  5944. // Attributes are not additive, so clear all formatting
  5945. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  5946. // should be replaced with spaces, so add one now
  5947. this[this.mode_](packet.pts, ' ');
  5948. this.column_++;
  5949. if ((char1 & 0xe) === 0xe) {
  5950. this.addFormatting(packet.pts, ['i']);
  5951. }
  5952. if ((char1 & 0x1) === 0x1) {
  5953. this.addFormatting(packet.pts, ['u']);
  5954. } // Detect offset control codes and adjust cursor
  5955. } else if (this.isOffsetControlCode(char0, char1)) {
  5956. // Cursor position is set by indent PAC (see below) in 4-column
  5957. // increments, with an additional offset code of 1-3 to reach any
  5958. // of the 32 columns specified by CEA-608. So all we need to do
  5959. // here is increment the column cursor by the given offset.
  5960. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  5961. } else if (this.isPAC(char0, char1)) {
  5962. // There's no logic for PAC -> row mapping, so we have to just
  5963. // find the row code in an array and use its index :(
  5964. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  5965. if (this.mode_ === 'rollUp') {
  5966. // This implies that the base row is incorrectly set.
  5967. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  5968. // of roll-up rows set.
  5969. if (row - this.rollUpRows_ + 1 < 0) {
  5970. row = this.rollUpRows_ - 1;
  5971. }
  5972. this.setRollUp(packet.pts, row);
  5973. }
  5974. if (row !== this.row_) {
  5975. // formatting is only persistent for current row
  5976. this.clearFormatting(packet.pts);
  5977. this.row_ = row;
  5978. } // All PACs can apply underline, so detect and apply
  5979. // (All odd-numbered second bytes set underline)
  5980. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  5981. this.addFormatting(packet.pts, ['u']);
  5982. }
  5983. if ((data & 0x10) === 0x10) {
  5984. // We've got an indent level code. Each successive even number
  5985. // increments the column cursor by 4, so we can get the desired
  5986. // column position by bit-shifting to the right (to get n/2)
  5987. // and multiplying by 4.
  5988. this.column_ = ((data & 0xe) >> 1) * 4;
  5989. }
  5990. if (this.isColorPAC(char1)) {
  5991. // it's a color code, though we only support white, which
  5992. // can be either normal or italicized. white italics can be
  5993. // either 0x4e or 0x6e depending on the row, so we just
  5994. // bitwise-and with 0xe to see if italics should be turned on
  5995. if ((char1 & 0xe) === 0xe) {
  5996. this.addFormatting(packet.pts, ['i']);
  5997. }
  5998. } // We have a normal character in char0, and possibly one in char1
  5999. } else if (this.isNormalChar(char0)) {
  6000. if (char1 === 0x00) {
  6001. char1 = null;
  6002. }
  6003. text = getCharFromCode(char0);
  6004. text += getCharFromCode(char1);
  6005. this[this.mode_](packet.pts, text);
  6006. this.column_ += text.length;
  6007. } // finish data processing
  6008. };
  6009. };
  6010. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  6011. // display buffer
  6012. Cea608Stream.prototype.flushDisplayed = function (pts) {
  6013. var content = this.displayed_ // remove spaces from the start and end of the string
  6014. .map(function (row, index) {
  6015. try {
  6016. return row.trim();
  6017. } catch (e) {
  6018. // Ordinarily, this shouldn't happen. However, caption
  6019. // parsing errors should not throw exceptions and
  6020. // break playback.
  6021. this.trigger('log', {
  6022. level: 'warn',
  6023. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  6024. });
  6025. return '';
  6026. }
  6027. }, this) // combine all text rows to display in one cue
  6028. .join('\n') // and remove blank rows from the start and end, but not the middle
  6029. .replace(/^\n+|\n+$/g, '');
  6030. if (content.length) {
  6031. this.trigger('data', {
  6032. startPts: this.startPts_,
  6033. endPts: pts,
  6034. text: content,
  6035. stream: this.name_
  6036. });
  6037. }
  6038. };
  6039. /**
  6040. * Zero out the data, used for startup and on seek
  6041. */
  6042. Cea608Stream.prototype.reset = function () {
  6043. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  6044. // actually display captions. If a caption is shifted to a row
  6045. // with a lower index than this, it is cleared from the display
  6046. // buffer
  6047. this.topRow_ = 0;
  6048. this.startPts_ = 0;
  6049. this.displayed_ = createDisplayBuffer();
  6050. this.nonDisplayed_ = createDisplayBuffer();
  6051. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  6052. this.column_ = 0;
  6053. this.row_ = BOTTOM_ROW;
  6054. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  6055. this.formatting_ = [];
  6056. };
  6057. /**
  6058. * Sets up control code and related constants for this instance
  6059. */
  6060. Cea608Stream.prototype.setConstants = function () {
  6061. // The following attributes have these uses:
  6062. // ext_ : char0 for mid-row codes, and the base for extended
  6063. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  6064. // extended codes)
  6065. // control_: char0 for control codes, except byte-shifted to the
  6066. // left so that we can do this.control_ | CONTROL_CODE
  6067. // offset_: char0 for tab offset codes
  6068. //
  6069. // It's also worth noting that control codes, and _only_ control codes,
  6070. // differ between field 1 and field2. Field 2 control codes are always
  6071. // their field 1 value plus 1. That's why there's the "| field" on the
  6072. // control value.
  6073. if (this.dataChannel_ === 0) {
  6074. this.BASE_ = 0x10;
  6075. this.EXT_ = 0x11;
  6076. this.CONTROL_ = (0x14 | this.field_) << 8;
  6077. this.OFFSET_ = 0x17;
  6078. } else if (this.dataChannel_ === 1) {
  6079. this.BASE_ = 0x18;
  6080. this.EXT_ = 0x19;
  6081. this.CONTROL_ = (0x1c | this.field_) << 8;
  6082. this.OFFSET_ = 0x1f;
  6083. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  6084. // list is not exhaustive. For a more comprehensive listing and semantics see
  6085. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  6086. // Padding
  6087. this.PADDING_ = 0x0000; // Pop-on Mode
  6088. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  6089. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  6090. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  6091. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  6092. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  6093. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  6094. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  6095. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  6096. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  6097. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  6098. };
  6099. /**
  6100. * Detects if the 2-byte packet data is a special character
  6101. *
  6102. * Special characters have a second byte in the range 0x30 to 0x3f,
  6103. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  6104. * data channel 2).
  6105. *
  6106. * @param {Integer} char0 The first byte
  6107. * @param {Integer} char1 The second byte
  6108. * @return {Boolean} Whether the 2 bytes are an special character
  6109. */
  6110. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  6111. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  6112. };
  6113. /**
  6114. * Detects if the 2-byte packet data is an extended character
  6115. *
  6116. * Extended characters have a second byte in the range 0x20 to 0x3f,
  6117. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  6118. * 0x1a or 0x1b (for data channel 2).
  6119. *
  6120. * @param {Integer} char0 The first byte
  6121. * @param {Integer} char1 The second byte
  6122. * @return {Boolean} Whether the 2 bytes are an extended character
  6123. */
  6124. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  6125. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  6126. };
  6127. /**
  6128. * Detects if the 2-byte packet is a mid-row code
  6129. *
  6130. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  6131. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  6132. * channel 2).
  6133. *
  6134. * @param {Integer} char0 The first byte
  6135. * @param {Integer} char1 The second byte
  6136. * @return {Boolean} Whether the 2 bytes are a mid-row code
  6137. */
  6138. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  6139. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  6140. };
  6141. /**
  6142. * Detects if the 2-byte packet is an offset control code
  6143. *
  6144. * Offset control codes have a second byte in the range 0x21 to 0x23,
  6145. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  6146. * data channel 2).
  6147. *
  6148. * @param {Integer} char0 The first byte
  6149. * @param {Integer} char1 The second byte
  6150. * @return {Boolean} Whether the 2 bytes are an offset control code
  6151. */
  6152. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  6153. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  6154. };
  6155. /**
  6156. * Detects if the 2-byte packet is a Preamble Address Code
  6157. *
  6158. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  6159. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  6160. * range 0x40 to 0x7f.
  6161. *
  6162. * @param {Integer} char0 The first byte
  6163. * @param {Integer} char1 The second byte
  6164. * @return {Boolean} Whether the 2 bytes are a PAC
  6165. */
  6166. Cea608Stream.prototype.isPAC = function (char0, char1) {
  6167. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  6168. };
  6169. /**
  6170. * Detects if a packet's second byte is in the range of a PAC color code
  6171. *
  6172. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  6173. * 0x60 to 0x6f.
  6174. *
  6175. * @param {Integer} char1 The second byte
  6176. * @return {Boolean} Whether the byte is a color PAC
  6177. */
  6178. Cea608Stream.prototype.isColorPAC = function (char1) {
  6179. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  6180. };
  6181. /**
  6182. * Detects if a single byte is in the range of a normal character
  6183. *
  6184. * Normal text bytes are in the range 0x20 to 0x7f.
  6185. *
  6186. * @param {Integer} char The byte
  6187. * @return {Boolean} Whether the byte is a normal character
  6188. */
  6189. Cea608Stream.prototype.isNormalChar = function (char) {
  6190. return char >= 0x20 && char <= 0x7f;
  6191. };
  6192. /**
  6193. * Configures roll-up
  6194. *
  6195. * @param {Integer} pts Current PTS
  6196. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  6197. * a new position
  6198. */
  6199. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  6200. // Reset the base row to the bottom row when switching modes
  6201. if (this.mode_ !== 'rollUp') {
  6202. this.row_ = BOTTOM_ROW;
  6203. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  6204. this.flushDisplayed(pts);
  6205. this.nonDisplayed_ = createDisplayBuffer();
  6206. this.displayed_ = createDisplayBuffer();
  6207. }
  6208. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  6209. // move currently displayed captions (up or down) to the new base row
  6210. for (var i = 0; i < this.rollUpRows_; i++) {
  6211. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  6212. this.displayed_[this.row_ - i] = '';
  6213. }
  6214. }
  6215. if (newBaseRow === undefined) {
  6216. newBaseRow = this.row_;
  6217. }
  6218. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  6219. }; // Adds the opening HTML tag for the passed character to the caption text,
  6220. // and keeps track of it for later closing
  6221. Cea608Stream.prototype.addFormatting = function (pts, format) {
  6222. this.formatting_ = this.formatting_.concat(format);
  6223. var text = format.reduce(function (text, format) {
  6224. return text + '<' + format + '>';
  6225. }, '');
  6226. this[this.mode_](pts, text);
  6227. }; // Adds HTML closing tags for current formatting to caption text and
  6228. // clears remembered formatting
  6229. Cea608Stream.prototype.clearFormatting = function (pts) {
  6230. if (!this.formatting_.length) {
  6231. return;
  6232. }
  6233. var text = this.formatting_.reverse().reduce(function (text, format) {
  6234. return text + '</' + format + '>';
  6235. }, '');
  6236. this.formatting_ = [];
  6237. this[this.mode_](pts, text);
  6238. }; // Mode Implementations
  6239. Cea608Stream.prototype.popOn = function (pts, text) {
  6240. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  6241. baseRow += text;
  6242. this.nonDisplayed_[this.row_] = baseRow;
  6243. };
  6244. Cea608Stream.prototype.rollUp = function (pts, text) {
  6245. var baseRow = this.displayed_[this.row_];
  6246. baseRow += text;
  6247. this.displayed_[this.row_] = baseRow;
  6248. };
  6249. Cea608Stream.prototype.shiftRowsUp_ = function () {
  6250. var i; // clear out inactive rows
  6251. for (i = 0; i < this.topRow_; i++) {
  6252. this.displayed_[i] = '';
  6253. }
  6254. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  6255. this.displayed_[i] = '';
  6256. } // shift displayed rows up
  6257. for (i = this.topRow_; i < this.row_; i++) {
  6258. this.displayed_[i] = this.displayed_[i + 1];
  6259. } // clear out the bottom row
  6260. this.displayed_[this.row_] = '';
  6261. };
  6262. Cea608Stream.prototype.paintOn = function (pts, text) {
  6263. var baseRow = this.displayed_[this.row_];
  6264. baseRow += text;
  6265. this.displayed_[this.row_] = baseRow;
  6266. }; // exports
  6267. var captionStream = {
  6268. CaptionStream: CaptionStream$2,
  6269. Cea608Stream: Cea608Stream,
  6270. Cea708Stream: Cea708Stream
  6271. };
  6272. /**
  6273. * mux.js
  6274. *
  6275. * Copyright (c) Brightcove
  6276. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6277. */
  6278. var streamTypes = {
  6279. H264_STREAM_TYPE: 0x1B,
  6280. ADTS_STREAM_TYPE: 0x0F,
  6281. METADATA_STREAM_TYPE: 0x15
  6282. };
  6283. /**
  6284. * mux.js
  6285. *
  6286. * Copyright (c) Brightcove
  6287. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6288. *
  6289. * Accepts program elementary stream (PES) data events and corrects
  6290. * decode and presentation time stamps to account for a rollover
  6291. * of the 33 bit value.
  6292. */
  6293. var Stream$6 = stream;
  6294. var MAX_TS = 8589934592;
  6295. var RO_THRESH = 4294967296;
  6296. var TYPE_SHARED = 'shared';
  6297. var handleRollover$1 = function (value, reference) {
  6298. var direction = 1;
  6299. if (value > reference) {
  6300. // If the current timestamp value is greater than our reference timestamp and we detect a
  6301. // timestamp rollover, this means the roll over is happening in the opposite direction.
  6302. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  6303. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  6304. // rollover point. In loading this segment, the timestamp values will be very large,
  6305. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  6306. // the time stamp to be `value - 2^33`.
  6307. direction = -1;
  6308. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  6309. // cause an incorrect adjustment.
  6310. while (Math.abs(reference - value) > RO_THRESH) {
  6311. value += direction * MAX_TS;
  6312. }
  6313. return value;
  6314. };
  6315. var TimestampRolloverStream$1 = function (type) {
  6316. var lastDTS, referenceDTS;
  6317. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  6318. // video and audio. We could use `undefined` here, but having a string
  6319. // makes debugging a little clearer.
  6320. this.type_ = type || TYPE_SHARED;
  6321. this.push = function (data) {
  6322. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  6323. // streams will only accept data that matches their type.
  6324. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  6325. return;
  6326. }
  6327. if (referenceDTS === undefined) {
  6328. referenceDTS = data.dts;
  6329. }
  6330. data.dts = handleRollover$1(data.dts, referenceDTS);
  6331. data.pts = handleRollover$1(data.pts, referenceDTS);
  6332. lastDTS = data.dts;
  6333. this.trigger('data', data);
  6334. };
  6335. this.flush = function () {
  6336. referenceDTS = lastDTS;
  6337. this.trigger('done');
  6338. };
  6339. this.endTimeline = function () {
  6340. this.flush();
  6341. this.trigger('endedtimeline');
  6342. };
  6343. this.discontinuity = function () {
  6344. referenceDTS = void 0;
  6345. lastDTS = void 0;
  6346. };
  6347. this.reset = function () {
  6348. this.discontinuity();
  6349. this.trigger('reset');
  6350. };
  6351. };
  6352. TimestampRolloverStream$1.prototype = new Stream$6();
  6353. var timestampRolloverStream = {
  6354. TimestampRolloverStream: TimestampRolloverStream$1,
  6355. handleRollover: handleRollover$1
  6356. }; // Once IE11 support is dropped, this function should be removed.
  6357. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  6358. if (!typedArray) {
  6359. return -1;
  6360. }
  6361. var currentIndex = fromIndex;
  6362. for (; currentIndex < typedArray.length; currentIndex++) {
  6363. if (typedArray[currentIndex] === element) {
  6364. return currentIndex;
  6365. }
  6366. }
  6367. return -1;
  6368. };
  6369. var typedArray = {
  6370. typedArrayIndexOf: typedArrayIndexOf$1
  6371. };
  6372. /**
  6373. * mux.js
  6374. *
  6375. * Copyright (c) Brightcove
  6376. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6377. *
  6378. * Tools for parsing ID3 frame data
  6379. * @see http://id3.org/id3v2.3.0
  6380. */
  6381. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  6382. // Frames that allow different types of text encoding contain a text
  6383. // encoding description byte [ID3v2.4.0 section 4.]
  6384. textEncodingDescriptionByte = {
  6385. Iso88591: 0x00,
  6386. // ISO-8859-1, terminated with \0.
  6387. Utf16: 0x01,
  6388. // UTF-16 encoded Unicode BOM, terminated with \0\0
  6389. Utf16be: 0x02,
  6390. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  6391. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  6392. },
  6393. // return a percent-encoded representation of the specified byte range
  6394. // @see http://en.wikipedia.org/wiki/Percent-encoding
  6395. percentEncode$1 = function (bytes, start, end) {
  6396. var i,
  6397. result = '';
  6398. for (i = start; i < end; i++) {
  6399. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  6400. }
  6401. return result;
  6402. },
  6403. // return the string representation of the specified byte range,
  6404. // interpreted as UTf-8.
  6405. parseUtf8 = function (bytes, start, end) {
  6406. return decodeURIComponent(percentEncode$1(bytes, start, end));
  6407. },
  6408. // return the string representation of the specified byte range,
  6409. // interpreted as ISO-8859-1.
  6410. parseIso88591$1 = function (bytes, start, end) {
  6411. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  6412. },
  6413. parseSyncSafeInteger$1 = function (data) {
  6414. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  6415. },
  6416. frameParsers = {
  6417. 'APIC': function (frame) {
  6418. var i = 1,
  6419. mimeTypeEndIndex,
  6420. descriptionEndIndex,
  6421. LINK_MIME_TYPE = '-->';
  6422. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6423. // ignore frames with unrecognized character encodings
  6424. return;
  6425. } // parsing fields [ID3v2.4.0 section 4.14.]
  6426. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6427. if (mimeTypeEndIndex < 0) {
  6428. // malformed frame
  6429. return;
  6430. } // parsing Mime type field (terminated with \0)
  6431. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  6432. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  6433. frame.pictureType = frame.data[i];
  6434. i++;
  6435. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6436. if (descriptionEndIndex < 0) {
  6437. // malformed frame
  6438. return;
  6439. } // parsing Description field (terminated with \0)
  6440. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  6441. i = descriptionEndIndex + 1;
  6442. if (frame.mimeType === LINK_MIME_TYPE) {
  6443. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  6444. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  6445. } else {
  6446. // parsing Picture Data field as binary data
  6447. frame.pictureData = frame.data.subarray(i, frame.data.length);
  6448. }
  6449. },
  6450. 'T*': function (frame) {
  6451. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6452. // ignore frames with unrecognized character encodings
  6453. return;
  6454. } // parse text field, do not include null terminator in the frame value
  6455. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  6456. 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.]
  6457. frame.values = frame.value.split('\0');
  6458. },
  6459. 'TXXX': function (frame) {
  6460. var descriptionEndIndex;
  6461. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6462. // ignore frames with unrecognized character encodings
  6463. return;
  6464. }
  6465. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6466. if (descriptionEndIndex === -1) {
  6467. return;
  6468. } // parse the text fields
  6469. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  6470. // frames that allow different types of encoding contain terminated text
  6471. // [ID3v2.4.0 section 4.]
  6472. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  6473. frame.data = frame.value;
  6474. },
  6475. 'W*': function (frame) {
  6476. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6477. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  6478. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  6479. },
  6480. 'WXXX': function (frame) {
  6481. var descriptionEndIndex;
  6482. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6483. // ignore frames with unrecognized character encodings
  6484. return;
  6485. }
  6486. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6487. if (descriptionEndIndex === -1) {
  6488. return;
  6489. } // parse the description and URL fields
  6490. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6491. // if the value is followed by a string termination all the following information
  6492. // should be ignored [ID3v2.4.0 section 4.3]
  6493. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  6494. },
  6495. 'PRIV': function (frame) {
  6496. var i;
  6497. for (i = 0; i < frame.data.length; i++) {
  6498. if (frame.data[i] === 0) {
  6499. // parse the description and URL fields
  6500. frame.owner = parseIso88591$1(frame.data, 0, i);
  6501. break;
  6502. }
  6503. }
  6504. frame.privateData = frame.data.subarray(i + 1);
  6505. frame.data = frame.privateData;
  6506. }
  6507. };
  6508. var parseId3Frames$1 = function (data) {
  6509. var frameSize,
  6510. frameHeader,
  6511. frameStart = 10,
  6512. tagSize = 0,
  6513. frames = []; // If we don't have enough data for a header, 10 bytes,
  6514. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  6515. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  6516. return;
  6517. } // the frame size is transmitted as a 28-bit integer in the
  6518. // last four bytes of the ID3 header.
  6519. // The most significant bit of each byte is dropped and the
  6520. // results concatenated to recover the actual value.
  6521. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  6522. // convenient for our comparisons to include it
  6523. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  6524. var hasExtendedHeader = data[5] & 0x40;
  6525. if (hasExtendedHeader) {
  6526. // advance the frame start past the extended header
  6527. frameStart += 4; // header size field
  6528. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  6529. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  6530. } // parse one or more ID3 frames
  6531. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  6532. do {
  6533. // determine the number of bytes in this frame
  6534. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  6535. if (frameSize < 1) {
  6536. break;
  6537. }
  6538. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  6539. var frame = {
  6540. id: frameHeader,
  6541. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  6542. };
  6543. frame.key = frame.id; // parse frame values
  6544. if (frameParsers[frame.id]) {
  6545. // use frame specific parser
  6546. frameParsers[frame.id](frame);
  6547. } else if (frame.id[0] === 'T') {
  6548. // use text frame generic parser
  6549. frameParsers['T*'](frame);
  6550. } else if (frame.id[0] === 'W') {
  6551. // use URL link frame generic parser
  6552. frameParsers['W*'](frame);
  6553. }
  6554. frames.push(frame);
  6555. frameStart += 10; // advance past the frame header
  6556. frameStart += frameSize; // advance past the frame body
  6557. } while (frameStart < tagSize);
  6558. return frames;
  6559. };
  6560. var parseId3 = {
  6561. parseId3Frames: parseId3Frames$1,
  6562. parseSyncSafeInteger: parseSyncSafeInteger$1,
  6563. frameParsers: frameParsers
  6564. };
  6565. /**
  6566. * mux.js
  6567. *
  6568. * Copyright (c) Brightcove
  6569. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6570. *
  6571. * Accepts program elementary stream (PES) data events and parses out
  6572. * ID3 metadata from them, if present.
  6573. * @see http://id3.org/id3v2.3.0
  6574. */
  6575. var Stream$5 = stream,
  6576. StreamTypes$3 = streamTypes,
  6577. id3 = parseId3,
  6578. MetadataStream;
  6579. MetadataStream = function (options) {
  6580. var settings = {
  6581. // the bytes of the program-level descriptor field in MP2T
  6582. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  6583. // program element descriptors"
  6584. descriptor: options && options.descriptor
  6585. },
  6586. // the total size in bytes of the ID3 tag being parsed
  6587. tagSize = 0,
  6588. // tag data that is not complete enough to be parsed
  6589. buffer = [],
  6590. // the total number of bytes currently in the buffer
  6591. bufferSize = 0,
  6592. i;
  6593. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  6594. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  6595. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  6596. if (settings.descriptor) {
  6597. for (i = 0; i < settings.descriptor.length; i++) {
  6598. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  6599. }
  6600. }
  6601. this.push = function (chunk) {
  6602. var tag, frameStart, frameSize, frame, i, frameHeader;
  6603. if (chunk.type !== 'timed-metadata') {
  6604. return;
  6605. } // if data_alignment_indicator is set in the PES header,
  6606. // we must have the start of a new ID3 tag. Assume anything
  6607. // remaining in the buffer was malformed and throw it out
  6608. if (chunk.dataAlignmentIndicator) {
  6609. bufferSize = 0;
  6610. buffer.length = 0;
  6611. } // ignore events that don't look like ID3 data
  6612. 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))) {
  6613. this.trigger('log', {
  6614. level: 'warn',
  6615. message: 'Skipping unrecognized metadata packet'
  6616. });
  6617. return;
  6618. } // add this chunk to the data we've collected so far
  6619. buffer.push(chunk);
  6620. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  6621. if (buffer.length === 1) {
  6622. // the frame size is transmitted as a 28-bit integer in the
  6623. // last four bytes of the ID3 header.
  6624. // The most significant bit of each byte is dropped and the
  6625. // results concatenated to recover the actual value.
  6626. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  6627. // convenient for our comparisons to include it
  6628. tagSize += 10;
  6629. } // if the entire frame has not arrived, wait for more data
  6630. if (bufferSize < tagSize) {
  6631. return;
  6632. } // collect the entire frame so it can be parsed
  6633. tag = {
  6634. data: new Uint8Array(tagSize),
  6635. frames: [],
  6636. pts: buffer[0].pts,
  6637. dts: buffer[0].dts
  6638. };
  6639. for (i = 0; i < tagSize;) {
  6640. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  6641. i += buffer[0].data.byteLength;
  6642. bufferSize -= buffer[0].data.byteLength;
  6643. buffer.shift();
  6644. } // find the start of the first frame and the end of the tag
  6645. frameStart = 10;
  6646. if (tag.data[5] & 0x40) {
  6647. // advance the frame start past the extended header
  6648. frameStart += 4; // header size field
  6649. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  6650. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  6651. } // parse one or more ID3 frames
  6652. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  6653. do {
  6654. // determine the number of bytes in this frame
  6655. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  6656. if (frameSize < 1) {
  6657. this.trigger('log', {
  6658. level: 'warn',
  6659. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  6660. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  6661. // to be sent along.
  6662. break;
  6663. }
  6664. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  6665. frame = {
  6666. id: frameHeader,
  6667. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  6668. };
  6669. frame.key = frame.id; // parse frame values
  6670. if (id3.frameParsers[frame.id]) {
  6671. // use frame specific parser
  6672. id3.frameParsers[frame.id](frame);
  6673. } else if (frame.id[0] === 'T') {
  6674. // use text frame generic parser
  6675. id3.frameParsers['T*'](frame);
  6676. } else if (frame.id[0] === 'W') {
  6677. // use URL link frame generic parser
  6678. id3.frameParsers['W*'](frame);
  6679. } // handle the special PRIV frame used to indicate the start
  6680. // time for raw AAC data
  6681. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  6682. var d = frame.data,
  6683. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  6684. size *= 4;
  6685. size += d[7] & 0x03;
  6686. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  6687. // on the value of this frame
  6688. // we couldn't have known the appropriate pts and dts before
  6689. // parsing this ID3 tag so set those values now
  6690. if (tag.pts === undefined && tag.dts === undefined) {
  6691. tag.pts = frame.timeStamp;
  6692. tag.dts = frame.timeStamp;
  6693. }
  6694. this.trigger('timestamp', frame);
  6695. }
  6696. tag.frames.push(frame);
  6697. frameStart += 10; // advance past the frame header
  6698. frameStart += frameSize; // advance past the frame body
  6699. } while (frameStart < tagSize);
  6700. this.trigger('data', tag);
  6701. };
  6702. };
  6703. MetadataStream.prototype = new Stream$5();
  6704. var metadataStream = MetadataStream;
  6705. /**
  6706. * mux.js
  6707. *
  6708. * Copyright (c) Brightcove
  6709. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6710. *
  6711. * A stream-based mp2t to mp4 converter. This utility can be used to
  6712. * deliver mp4s to a SourceBuffer on platforms that support native
  6713. * Media Source Extensions.
  6714. */
  6715. var Stream$4 = stream,
  6716. CaptionStream$1 = captionStream,
  6717. StreamTypes$2 = streamTypes,
  6718. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  6719. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  6720. var MP2T_PACKET_LENGTH$1 = 188,
  6721. // bytes
  6722. SYNC_BYTE$1 = 0x47;
  6723. /**
  6724. * Splits an incoming stream of binary data into MPEG-2 Transport
  6725. * Stream packets.
  6726. */
  6727. TransportPacketStream = function () {
  6728. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  6729. bytesInBuffer = 0;
  6730. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  6731. /**
  6732. * Split a stream of data into M2TS packets
  6733. **/
  6734. this.push = function (bytes) {
  6735. var startIndex = 0,
  6736. endIndex = MP2T_PACKET_LENGTH$1,
  6737. everything; // If there are bytes remaining from the last segment, prepend them to the
  6738. // bytes that were pushed in
  6739. if (bytesInBuffer) {
  6740. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  6741. everything.set(buffer.subarray(0, bytesInBuffer));
  6742. everything.set(bytes, bytesInBuffer);
  6743. bytesInBuffer = 0;
  6744. } else {
  6745. everything = bytes;
  6746. } // While we have enough data for a packet
  6747. while (endIndex < everything.byteLength) {
  6748. // Look for a pair of start and end sync bytes in the data..
  6749. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  6750. // We found a packet so emit it and jump one whole packet forward in
  6751. // the stream
  6752. this.trigger('data', everything.subarray(startIndex, endIndex));
  6753. startIndex += MP2T_PACKET_LENGTH$1;
  6754. endIndex += MP2T_PACKET_LENGTH$1;
  6755. continue;
  6756. } // If we get here, we have somehow become de-synchronized and we need to step
  6757. // forward one byte at a time until we find a pair of sync bytes that denote
  6758. // a packet
  6759. startIndex++;
  6760. endIndex++;
  6761. } // If there was some data left over at the end of the segment that couldn't
  6762. // possibly be a whole packet, keep it because it might be the start of a packet
  6763. // that continues in the next segment
  6764. if (startIndex < everything.byteLength) {
  6765. buffer.set(everything.subarray(startIndex), 0);
  6766. bytesInBuffer = everything.byteLength - startIndex;
  6767. }
  6768. };
  6769. /**
  6770. * Passes identified M2TS packets to the TransportParseStream to be parsed
  6771. **/
  6772. this.flush = function () {
  6773. // If the buffer contains a whole packet when we are being flushed, emit it
  6774. // and empty the buffer. Otherwise hold onto the data because it may be
  6775. // important for decoding the next segment
  6776. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  6777. this.trigger('data', buffer);
  6778. bytesInBuffer = 0;
  6779. }
  6780. this.trigger('done');
  6781. };
  6782. this.endTimeline = function () {
  6783. this.flush();
  6784. this.trigger('endedtimeline');
  6785. };
  6786. this.reset = function () {
  6787. bytesInBuffer = 0;
  6788. this.trigger('reset');
  6789. };
  6790. };
  6791. TransportPacketStream.prototype = new Stream$4();
  6792. /**
  6793. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  6794. * forms of the individual transport stream packets.
  6795. */
  6796. TransportParseStream = function () {
  6797. var parsePsi, parsePat, parsePmt, self;
  6798. TransportParseStream.prototype.init.call(this);
  6799. self = this;
  6800. this.packetsWaitingForPmt = [];
  6801. this.programMapTable = undefined;
  6802. parsePsi = function (payload, psi) {
  6803. var offset = 0; // PSI packets may be split into multiple sections and those
  6804. // sections may be split into multiple packets. If a PSI
  6805. // section starts in this packet, the payload_unit_start_indicator
  6806. // will be true and the first byte of the payload will indicate
  6807. // the offset from the current position to the start of the
  6808. // section.
  6809. if (psi.payloadUnitStartIndicator) {
  6810. offset += payload[offset] + 1;
  6811. }
  6812. if (psi.type === 'pat') {
  6813. parsePat(payload.subarray(offset), psi);
  6814. } else {
  6815. parsePmt(payload.subarray(offset), psi);
  6816. }
  6817. };
  6818. parsePat = function (payload, pat) {
  6819. pat.section_number = payload[7]; // eslint-disable-line camelcase
  6820. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  6821. // skip the PSI header and parse the first PMT entry
  6822. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  6823. pat.pmtPid = self.pmtPid;
  6824. };
  6825. /**
  6826. * Parse out the relevant fields of a Program Map Table (PMT).
  6827. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  6828. * packet. The first byte in this array should be the table_id
  6829. * field.
  6830. * @param pmt {object} the object that should be decorated with
  6831. * fields parsed from the PMT.
  6832. */
  6833. parsePmt = function (payload, pmt) {
  6834. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  6835. // take effect. We don't believe this should ever be the case
  6836. // for HLS but we'll ignore "forward" PMT declarations if we see
  6837. // them. Future PMT declarations have the current_next_indicator
  6838. // set to zero.
  6839. if (!(payload[5] & 0x01)) {
  6840. return;
  6841. } // overwrite any existing program map table
  6842. self.programMapTable = {
  6843. video: null,
  6844. audio: null,
  6845. 'timed-metadata': {}
  6846. }; // the mapping table ends at the end of the current section
  6847. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  6848. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  6849. // long the program info descriptors are
  6850. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  6851. offset = 12 + programInfoLength;
  6852. while (offset < tableEnd) {
  6853. var streamType = payload[offset];
  6854. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  6855. // TODO: should this be done for metadata too? for now maintain behavior of
  6856. // multiple metadata streams
  6857. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  6858. self.programMapTable.video = pid;
  6859. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  6860. self.programMapTable.audio = pid;
  6861. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  6862. // map pid to stream type for metadata streams
  6863. self.programMapTable['timed-metadata'][pid] = streamType;
  6864. } // move to the next table entry
  6865. // skip past the elementary stream descriptors, if present
  6866. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  6867. } // record the map on the packet as well
  6868. pmt.programMapTable = self.programMapTable;
  6869. };
  6870. /**
  6871. * Deliver a new MP2T packet to the next stream in the pipeline.
  6872. */
  6873. this.push = function (packet) {
  6874. var result = {},
  6875. offset = 4;
  6876. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  6877. result.pid = packet[1] & 0x1f;
  6878. result.pid <<= 8;
  6879. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  6880. // fifth byte of the TS packet header. The adaptation field is
  6881. // used to add stuffing to PES packets that don't fill a complete
  6882. // TS packet, and to specify some forms of timing and control data
  6883. // that we do not currently use.
  6884. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  6885. offset += packet[offset] + 1;
  6886. } // parse the rest of the packet based on the type
  6887. if (result.pid === 0) {
  6888. result.type = 'pat';
  6889. parsePsi(packet.subarray(offset), result);
  6890. this.trigger('data', result);
  6891. } else if (result.pid === this.pmtPid) {
  6892. result.type = 'pmt';
  6893. parsePsi(packet.subarray(offset), result);
  6894. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  6895. while (this.packetsWaitingForPmt.length) {
  6896. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  6897. }
  6898. } else if (this.programMapTable === undefined) {
  6899. // When we have not seen a PMT yet, defer further processing of
  6900. // PES packets until one has been parsed
  6901. this.packetsWaitingForPmt.push([packet, offset, result]);
  6902. } else {
  6903. this.processPes_(packet, offset, result);
  6904. }
  6905. };
  6906. this.processPes_ = function (packet, offset, result) {
  6907. // set the appropriate stream type
  6908. if (result.pid === this.programMapTable.video) {
  6909. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  6910. } else if (result.pid === this.programMapTable.audio) {
  6911. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  6912. } else {
  6913. // if not video or audio, it is timed-metadata or unknown
  6914. // if unknown, streamType will be undefined
  6915. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  6916. }
  6917. result.type = 'pes';
  6918. result.data = packet.subarray(offset);
  6919. this.trigger('data', result);
  6920. };
  6921. };
  6922. TransportParseStream.prototype = new Stream$4();
  6923. TransportParseStream.STREAM_TYPES = {
  6924. h264: 0x1b,
  6925. adts: 0x0f
  6926. };
  6927. /**
  6928. * Reconsistutes program elementary stream (PES) packets from parsed
  6929. * transport stream packets. That is, if you pipe an
  6930. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  6931. * events will be events which capture the bytes for individual PES
  6932. * packets plus relevant metadata that has been extracted from the
  6933. * container.
  6934. */
  6935. ElementaryStream = function () {
  6936. var self = this,
  6937. segmentHadPmt = false,
  6938. // PES packet fragments
  6939. video = {
  6940. data: [],
  6941. size: 0
  6942. },
  6943. audio = {
  6944. data: [],
  6945. size: 0
  6946. },
  6947. timedMetadata = {
  6948. data: [],
  6949. size: 0
  6950. },
  6951. programMapTable,
  6952. parsePes = function (payload, pes) {
  6953. var ptsDtsFlags;
  6954. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  6955. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  6956. // that are frame data that is continuing from the previous fragment. This
  6957. // is to check that the pes data is the start of a new pes payload
  6958. if (startPrefix !== 1) {
  6959. return;
  6960. } // get the packet length, this will be 0 for video
  6961. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  6962. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  6963. // and a DTS value. Determine what combination of values is
  6964. // available to work with.
  6965. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  6966. // performs all bitwise operations on 32-bit integers but javascript
  6967. // supports a much greater range (52-bits) of integer using standard
  6968. // mathematical operations.
  6969. // We construct a 31-bit value using bitwise operators over the 31
  6970. // most significant bits and then multiply by 4 (equal to a left-shift
  6971. // of 2) before we add the final 2 least significant bits of the
  6972. // timestamp (equal to an OR.)
  6973. if (ptsDtsFlags & 0xC0) {
  6974. // the PTS and DTS are not written out directly. For information
  6975. // on how they are encoded, see
  6976. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  6977. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  6978. pes.pts *= 4; // Left shift by 2
  6979. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  6980. pes.dts = pes.pts;
  6981. if (ptsDtsFlags & 0x40) {
  6982. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  6983. pes.dts *= 4; // Left shift by 2
  6984. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  6985. }
  6986. } // the data section starts immediately after the PES header.
  6987. // pes_header_data_length specifies the number of header bytes
  6988. // that follow the last byte of the field.
  6989. pes.data = payload.subarray(9 + payload[8]);
  6990. },
  6991. /**
  6992. * Pass completely parsed PES packets to the next stream in the pipeline
  6993. **/
  6994. flushStream = function (stream, type, forceFlush) {
  6995. var packetData = new Uint8Array(stream.size),
  6996. event = {
  6997. type: type
  6998. },
  6999. i = 0,
  7000. offset = 0,
  7001. packetFlushable = false,
  7002. fragment; // do nothing if there is not enough buffered data for a complete
  7003. // PES header
  7004. if (!stream.data.length || stream.size < 9) {
  7005. return;
  7006. }
  7007. event.trackId = stream.data[0].pid; // reassemble the packet
  7008. for (i = 0; i < stream.data.length; i++) {
  7009. fragment = stream.data[i];
  7010. packetData.set(fragment.data, offset);
  7011. offset += fragment.data.byteLength;
  7012. } // parse assembled packet's PES header
  7013. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  7014. // check that there is enough stream data to fill the packet
  7015. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  7016. if (forceFlush || packetFlushable) {
  7017. stream.size = 0;
  7018. stream.data.length = 0;
  7019. } // only emit packets that are complete. this is to avoid assembling
  7020. // incomplete PES packets due to poor segmentation
  7021. if (packetFlushable) {
  7022. self.trigger('data', event);
  7023. }
  7024. };
  7025. ElementaryStream.prototype.init.call(this);
  7026. /**
  7027. * Identifies M2TS packet types and parses PES packets using metadata
  7028. * parsed from the PMT
  7029. **/
  7030. this.push = function (data) {
  7031. ({
  7032. pat: function () {// we have to wait for the PMT to arrive as well before we
  7033. // have any meaningful metadata
  7034. },
  7035. pes: function () {
  7036. var stream, streamType;
  7037. switch (data.streamType) {
  7038. case StreamTypes$2.H264_STREAM_TYPE:
  7039. stream = video;
  7040. streamType = 'video';
  7041. break;
  7042. case StreamTypes$2.ADTS_STREAM_TYPE:
  7043. stream = audio;
  7044. streamType = 'audio';
  7045. break;
  7046. case StreamTypes$2.METADATA_STREAM_TYPE:
  7047. stream = timedMetadata;
  7048. streamType = 'timed-metadata';
  7049. break;
  7050. default:
  7051. // ignore unknown stream types
  7052. return;
  7053. } // if a new packet is starting, we can flush the completed
  7054. // packet
  7055. if (data.payloadUnitStartIndicator) {
  7056. flushStream(stream, streamType, true);
  7057. } // buffer this fragment until we are sure we've received the
  7058. // complete payload
  7059. stream.data.push(data);
  7060. stream.size += data.data.byteLength;
  7061. },
  7062. pmt: function () {
  7063. var event = {
  7064. type: 'metadata',
  7065. tracks: []
  7066. };
  7067. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  7068. if (programMapTable.video !== null) {
  7069. event.tracks.push({
  7070. timelineStartInfo: {
  7071. baseMediaDecodeTime: 0
  7072. },
  7073. id: +programMapTable.video,
  7074. codec: 'avc',
  7075. type: 'video'
  7076. });
  7077. }
  7078. if (programMapTable.audio !== null) {
  7079. event.tracks.push({
  7080. timelineStartInfo: {
  7081. baseMediaDecodeTime: 0
  7082. },
  7083. id: +programMapTable.audio,
  7084. codec: 'adts',
  7085. type: 'audio'
  7086. });
  7087. }
  7088. segmentHadPmt = true;
  7089. self.trigger('data', event);
  7090. }
  7091. })[data.type]();
  7092. };
  7093. this.reset = function () {
  7094. video.size = 0;
  7095. video.data.length = 0;
  7096. audio.size = 0;
  7097. audio.data.length = 0;
  7098. this.trigger('reset');
  7099. };
  7100. /**
  7101. * Flush any remaining input. Video PES packets may be of variable
  7102. * length. Normally, the start of a new video packet can trigger the
  7103. * finalization of the previous packet. That is not possible if no
  7104. * more video is forthcoming, however. In that case, some other
  7105. * mechanism (like the end of the file) has to be employed. When it is
  7106. * clear that no additional data is forthcoming, calling this method
  7107. * will flush the buffered packets.
  7108. */
  7109. this.flushStreams_ = function () {
  7110. // !!THIS ORDER IS IMPORTANT!!
  7111. // video first then audio
  7112. flushStream(video, 'video');
  7113. flushStream(audio, 'audio');
  7114. flushStream(timedMetadata, 'timed-metadata');
  7115. };
  7116. this.flush = function () {
  7117. // if on flush we haven't had a pmt emitted
  7118. // and we have a pmt to emit. emit the pmt
  7119. // so that we trigger a trackinfo downstream.
  7120. if (!segmentHadPmt && programMapTable) {
  7121. var pmt = {
  7122. type: 'metadata',
  7123. tracks: []
  7124. }; // translate audio and video streams to tracks
  7125. if (programMapTable.video !== null) {
  7126. pmt.tracks.push({
  7127. timelineStartInfo: {
  7128. baseMediaDecodeTime: 0
  7129. },
  7130. id: +programMapTable.video,
  7131. codec: 'avc',
  7132. type: 'video'
  7133. });
  7134. }
  7135. if (programMapTable.audio !== null) {
  7136. pmt.tracks.push({
  7137. timelineStartInfo: {
  7138. baseMediaDecodeTime: 0
  7139. },
  7140. id: +programMapTable.audio,
  7141. codec: 'adts',
  7142. type: 'audio'
  7143. });
  7144. }
  7145. self.trigger('data', pmt);
  7146. }
  7147. segmentHadPmt = false;
  7148. this.flushStreams_();
  7149. this.trigger('done');
  7150. };
  7151. };
  7152. ElementaryStream.prototype = new Stream$4();
  7153. var m2ts$1 = {
  7154. PAT_PID: 0x0000,
  7155. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  7156. TransportPacketStream: TransportPacketStream,
  7157. TransportParseStream: TransportParseStream,
  7158. ElementaryStream: ElementaryStream,
  7159. TimestampRolloverStream: TimestampRolloverStream,
  7160. CaptionStream: CaptionStream$1.CaptionStream,
  7161. Cea608Stream: CaptionStream$1.Cea608Stream,
  7162. Cea708Stream: CaptionStream$1.Cea708Stream,
  7163. MetadataStream: metadataStream
  7164. };
  7165. for (var type in StreamTypes$2) {
  7166. if (StreamTypes$2.hasOwnProperty(type)) {
  7167. m2ts$1[type] = StreamTypes$2[type];
  7168. }
  7169. }
  7170. var m2ts_1 = m2ts$1;
  7171. /**
  7172. * mux.js
  7173. *
  7174. * Copyright (c) Brightcove
  7175. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7176. */
  7177. var Stream$3 = stream;
  7178. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  7179. var AdtsStream$1;
  7180. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7181. /*
  7182. * Accepts a ElementaryStream and emits data events with parsed
  7183. * AAC Audio Frames of the individual packets. Input audio in ADTS
  7184. * format is unpacked and re-emitted as AAC frames.
  7185. *
  7186. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  7187. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  7188. */
  7189. AdtsStream$1 = function (handlePartialSegments) {
  7190. var buffer,
  7191. frameNum = 0;
  7192. AdtsStream$1.prototype.init.call(this);
  7193. this.skipWarn_ = function (start, end) {
  7194. this.trigger('log', {
  7195. level: 'warn',
  7196. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  7197. });
  7198. };
  7199. this.push = function (packet) {
  7200. var i = 0,
  7201. frameLength,
  7202. protectionSkipBytes,
  7203. oldBuffer,
  7204. sampleCount,
  7205. adtsFrameDuration;
  7206. if (!handlePartialSegments) {
  7207. frameNum = 0;
  7208. }
  7209. if (packet.type !== 'audio') {
  7210. // ignore non-audio data
  7211. return;
  7212. } // Prepend any data in the buffer to the input data so that we can parse
  7213. // aac frames the cross a PES packet boundary
  7214. if (buffer && buffer.length) {
  7215. oldBuffer = buffer;
  7216. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  7217. buffer.set(oldBuffer);
  7218. buffer.set(packet.data, oldBuffer.byteLength);
  7219. } else {
  7220. buffer = packet.data;
  7221. } // unpack any ADTS frames which have been fully received
  7222. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  7223. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  7224. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  7225. while (i + 7 < buffer.length) {
  7226. // Look for the start of an ADTS header..
  7227. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  7228. if (typeof skip !== 'number') {
  7229. skip = i;
  7230. } // If a valid header was not found, jump one forward and attempt to
  7231. // find a valid ADTS header starting at the next byte
  7232. i++;
  7233. continue;
  7234. }
  7235. if (typeof skip === 'number') {
  7236. this.skipWarn_(skip, i);
  7237. skip = null;
  7238. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  7239. // end of the ADTS header
  7240. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  7241. // end of the sync sequence
  7242. // NOTE: frame length includes the size of the header
  7243. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  7244. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  7245. 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,
  7246. // then we have to wait for more data
  7247. if (buffer.byteLength - i < frameLength) {
  7248. break;
  7249. } // Otherwise, deliver the complete AAC frame
  7250. this.trigger('data', {
  7251. pts: packet.pts + frameNum * adtsFrameDuration,
  7252. dts: packet.dts + frameNum * adtsFrameDuration,
  7253. sampleCount: sampleCount,
  7254. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  7255. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  7256. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  7257. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  7258. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  7259. samplesize: 16,
  7260. // data is the frame without it's header
  7261. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  7262. });
  7263. frameNum++;
  7264. i += frameLength;
  7265. }
  7266. if (typeof skip === 'number') {
  7267. this.skipWarn_(skip, i);
  7268. skip = null;
  7269. } // remove processed bytes from the buffer.
  7270. buffer = buffer.subarray(i);
  7271. };
  7272. this.flush = function () {
  7273. frameNum = 0;
  7274. this.trigger('done');
  7275. };
  7276. this.reset = function () {
  7277. buffer = void 0;
  7278. this.trigger('reset');
  7279. };
  7280. this.endTimeline = function () {
  7281. buffer = void 0;
  7282. this.trigger('endedtimeline');
  7283. };
  7284. };
  7285. AdtsStream$1.prototype = new Stream$3();
  7286. var adts = AdtsStream$1;
  7287. /**
  7288. * mux.js
  7289. *
  7290. * Copyright (c) Brightcove
  7291. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7292. */
  7293. var ExpGolomb$1;
  7294. /**
  7295. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  7296. * scheme used by h264.
  7297. */
  7298. ExpGolomb$1 = function (workingData) {
  7299. var // the number of bytes left to examine in workingData
  7300. workingBytesAvailable = workingData.byteLength,
  7301. // the current word being examined
  7302. workingWord = 0,
  7303. // :uint
  7304. // the number of bits left to examine in the current word
  7305. workingBitsAvailable = 0; // :uint;
  7306. // ():uint
  7307. this.length = function () {
  7308. return 8 * workingBytesAvailable;
  7309. }; // ():uint
  7310. this.bitsAvailable = function () {
  7311. return 8 * workingBytesAvailable + workingBitsAvailable;
  7312. }; // ():void
  7313. this.loadWord = function () {
  7314. var position = workingData.byteLength - workingBytesAvailable,
  7315. workingBytes = new Uint8Array(4),
  7316. availableBytes = Math.min(4, workingBytesAvailable);
  7317. if (availableBytes === 0) {
  7318. throw new Error('no bytes available');
  7319. }
  7320. workingBytes.set(workingData.subarray(position, position + availableBytes));
  7321. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  7322. workingBitsAvailable = availableBytes * 8;
  7323. workingBytesAvailable -= availableBytes;
  7324. }; // (count:int):void
  7325. this.skipBits = function (count) {
  7326. var skipBytes; // :int
  7327. if (workingBitsAvailable > count) {
  7328. workingWord <<= count;
  7329. workingBitsAvailable -= count;
  7330. } else {
  7331. count -= workingBitsAvailable;
  7332. skipBytes = Math.floor(count / 8);
  7333. count -= skipBytes * 8;
  7334. workingBytesAvailable -= skipBytes;
  7335. this.loadWord();
  7336. workingWord <<= count;
  7337. workingBitsAvailable -= count;
  7338. }
  7339. }; // (size:int):uint
  7340. this.readBits = function (size) {
  7341. var bits = Math.min(workingBitsAvailable, size),
  7342. // :uint
  7343. valu = workingWord >>> 32 - bits; // :uint
  7344. // if size > 31, handle error
  7345. workingBitsAvailable -= bits;
  7346. if (workingBitsAvailable > 0) {
  7347. workingWord <<= bits;
  7348. } else if (workingBytesAvailable > 0) {
  7349. this.loadWord();
  7350. }
  7351. bits = size - bits;
  7352. if (bits > 0) {
  7353. return valu << bits | this.readBits(bits);
  7354. }
  7355. return valu;
  7356. }; // ():uint
  7357. this.skipLeadingZeros = function () {
  7358. var leadingZeroCount; // :uint
  7359. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  7360. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  7361. // the first bit of working word is 1
  7362. workingWord <<= leadingZeroCount;
  7363. workingBitsAvailable -= leadingZeroCount;
  7364. return leadingZeroCount;
  7365. }
  7366. } // we exhausted workingWord and still have not found a 1
  7367. this.loadWord();
  7368. return leadingZeroCount + this.skipLeadingZeros();
  7369. }; // ():void
  7370. this.skipUnsignedExpGolomb = function () {
  7371. this.skipBits(1 + this.skipLeadingZeros());
  7372. }; // ():void
  7373. this.skipExpGolomb = function () {
  7374. this.skipBits(1 + this.skipLeadingZeros());
  7375. }; // ():uint
  7376. this.readUnsignedExpGolomb = function () {
  7377. var clz = this.skipLeadingZeros(); // :uint
  7378. return this.readBits(clz + 1) - 1;
  7379. }; // ():int
  7380. this.readExpGolomb = function () {
  7381. var valu = this.readUnsignedExpGolomb(); // :int
  7382. if (0x01 & valu) {
  7383. // the number is odd if the low order bit is set
  7384. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  7385. }
  7386. return -1 * (valu >>> 1); // divide by two then make it negative
  7387. }; // Some convenience functions
  7388. // :Boolean
  7389. this.readBoolean = function () {
  7390. return this.readBits(1) === 1;
  7391. }; // ():int
  7392. this.readUnsignedByte = function () {
  7393. return this.readBits(8);
  7394. };
  7395. this.loadWord();
  7396. };
  7397. var expGolomb = ExpGolomb$1;
  7398. /**
  7399. * mux.js
  7400. *
  7401. * Copyright (c) Brightcove
  7402. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7403. */
  7404. var Stream$2 = stream;
  7405. var ExpGolomb = expGolomb;
  7406. var H264Stream$1, NalByteStream;
  7407. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  7408. /**
  7409. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  7410. */
  7411. NalByteStream = function () {
  7412. var syncPoint = 0,
  7413. i,
  7414. buffer;
  7415. NalByteStream.prototype.init.call(this);
  7416. /*
  7417. * Scans a byte stream and triggers a data event with the NAL units found.
  7418. * @param {Object} data Event received from H264Stream
  7419. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  7420. *
  7421. * @see H264Stream.push
  7422. */
  7423. this.push = function (data) {
  7424. var swapBuffer;
  7425. if (!buffer) {
  7426. buffer = data.data;
  7427. } else {
  7428. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  7429. swapBuffer.set(buffer);
  7430. swapBuffer.set(data.data, buffer.byteLength);
  7431. buffer = swapBuffer;
  7432. }
  7433. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  7434. // scan for NAL unit boundaries
  7435. // a match looks like this:
  7436. // 0 0 1 .. NAL .. 0 0 1
  7437. // ^ sync point ^ i
  7438. // or this:
  7439. // 0 0 1 .. NAL .. 0 0 0
  7440. // ^ sync point ^ i
  7441. // advance the sync point to a NAL start, if necessary
  7442. for (; syncPoint < len - 3; syncPoint++) {
  7443. if (buffer[syncPoint + 2] === 1) {
  7444. // the sync point is properly aligned
  7445. i = syncPoint + 5;
  7446. break;
  7447. }
  7448. }
  7449. while (i < len) {
  7450. // look at the current byte to determine if we've hit the end of
  7451. // a NAL unit boundary
  7452. switch (buffer[i]) {
  7453. case 0:
  7454. // skip past non-sync sequences
  7455. if (buffer[i - 1] !== 0) {
  7456. i += 2;
  7457. break;
  7458. } else if (buffer[i - 2] !== 0) {
  7459. i++;
  7460. break;
  7461. } // deliver the NAL unit if it isn't empty
  7462. if (syncPoint + 3 !== i - 2) {
  7463. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7464. } // drop trailing zeroes
  7465. do {
  7466. i++;
  7467. } while (buffer[i] !== 1 && i < len);
  7468. syncPoint = i - 2;
  7469. i += 3;
  7470. break;
  7471. case 1:
  7472. // skip past non-sync sequences
  7473. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  7474. i += 3;
  7475. break;
  7476. } // deliver the NAL unit
  7477. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7478. syncPoint = i - 2;
  7479. i += 3;
  7480. break;
  7481. default:
  7482. // the current byte isn't a one or zero, so it cannot be part
  7483. // of a sync sequence
  7484. i += 3;
  7485. break;
  7486. }
  7487. } // filter out the NAL units that were delivered
  7488. buffer = buffer.subarray(syncPoint);
  7489. i -= syncPoint;
  7490. syncPoint = 0;
  7491. };
  7492. this.reset = function () {
  7493. buffer = null;
  7494. syncPoint = 0;
  7495. this.trigger('reset');
  7496. };
  7497. this.flush = function () {
  7498. // deliver the last buffered NAL unit
  7499. if (buffer && buffer.byteLength > 3) {
  7500. this.trigger('data', buffer.subarray(syncPoint + 3));
  7501. } // reset the stream state
  7502. buffer = null;
  7503. syncPoint = 0;
  7504. this.trigger('done');
  7505. };
  7506. this.endTimeline = function () {
  7507. this.flush();
  7508. this.trigger('endedtimeline');
  7509. };
  7510. };
  7511. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  7512. // see Recommendation ITU-T H.264 (4/2013),
  7513. // 7.3.2.1.1 Sequence parameter set data syntax
  7514. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  7515. 100: true,
  7516. 110: true,
  7517. 122: true,
  7518. 244: true,
  7519. 44: true,
  7520. 83: true,
  7521. 86: true,
  7522. 118: true,
  7523. 128: true,
  7524. // TODO: the three profiles below don't
  7525. // appear to have sps data in the specificiation anymore?
  7526. 138: true,
  7527. 139: true,
  7528. 134: true
  7529. };
  7530. /**
  7531. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  7532. * events.
  7533. */
  7534. H264Stream$1 = function () {
  7535. var nalByteStream = new NalByteStream(),
  7536. self,
  7537. trackId,
  7538. currentPts,
  7539. currentDts,
  7540. discardEmulationPreventionBytes,
  7541. readSequenceParameterSet,
  7542. skipScalingList;
  7543. H264Stream$1.prototype.init.call(this);
  7544. self = this;
  7545. /*
  7546. * Pushes a packet from a stream onto the NalByteStream
  7547. *
  7548. * @param {Object} packet - A packet received from a stream
  7549. * @param {Uint8Array} packet.data - The raw bytes of the packet
  7550. * @param {Number} packet.dts - Decode timestamp of the packet
  7551. * @param {Number} packet.pts - Presentation timestamp of the packet
  7552. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  7553. * @param {('video'|'audio')} packet.type - The type of packet
  7554. *
  7555. */
  7556. this.push = function (packet) {
  7557. if (packet.type !== 'video') {
  7558. return;
  7559. }
  7560. trackId = packet.trackId;
  7561. currentPts = packet.pts;
  7562. currentDts = packet.dts;
  7563. nalByteStream.push(packet);
  7564. };
  7565. /*
  7566. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  7567. * for the NALUs to the next stream component.
  7568. * Also, preprocess caption and sequence parameter NALUs.
  7569. *
  7570. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  7571. * @see NalByteStream.push
  7572. */
  7573. nalByteStream.on('data', function (data) {
  7574. var event = {
  7575. trackId: trackId,
  7576. pts: currentPts,
  7577. dts: currentDts,
  7578. data: data,
  7579. nalUnitTypeCode: data[0] & 0x1f
  7580. };
  7581. switch (event.nalUnitTypeCode) {
  7582. case 0x05:
  7583. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  7584. break;
  7585. case 0x06:
  7586. event.nalUnitType = 'sei_rbsp';
  7587. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  7588. break;
  7589. case 0x07:
  7590. event.nalUnitType = 'seq_parameter_set_rbsp';
  7591. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  7592. event.config = readSequenceParameterSet(event.escapedRBSP);
  7593. break;
  7594. case 0x08:
  7595. event.nalUnitType = 'pic_parameter_set_rbsp';
  7596. break;
  7597. case 0x09:
  7598. event.nalUnitType = 'access_unit_delimiter_rbsp';
  7599. break;
  7600. } // This triggers data on the H264Stream
  7601. self.trigger('data', event);
  7602. });
  7603. nalByteStream.on('done', function () {
  7604. self.trigger('done');
  7605. });
  7606. nalByteStream.on('partialdone', function () {
  7607. self.trigger('partialdone');
  7608. });
  7609. nalByteStream.on('reset', function () {
  7610. self.trigger('reset');
  7611. });
  7612. nalByteStream.on('endedtimeline', function () {
  7613. self.trigger('endedtimeline');
  7614. });
  7615. this.flush = function () {
  7616. nalByteStream.flush();
  7617. };
  7618. this.partialFlush = function () {
  7619. nalByteStream.partialFlush();
  7620. };
  7621. this.reset = function () {
  7622. nalByteStream.reset();
  7623. };
  7624. this.endTimeline = function () {
  7625. nalByteStream.endTimeline();
  7626. };
  7627. /**
  7628. * Advance the ExpGolomb decoder past a scaling list. The scaling
  7629. * list is optionally transmitted as part of a sequence parameter
  7630. * set and is not relevant to transmuxing.
  7631. * @param count {number} the number of entries in this scaling list
  7632. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  7633. * start of a scaling list
  7634. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  7635. */
  7636. skipScalingList = function (count, expGolombDecoder) {
  7637. var lastScale = 8,
  7638. nextScale = 8,
  7639. j,
  7640. deltaScale;
  7641. for (j = 0; j < count; j++) {
  7642. if (nextScale !== 0) {
  7643. deltaScale = expGolombDecoder.readExpGolomb();
  7644. nextScale = (lastScale + deltaScale + 256) % 256;
  7645. }
  7646. lastScale = nextScale === 0 ? lastScale : nextScale;
  7647. }
  7648. };
  7649. /**
  7650. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  7651. * Sequence Payload"
  7652. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  7653. * unit
  7654. * @return {Uint8Array} the RBSP without any Emulation
  7655. * Prevention Bytes
  7656. */
  7657. discardEmulationPreventionBytes = function (data) {
  7658. var length = data.byteLength,
  7659. emulationPreventionBytesPositions = [],
  7660. i = 1,
  7661. newLength,
  7662. newData; // Find all `Emulation Prevention Bytes`
  7663. while (i < length - 2) {
  7664. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  7665. emulationPreventionBytesPositions.push(i + 2);
  7666. i += 2;
  7667. } else {
  7668. i++;
  7669. }
  7670. } // If no Emulation Prevention Bytes were found just return the original
  7671. // array
  7672. if (emulationPreventionBytesPositions.length === 0) {
  7673. return data;
  7674. } // Create a new array to hold the NAL unit data
  7675. newLength = length - emulationPreventionBytesPositions.length;
  7676. newData = new Uint8Array(newLength);
  7677. var sourceIndex = 0;
  7678. for (i = 0; i < newLength; sourceIndex++, i++) {
  7679. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  7680. // Skip this byte
  7681. sourceIndex++; // Remove this position index
  7682. emulationPreventionBytesPositions.shift();
  7683. }
  7684. newData[i] = data[sourceIndex];
  7685. }
  7686. return newData;
  7687. };
  7688. /**
  7689. * Read a sequence parameter set and return some interesting video
  7690. * properties. A sequence parameter set is the H264 metadata that
  7691. * describes the properties of upcoming video frames.
  7692. * @param data {Uint8Array} the bytes of a sequence parameter set
  7693. * @return {object} an object with configuration parsed from the
  7694. * sequence parameter set, including the dimensions of the
  7695. * associated video frames.
  7696. */
  7697. readSequenceParameterSet = function (data) {
  7698. var frameCropLeftOffset = 0,
  7699. frameCropRightOffset = 0,
  7700. frameCropTopOffset = 0,
  7701. frameCropBottomOffset = 0,
  7702. expGolombDecoder,
  7703. profileIdc,
  7704. levelIdc,
  7705. profileCompatibility,
  7706. chromaFormatIdc,
  7707. picOrderCntType,
  7708. numRefFramesInPicOrderCntCycle,
  7709. picWidthInMbsMinus1,
  7710. picHeightInMapUnitsMinus1,
  7711. frameMbsOnlyFlag,
  7712. scalingListCount,
  7713. sarRatio = [1, 1],
  7714. aspectRatioIdc,
  7715. i;
  7716. expGolombDecoder = new ExpGolomb(data);
  7717. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  7718. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  7719. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  7720. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  7721. // some profiles have more optional data we don't need
  7722. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  7723. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  7724. if (chromaFormatIdc === 3) {
  7725. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  7726. }
  7727. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  7728. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  7729. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  7730. if (expGolombDecoder.readBoolean()) {
  7731. // seq_scaling_matrix_present_flag
  7732. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  7733. for (i = 0; i < scalingListCount; i++) {
  7734. if (expGolombDecoder.readBoolean()) {
  7735. // seq_scaling_list_present_flag[ i ]
  7736. if (i < 6) {
  7737. skipScalingList(16, expGolombDecoder);
  7738. } else {
  7739. skipScalingList(64, expGolombDecoder);
  7740. }
  7741. }
  7742. }
  7743. }
  7744. }
  7745. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  7746. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  7747. if (picOrderCntType === 0) {
  7748. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  7749. } else if (picOrderCntType === 1) {
  7750. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  7751. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  7752. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  7753. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  7754. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  7755. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  7756. }
  7757. }
  7758. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  7759. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  7760. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  7761. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  7762. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  7763. if (frameMbsOnlyFlag === 0) {
  7764. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  7765. }
  7766. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  7767. if (expGolombDecoder.readBoolean()) {
  7768. // frame_cropping_flag
  7769. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  7770. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  7771. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  7772. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  7773. }
  7774. if (expGolombDecoder.readBoolean()) {
  7775. // vui_parameters_present_flag
  7776. if (expGolombDecoder.readBoolean()) {
  7777. // aspect_ratio_info_present_flag
  7778. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  7779. switch (aspectRatioIdc) {
  7780. case 1:
  7781. sarRatio = [1, 1];
  7782. break;
  7783. case 2:
  7784. sarRatio = [12, 11];
  7785. break;
  7786. case 3:
  7787. sarRatio = [10, 11];
  7788. break;
  7789. case 4:
  7790. sarRatio = [16, 11];
  7791. break;
  7792. case 5:
  7793. sarRatio = [40, 33];
  7794. break;
  7795. case 6:
  7796. sarRatio = [24, 11];
  7797. break;
  7798. case 7:
  7799. sarRatio = [20, 11];
  7800. break;
  7801. case 8:
  7802. sarRatio = [32, 11];
  7803. break;
  7804. case 9:
  7805. sarRatio = [80, 33];
  7806. break;
  7807. case 10:
  7808. sarRatio = [18, 11];
  7809. break;
  7810. case 11:
  7811. sarRatio = [15, 11];
  7812. break;
  7813. case 12:
  7814. sarRatio = [64, 33];
  7815. break;
  7816. case 13:
  7817. sarRatio = [160, 99];
  7818. break;
  7819. case 14:
  7820. sarRatio = [4, 3];
  7821. break;
  7822. case 15:
  7823. sarRatio = [3, 2];
  7824. break;
  7825. case 16:
  7826. sarRatio = [2, 1];
  7827. break;
  7828. case 255:
  7829. {
  7830. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  7831. break;
  7832. }
  7833. }
  7834. if (sarRatio) {
  7835. sarRatio[0] / sarRatio[1];
  7836. }
  7837. }
  7838. }
  7839. return {
  7840. profileIdc: profileIdc,
  7841. levelIdc: levelIdc,
  7842. profileCompatibility: profileCompatibility,
  7843. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  7844. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  7845. // sar is sample aspect ratio
  7846. sarRatio: sarRatio
  7847. };
  7848. };
  7849. };
  7850. H264Stream$1.prototype = new Stream$2();
  7851. var h264 = {
  7852. H264Stream: H264Stream$1,
  7853. NalByteStream: NalByteStream
  7854. };
  7855. /**
  7856. * mux.js
  7857. *
  7858. * Copyright (c) Brightcove
  7859. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7860. *
  7861. * Utilities to detect basic properties and metadata about Aac data.
  7862. */
  7863. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7864. var parseId3TagSize = function (header, byteIndex) {
  7865. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  7866. flags = header[byteIndex + 5],
  7867. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  7868. returnSize = returnSize >= 0 ? returnSize : 0;
  7869. if (footerPresent) {
  7870. return returnSize + 20;
  7871. }
  7872. return returnSize + 10;
  7873. };
  7874. var getId3Offset = function (data, offset) {
  7875. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  7876. return offset;
  7877. }
  7878. offset += parseId3TagSize(data, offset);
  7879. return getId3Offset(data, offset);
  7880. }; // TODO: use vhs-utils
  7881. var isLikelyAacData$1 = function (data) {
  7882. var offset = getId3Offset(data, 0);
  7883. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  7884. // is not mp3 data but aac data.
  7885. (data[offset + 1] & 0x16) === 0x10;
  7886. };
  7887. var parseSyncSafeInteger = function (data) {
  7888. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  7889. }; // return a percent-encoded representation of the specified byte range
  7890. // @see http://en.wikipedia.org/wiki/Percent-encoding
  7891. var percentEncode = function (bytes, start, end) {
  7892. var i,
  7893. result = '';
  7894. for (i = start; i < end; i++) {
  7895. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  7896. }
  7897. return result;
  7898. }; // return the string representation of the specified byte range,
  7899. // interpreted as ISO-8859-1.
  7900. var parseIso88591 = function (bytes, start, end) {
  7901. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  7902. };
  7903. var parseAdtsSize = function (header, byteIndex) {
  7904. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  7905. middle = header[byteIndex + 4] << 3,
  7906. highTwo = header[byteIndex + 3] & 0x3 << 11;
  7907. return highTwo | middle | lowThree;
  7908. };
  7909. var parseType$4 = function (header, byteIndex) {
  7910. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  7911. return 'timed-metadata';
  7912. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  7913. return 'audio';
  7914. }
  7915. return null;
  7916. };
  7917. var parseSampleRate = function (packet) {
  7918. var i = 0;
  7919. while (i + 5 < packet.length) {
  7920. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  7921. // If a valid header was not found, jump one forward and attempt to
  7922. // find a valid ADTS header starting at the next byte
  7923. i++;
  7924. continue;
  7925. }
  7926. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  7927. }
  7928. return null;
  7929. };
  7930. var parseAacTimestamp = function (packet) {
  7931. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  7932. frameStart = 10;
  7933. if (packet[5] & 0x40) {
  7934. // advance the frame start past the extended header
  7935. frameStart += 4; // header size field
  7936. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  7937. } // parse one or more ID3 frames
  7938. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  7939. do {
  7940. // determine the number of bytes in this frame
  7941. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  7942. if (frameSize < 1) {
  7943. return null;
  7944. }
  7945. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  7946. if (frameHeader === 'PRIV') {
  7947. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  7948. for (var i = 0; i < frame.byteLength; i++) {
  7949. if (frame[i] === 0) {
  7950. var owner = parseIso88591(frame, 0, i);
  7951. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  7952. var d = frame.subarray(i + 1);
  7953. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  7954. size *= 4;
  7955. size += d[7] & 0x03;
  7956. return size;
  7957. }
  7958. break;
  7959. }
  7960. }
  7961. }
  7962. frameStart += 10; // advance past the frame header
  7963. frameStart += frameSize; // advance past the frame body
  7964. } while (frameStart < packet.byteLength);
  7965. return null;
  7966. };
  7967. var utils = {
  7968. isLikelyAacData: isLikelyAacData$1,
  7969. parseId3TagSize: parseId3TagSize,
  7970. parseAdtsSize: parseAdtsSize,
  7971. parseType: parseType$4,
  7972. parseSampleRate: parseSampleRate,
  7973. parseAacTimestamp: parseAacTimestamp
  7974. };
  7975. /**
  7976. * mux.js
  7977. *
  7978. * Copyright (c) Brightcove
  7979. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7980. *
  7981. * A stream-based aac to mp4 converter. This utility can be used to
  7982. * deliver mp4s to a SourceBuffer on platforms that support native
  7983. * Media Source Extensions.
  7984. */
  7985. var Stream$1 = stream;
  7986. var aacUtils = utils; // Constants
  7987. var AacStream$1;
  7988. /**
  7989. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  7990. */
  7991. AacStream$1 = function () {
  7992. var everything = new Uint8Array(),
  7993. timeStamp = 0;
  7994. AacStream$1.prototype.init.call(this);
  7995. this.setTimestamp = function (timestamp) {
  7996. timeStamp = timestamp;
  7997. };
  7998. this.push = function (bytes) {
  7999. var frameSize = 0,
  8000. byteIndex = 0,
  8001. bytesLeft,
  8002. chunk,
  8003. packet,
  8004. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  8005. // bytes that were pushed in
  8006. if (everything.length) {
  8007. tempLength = everything.length;
  8008. everything = new Uint8Array(bytes.byteLength + tempLength);
  8009. everything.set(everything.subarray(0, tempLength));
  8010. everything.set(bytes, tempLength);
  8011. } else {
  8012. everything = bytes;
  8013. }
  8014. while (everything.length - byteIndex >= 3) {
  8015. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  8016. // Exit early because we don't have enough to parse
  8017. // the ID3 tag header
  8018. if (everything.length - byteIndex < 10) {
  8019. break;
  8020. } // check framesize
  8021. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8022. // to emit a full packet
  8023. // Add to byteIndex to support multiple ID3 tags in sequence
  8024. if (byteIndex + frameSize > everything.length) {
  8025. break;
  8026. }
  8027. chunk = {
  8028. type: 'timed-metadata',
  8029. data: everything.subarray(byteIndex, byteIndex + frameSize)
  8030. };
  8031. this.trigger('data', chunk);
  8032. byteIndex += frameSize;
  8033. continue;
  8034. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  8035. // Exit early because we don't have enough to parse
  8036. // the ADTS frame header
  8037. if (everything.length - byteIndex < 7) {
  8038. break;
  8039. }
  8040. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8041. // to emit a full packet
  8042. if (byteIndex + frameSize > everything.length) {
  8043. break;
  8044. }
  8045. packet = {
  8046. type: 'audio',
  8047. data: everything.subarray(byteIndex, byteIndex + frameSize),
  8048. pts: timeStamp,
  8049. dts: timeStamp
  8050. };
  8051. this.trigger('data', packet);
  8052. byteIndex += frameSize;
  8053. continue;
  8054. }
  8055. byteIndex++;
  8056. }
  8057. bytesLeft = everything.length - byteIndex;
  8058. if (bytesLeft > 0) {
  8059. everything = everything.subarray(byteIndex);
  8060. } else {
  8061. everything = new Uint8Array();
  8062. }
  8063. };
  8064. this.reset = function () {
  8065. everything = new Uint8Array();
  8066. this.trigger('reset');
  8067. };
  8068. this.endTimeline = function () {
  8069. everything = new Uint8Array();
  8070. this.trigger('endedtimeline');
  8071. };
  8072. };
  8073. AacStream$1.prototype = new Stream$1();
  8074. var aac = AacStream$1;
  8075. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  8076. var audioProperties = AUDIO_PROPERTIES$1;
  8077. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  8078. var videoProperties = VIDEO_PROPERTIES$1;
  8079. /**
  8080. * mux.js
  8081. *
  8082. * Copyright (c) Brightcove
  8083. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8084. *
  8085. * A stream-based mp2t to mp4 converter. This utility can be used to
  8086. * deliver mp4s to a SourceBuffer on platforms that support native
  8087. * Media Source Extensions.
  8088. */
  8089. var Stream = stream;
  8090. var mp4 = mp4Generator;
  8091. var frameUtils = frameUtils$1;
  8092. var audioFrameUtils = audioFrameUtils$1;
  8093. var trackDecodeInfo = trackDecodeInfo$1;
  8094. var m2ts = m2ts_1;
  8095. var clock = clock$2;
  8096. var AdtsStream = adts;
  8097. var H264Stream = h264.H264Stream;
  8098. var AacStream = aac;
  8099. var isLikelyAacData = utils.isLikelyAacData;
  8100. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  8101. var AUDIO_PROPERTIES = audioProperties;
  8102. var VIDEO_PROPERTIES = videoProperties; // object types
  8103. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  8104. var retriggerForStream = function (key, event) {
  8105. event.stream = key;
  8106. this.trigger('log', event);
  8107. };
  8108. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  8109. var keys = Object.keys(pipeline);
  8110. for (var i = 0; i < keys.length; i++) {
  8111. var key = keys[i]; // skip non-stream keys and headOfPipeline
  8112. // which is just a duplicate
  8113. if (key === 'headOfPipeline' || !pipeline[key].on) {
  8114. continue;
  8115. }
  8116. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  8117. }
  8118. };
  8119. /**
  8120. * Compare two arrays (even typed) for same-ness
  8121. */
  8122. var arrayEquals = function (a, b) {
  8123. var i;
  8124. if (a.length !== b.length) {
  8125. return false;
  8126. } // compare the value of each element in the array
  8127. for (i = 0; i < a.length; i++) {
  8128. if (a[i] !== b[i]) {
  8129. return false;
  8130. }
  8131. }
  8132. return true;
  8133. };
  8134. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  8135. var ptsOffsetFromDts = startPts - startDts,
  8136. decodeDuration = endDts - startDts,
  8137. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  8138. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  8139. // In order to provide relevant values for the player times, base timing info on the
  8140. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  8141. return {
  8142. start: {
  8143. dts: baseMediaDecodeTime,
  8144. pts: baseMediaDecodeTime + ptsOffsetFromDts
  8145. },
  8146. end: {
  8147. dts: baseMediaDecodeTime + decodeDuration,
  8148. pts: baseMediaDecodeTime + presentationDuration
  8149. },
  8150. prependedContentDuration: prependedContentDuration,
  8151. baseMediaDecodeTime: baseMediaDecodeTime
  8152. };
  8153. };
  8154. /**
  8155. * Constructs a single-track, ISO BMFF media segment from AAC data
  8156. * events. The output of this stream can be fed to a SourceBuffer
  8157. * configured with a suitable initialization segment.
  8158. * @param track {object} track metadata configuration
  8159. * @param options {object} transmuxer options object
  8160. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8161. * in the source; false to adjust the first segment to start at 0.
  8162. */
  8163. AudioSegmentStream = function (track, options) {
  8164. var adtsFrames = [],
  8165. sequenceNumber,
  8166. earliestAllowedDts = 0,
  8167. audioAppendStartTs = 0,
  8168. videoBaseMediaDecodeTime = Infinity;
  8169. options = options || {};
  8170. sequenceNumber = options.firstSequenceNumber || 0;
  8171. AudioSegmentStream.prototype.init.call(this);
  8172. this.push = function (data) {
  8173. trackDecodeInfo.collectDtsInfo(track, data);
  8174. if (track) {
  8175. AUDIO_PROPERTIES.forEach(function (prop) {
  8176. track[prop] = data[prop];
  8177. });
  8178. } // buffer audio data until end() is called
  8179. adtsFrames.push(data);
  8180. };
  8181. this.setEarliestDts = function (earliestDts) {
  8182. earliestAllowedDts = earliestDts;
  8183. };
  8184. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  8185. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  8186. };
  8187. this.setAudioAppendStart = function (timestamp) {
  8188. audioAppendStartTs = timestamp;
  8189. };
  8190. this.flush = function () {
  8191. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  8192. if (adtsFrames.length === 0) {
  8193. this.trigger('done', 'AudioSegmentStream');
  8194. return;
  8195. }
  8196. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  8197. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  8198. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  8199. // samples (that is, adts frames) in the audio data
  8200. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  8201. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  8202. adtsFrames = [];
  8203. moof = mp4.moof(sequenceNumber, [track]);
  8204. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  8205. sequenceNumber++;
  8206. boxes.set(moof);
  8207. boxes.set(mdat, moof.byteLength);
  8208. trackDecodeInfo.clearDtsInfo(track);
  8209. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  8210. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  8211. // valid use-case where an init segment/data should be triggered without associated
  8212. // frames. Leaving for now, but should be looked into.
  8213. if (frames.length) {
  8214. segmentDuration = frames.length * frameDuration;
  8215. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  8216. // frame info is in video clock cycles. Convert to match expectation of
  8217. // listeners (that all timestamps will be based on video clock cycles).
  8218. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  8219. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  8220. this.trigger('timingInfo', {
  8221. start: frames[0].pts,
  8222. end: frames[0].pts + segmentDuration
  8223. });
  8224. }
  8225. this.trigger('data', {
  8226. track: track,
  8227. boxes: boxes
  8228. });
  8229. this.trigger('done', 'AudioSegmentStream');
  8230. };
  8231. this.reset = function () {
  8232. trackDecodeInfo.clearDtsInfo(track);
  8233. adtsFrames = [];
  8234. this.trigger('reset');
  8235. };
  8236. };
  8237. AudioSegmentStream.prototype = new Stream();
  8238. /**
  8239. * Constructs a single-track, ISO BMFF media segment from H264 data
  8240. * events. The output of this stream can be fed to a SourceBuffer
  8241. * configured with a suitable initialization segment.
  8242. * @param track {object} track metadata configuration
  8243. * @param options {object} transmuxer options object
  8244. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  8245. * gopsToAlignWith list when attempting to align gop pts
  8246. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8247. * in the source; false to adjust the first segment to start at 0.
  8248. */
  8249. VideoSegmentStream = function (track, options) {
  8250. var sequenceNumber,
  8251. nalUnits = [],
  8252. gopsToAlignWith = [],
  8253. config,
  8254. pps;
  8255. options = options || {};
  8256. sequenceNumber = options.firstSequenceNumber || 0;
  8257. VideoSegmentStream.prototype.init.call(this);
  8258. delete track.minPTS;
  8259. this.gopCache_ = [];
  8260. /**
  8261. * Constructs a ISO BMFF segment given H264 nalUnits
  8262. * @param {Object} nalUnit A data event representing a nalUnit
  8263. * @param {String} nalUnit.nalUnitType
  8264. * @param {Object} nalUnit.config Properties for a mp4 track
  8265. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  8266. * @see lib/codecs/h264.js
  8267. **/
  8268. this.push = function (nalUnit) {
  8269. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  8270. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  8271. config = nalUnit.config;
  8272. track.sps = [nalUnit.data];
  8273. VIDEO_PROPERTIES.forEach(function (prop) {
  8274. track[prop] = config[prop];
  8275. }, this);
  8276. }
  8277. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  8278. pps = nalUnit.data;
  8279. track.pps = [nalUnit.data];
  8280. } // buffer video until flush() is called
  8281. nalUnits.push(nalUnit);
  8282. };
  8283. /**
  8284. * Pass constructed ISO BMFF track and boxes on to the
  8285. * next stream in the pipeline
  8286. **/
  8287. this.flush = function () {
  8288. var frames,
  8289. gopForFusion,
  8290. gops,
  8291. moof,
  8292. mdat,
  8293. boxes,
  8294. prependedContentDuration = 0,
  8295. firstGop,
  8296. lastGop; // Throw away nalUnits at the start of the byte stream until
  8297. // we find the first AUD
  8298. while (nalUnits.length) {
  8299. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  8300. break;
  8301. }
  8302. nalUnits.shift();
  8303. } // Return early if no video data has been observed
  8304. if (nalUnits.length === 0) {
  8305. this.resetStream_();
  8306. this.trigger('done', 'VideoSegmentStream');
  8307. return;
  8308. } // Organize the raw nal-units into arrays that represent
  8309. // higher-level constructs such as frames and gops
  8310. // (group-of-pictures)
  8311. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  8312. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  8313. // a problem since MSE (on Chrome) requires a leading keyframe.
  8314. //
  8315. // We have two approaches to repairing this situation:
  8316. // 1) GOP-FUSION:
  8317. // This is where we keep track of the GOPS (group-of-pictures)
  8318. // from previous fragments and attempt to find one that we can
  8319. // prepend to the current fragment in order to create a valid
  8320. // fragment.
  8321. // 2) KEYFRAME-PULLING:
  8322. // Here we search for the first keyframe in the fragment and
  8323. // throw away all the frames between the start of the fragment
  8324. // and that keyframe. We then extend the duration and pull the
  8325. // PTS of the keyframe forward so that it covers the time range
  8326. // of the frames that were disposed of.
  8327. //
  8328. // #1 is far prefereable over #2 which can cause "stuttering" but
  8329. // requires more things to be just right.
  8330. if (!gops[0][0].keyFrame) {
  8331. // Search for a gop for fusion from our gopCache
  8332. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  8333. if (gopForFusion) {
  8334. // in order to provide more accurate timing information about the segment, save
  8335. // the number of seconds prepended to the original segment due to GOP fusion
  8336. prependedContentDuration = gopForFusion.duration;
  8337. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  8338. // new gop at the beginning
  8339. gops.byteLength += gopForFusion.byteLength;
  8340. gops.nalCount += gopForFusion.nalCount;
  8341. gops.pts = gopForFusion.pts;
  8342. gops.dts = gopForFusion.dts;
  8343. gops.duration += gopForFusion.duration;
  8344. } else {
  8345. // If we didn't find a candidate gop fall back to keyframe-pulling
  8346. gops = frameUtils.extendFirstKeyFrame(gops);
  8347. }
  8348. } // Trim gops to align with gopsToAlignWith
  8349. if (gopsToAlignWith.length) {
  8350. var alignedGops;
  8351. if (options.alignGopsAtEnd) {
  8352. alignedGops = this.alignGopsAtEnd_(gops);
  8353. } else {
  8354. alignedGops = this.alignGopsAtStart_(gops);
  8355. }
  8356. if (!alignedGops) {
  8357. // save all the nals in the last GOP into the gop cache
  8358. this.gopCache_.unshift({
  8359. gop: gops.pop(),
  8360. pps: track.pps,
  8361. sps: track.sps
  8362. }); // Keep a maximum of 6 GOPs in the cache
  8363. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8364. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  8365. this.resetStream_();
  8366. this.trigger('done', 'VideoSegmentStream');
  8367. return;
  8368. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  8369. // when recalculated before sending off to CoalesceStream
  8370. trackDecodeInfo.clearDtsInfo(track);
  8371. gops = alignedGops;
  8372. }
  8373. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  8374. // samples (that is, frames) in the video data
  8375. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  8376. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  8377. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  8378. this.trigger('processedGopsInfo', gops.map(function (gop) {
  8379. return {
  8380. pts: gop.pts,
  8381. dts: gop.dts,
  8382. byteLength: gop.byteLength
  8383. };
  8384. }));
  8385. firstGop = gops[0];
  8386. lastGop = gops[gops.length - 1];
  8387. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  8388. this.trigger('timingInfo', {
  8389. start: gops[0].pts,
  8390. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  8391. }); // save all the nals in the last GOP into the gop cache
  8392. this.gopCache_.unshift({
  8393. gop: gops.pop(),
  8394. pps: track.pps,
  8395. sps: track.sps
  8396. }); // Keep a maximum of 6 GOPs in the cache
  8397. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8398. nalUnits = [];
  8399. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  8400. this.trigger('timelineStartInfo', track.timelineStartInfo);
  8401. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  8402. // throwing away hundreds of media segment fragments
  8403. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  8404. sequenceNumber++;
  8405. boxes.set(moof);
  8406. boxes.set(mdat, moof.byteLength);
  8407. this.trigger('data', {
  8408. track: track,
  8409. boxes: boxes
  8410. });
  8411. this.resetStream_(); // Continue with the flush process now
  8412. this.trigger('done', 'VideoSegmentStream');
  8413. };
  8414. this.reset = function () {
  8415. this.resetStream_();
  8416. nalUnits = [];
  8417. this.gopCache_.length = 0;
  8418. gopsToAlignWith.length = 0;
  8419. this.trigger('reset');
  8420. };
  8421. this.resetStream_ = function () {
  8422. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  8423. // for instance, when we are rendition switching
  8424. config = undefined;
  8425. pps = undefined;
  8426. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  8427. // return it or return null if no good candidate was found
  8428. this.getGopForFusion_ = function (nalUnit) {
  8429. var halfSecond = 45000,
  8430. // Half-a-second in a 90khz clock
  8431. allowableOverlap = 10000,
  8432. // About 3 frames @ 30fps
  8433. nearestDistance = Infinity,
  8434. dtsDistance,
  8435. nearestGopObj,
  8436. currentGop,
  8437. currentGopObj,
  8438. i; // Search for the GOP nearest to the beginning of this nal unit
  8439. for (i = 0; i < this.gopCache_.length; i++) {
  8440. currentGopObj = this.gopCache_[i];
  8441. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  8442. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  8443. continue;
  8444. } // Reject Gops that would require a negative baseMediaDecodeTime
  8445. if (currentGop.dts < track.timelineStartInfo.dts) {
  8446. continue;
  8447. } // The distance between the end of the gop and the start of the nalUnit
  8448. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  8449. // a half-second of the nal unit
  8450. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  8451. // Always use the closest GOP we found if there is more than
  8452. // one candidate
  8453. if (!nearestGopObj || nearestDistance > dtsDistance) {
  8454. nearestGopObj = currentGopObj;
  8455. nearestDistance = dtsDistance;
  8456. }
  8457. }
  8458. }
  8459. if (nearestGopObj) {
  8460. return nearestGopObj.gop;
  8461. }
  8462. return null;
  8463. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  8464. // of gopsToAlignWith starting from the START of the list
  8465. this.alignGopsAtStart_ = function (gops) {
  8466. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  8467. byteLength = gops.byteLength;
  8468. nalCount = gops.nalCount;
  8469. duration = gops.duration;
  8470. alignIndex = gopIndex = 0;
  8471. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  8472. align = gopsToAlignWith[alignIndex];
  8473. gop = gops[gopIndex];
  8474. if (align.pts === gop.pts) {
  8475. break;
  8476. }
  8477. if (gop.pts > align.pts) {
  8478. // this current gop starts after the current gop we want to align on, so increment
  8479. // align index
  8480. alignIndex++;
  8481. continue;
  8482. } // current gop starts before the current gop we want to align on. so increment gop
  8483. // index
  8484. gopIndex++;
  8485. byteLength -= gop.byteLength;
  8486. nalCount -= gop.nalCount;
  8487. duration -= gop.duration;
  8488. }
  8489. if (gopIndex === 0) {
  8490. // no gops to trim
  8491. return gops;
  8492. }
  8493. if (gopIndex === gops.length) {
  8494. // all gops trimmed, skip appending all gops
  8495. return null;
  8496. }
  8497. alignedGops = gops.slice(gopIndex);
  8498. alignedGops.byteLength = byteLength;
  8499. alignedGops.duration = duration;
  8500. alignedGops.nalCount = nalCount;
  8501. alignedGops.pts = alignedGops[0].pts;
  8502. alignedGops.dts = alignedGops[0].dts;
  8503. return alignedGops;
  8504. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  8505. // of gopsToAlignWith starting from the END of the list
  8506. this.alignGopsAtEnd_ = function (gops) {
  8507. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  8508. alignIndex = gopsToAlignWith.length - 1;
  8509. gopIndex = gops.length - 1;
  8510. alignEndIndex = null;
  8511. matchFound = false;
  8512. while (alignIndex >= 0 && gopIndex >= 0) {
  8513. align = gopsToAlignWith[alignIndex];
  8514. gop = gops[gopIndex];
  8515. if (align.pts === gop.pts) {
  8516. matchFound = true;
  8517. break;
  8518. }
  8519. if (align.pts > gop.pts) {
  8520. alignIndex--;
  8521. continue;
  8522. }
  8523. if (alignIndex === gopsToAlignWith.length - 1) {
  8524. // gop.pts is greater than the last alignment candidate. If no match is found
  8525. // by the end of this loop, we still want to append gops that come after this
  8526. // point
  8527. alignEndIndex = gopIndex;
  8528. }
  8529. gopIndex--;
  8530. }
  8531. if (!matchFound && alignEndIndex === null) {
  8532. return null;
  8533. }
  8534. var trimIndex;
  8535. if (matchFound) {
  8536. trimIndex = gopIndex;
  8537. } else {
  8538. trimIndex = alignEndIndex;
  8539. }
  8540. if (trimIndex === 0) {
  8541. return gops;
  8542. }
  8543. var alignedGops = gops.slice(trimIndex);
  8544. var metadata = alignedGops.reduce(function (total, gop) {
  8545. total.byteLength += gop.byteLength;
  8546. total.duration += gop.duration;
  8547. total.nalCount += gop.nalCount;
  8548. return total;
  8549. }, {
  8550. byteLength: 0,
  8551. duration: 0,
  8552. nalCount: 0
  8553. });
  8554. alignedGops.byteLength = metadata.byteLength;
  8555. alignedGops.duration = metadata.duration;
  8556. alignedGops.nalCount = metadata.nalCount;
  8557. alignedGops.pts = alignedGops[0].pts;
  8558. alignedGops.dts = alignedGops[0].dts;
  8559. return alignedGops;
  8560. };
  8561. this.alignGopsWith = function (newGopsToAlignWith) {
  8562. gopsToAlignWith = newGopsToAlignWith;
  8563. };
  8564. };
  8565. VideoSegmentStream.prototype = new Stream();
  8566. /**
  8567. * A Stream that can combine multiple streams (ie. audio & video)
  8568. * into a single output segment for MSE. Also supports audio-only
  8569. * and video-only streams.
  8570. * @param options {object} transmuxer options object
  8571. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8572. * in the source; false to adjust the first segment to start at media timeline start.
  8573. */
  8574. CoalesceStream = function (options, metadataStream) {
  8575. // Number of Tracks per output segment
  8576. // If greater than 1, we combine multiple
  8577. // tracks into a single segment
  8578. this.numberOfTracks = 0;
  8579. this.metadataStream = metadataStream;
  8580. options = options || {};
  8581. if (typeof options.remux !== 'undefined') {
  8582. this.remuxTracks = !!options.remux;
  8583. } else {
  8584. this.remuxTracks = true;
  8585. }
  8586. if (typeof options.keepOriginalTimestamps === 'boolean') {
  8587. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  8588. } else {
  8589. this.keepOriginalTimestamps = false;
  8590. }
  8591. this.pendingTracks = [];
  8592. this.videoTrack = null;
  8593. this.pendingBoxes = [];
  8594. this.pendingCaptions = [];
  8595. this.pendingMetadata = [];
  8596. this.pendingBytes = 0;
  8597. this.emittedTracks = 0;
  8598. CoalesceStream.prototype.init.call(this); // Take output from multiple
  8599. this.push = function (output) {
  8600. // buffer incoming captions until the associated video segment
  8601. // finishes
  8602. if (output.text) {
  8603. return this.pendingCaptions.push(output);
  8604. } // buffer incoming id3 tags until the final flush
  8605. if (output.frames) {
  8606. return this.pendingMetadata.push(output);
  8607. } // Add this track to the list of pending tracks and store
  8608. // important information required for the construction of
  8609. // the final segment
  8610. this.pendingTracks.push(output.track);
  8611. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  8612. // We unshift audio and push video because
  8613. // as of Chrome 75 when switching from
  8614. // one init segment to another if the video
  8615. // mdat does not appear after the audio mdat
  8616. // only audio will play for the duration of our transmux.
  8617. if (output.track.type === 'video') {
  8618. this.videoTrack = output.track;
  8619. this.pendingBoxes.push(output.boxes);
  8620. }
  8621. if (output.track.type === 'audio') {
  8622. this.audioTrack = output.track;
  8623. this.pendingBoxes.unshift(output.boxes);
  8624. }
  8625. };
  8626. };
  8627. CoalesceStream.prototype = new Stream();
  8628. CoalesceStream.prototype.flush = function (flushSource) {
  8629. var offset = 0,
  8630. event = {
  8631. captions: [],
  8632. captionStreams: {},
  8633. metadata: [],
  8634. info: {}
  8635. },
  8636. caption,
  8637. id3,
  8638. initSegment,
  8639. timelineStartPts = 0,
  8640. i;
  8641. if (this.pendingTracks.length < this.numberOfTracks) {
  8642. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  8643. // Return because we haven't received a flush from a data-generating
  8644. // portion of the segment (meaning that we have only recieved meta-data
  8645. // or captions.)
  8646. return;
  8647. } else if (this.remuxTracks) {
  8648. // Return until we have enough tracks from the pipeline to remux (if we
  8649. // are remuxing audio and video into a single MP4)
  8650. return;
  8651. } else if (this.pendingTracks.length === 0) {
  8652. // In the case where we receive a flush without any data having been
  8653. // received we consider it an emitted track for the purposes of coalescing
  8654. // `done` events.
  8655. // We do this for the case where there is an audio and video track in the
  8656. // segment but no audio data. (seen in several playlists with alternate
  8657. // audio tracks and no audio present in the main TS segments.)
  8658. this.emittedTracks++;
  8659. if (this.emittedTracks >= this.numberOfTracks) {
  8660. this.trigger('done');
  8661. this.emittedTracks = 0;
  8662. }
  8663. return;
  8664. }
  8665. }
  8666. if (this.videoTrack) {
  8667. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  8668. VIDEO_PROPERTIES.forEach(function (prop) {
  8669. event.info[prop] = this.videoTrack[prop];
  8670. }, this);
  8671. } else if (this.audioTrack) {
  8672. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  8673. AUDIO_PROPERTIES.forEach(function (prop) {
  8674. event.info[prop] = this.audioTrack[prop];
  8675. }, this);
  8676. }
  8677. if (this.videoTrack || this.audioTrack) {
  8678. if (this.pendingTracks.length === 1) {
  8679. event.type = this.pendingTracks[0].type;
  8680. } else {
  8681. event.type = 'combined';
  8682. }
  8683. this.emittedTracks += this.pendingTracks.length;
  8684. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  8685. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  8686. // and track definitions
  8687. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  8688. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  8689. for (i = 0; i < this.pendingBoxes.length; i++) {
  8690. event.data.set(this.pendingBoxes[i], offset);
  8691. offset += this.pendingBoxes[i].byteLength;
  8692. } // Translate caption PTS times into second offsets to match the
  8693. // video timeline for the segment, and add track info
  8694. for (i = 0; i < this.pendingCaptions.length; i++) {
  8695. caption = this.pendingCaptions[i];
  8696. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  8697. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  8698. event.captionStreams[caption.stream] = true;
  8699. event.captions.push(caption);
  8700. } // Translate ID3 frame PTS times into second offsets to match the
  8701. // video timeline for the segment
  8702. for (i = 0; i < this.pendingMetadata.length; i++) {
  8703. id3 = this.pendingMetadata[i];
  8704. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  8705. event.metadata.push(id3);
  8706. } // We add this to every single emitted segment even though we only need
  8707. // it for the first
  8708. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  8709. this.pendingTracks.length = 0;
  8710. this.videoTrack = null;
  8711. this.pendingBoxes.length = 0;
  8712. this.pendingCaptions.length = 0;
  8713. this.pendingBytes = 0;
  8714. this.pendingMetadata.length = 0; // Emit the built segment
  8715. // We include captions and ID3 tags for backwards compatibility,
  8716. // ideally we should send only video and audio in the data event
  8717. this.trigger('data', event); // Emit each caption to the outside world
  8718. // Ideally, this would happen immediately on parsing captions,
  8719. // but we need to ensure that video data is sent back first
  8720. // so that caption timing can be adjusted to match video timing
  8721. for (i = 0; i < event.captions.length; i++) {
  8722. caption = event.captions[i];
  8723. this.trigger('caption', caption);
  8724. } // Emit each id3 tag to the outside world
  8725. // Ideally, this would happen immediately on parsing the tag,
  8726. // but we need to ensure that video data is sent back first
  8727. // so that ID3 frame timing can be adjusted to match video timing
  8728. for (i = 0; i < event.metadata.length; i++) {
  8729. id3 = event.metadata[i];
  8730. this.trigger('id3Frame', id3);
  8731. }
  8732. } // Only emit `done` if all tracks have been flushed and emitted
  8733. if (this.emittedTracks >= this.numberOfTracks) {
  8734. this.trigger('done');
  8735. this.emittedTracks = 0;
  8736. }
  8737. };
  8738. CoalesceStream.prototype.setRemux = function (val) {
  8739. this.remuxTracks = val;
  8740. };
  8741. /**
  8742. * A Stream that expects MP2T binary data as input and produces
  8743. * corresponding media segments, suitable for use with Media Source
  8744. * Extension (MSE) implementations that support the ISO BMFF byte
  8745. * stream format, like Chrome.
  8746. */
  8747. Transmuxer = function (options) {
  8748. var self = this,
  8749. hasFlushed = true,
  8750. videoTrack,
  8751. audioTrack;
  8752. Transmuxer.prototype.init.call(this);
  8753. options = options || {};
  8754. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  8755. this.transmuxPipeline_ = {};
  8756. this.setupAacPipeline = function () {
  8757. var pipeline = {};
  8758. this.transmuxPipeline_ = pipeline;
  8759. pipeline.type = 'aac';
  8760. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  8761. pipeline.aacStream = new AacStream();
  8762. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  8763. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  8764. pipeline.adtsStream = new AdtsStream();
  8765. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  8766. pipeline.headOfPipeline = pipeline.aacStream;
  8767. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  8768. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  8769. pipeline.metadataStream.on('timestamp', function (frame) {
  8770. pipeline.aacStream.setTimestamp(frame.timeStamp);
  8771. });
  8772. pipeline.aacStream.on('data', function (data) {
  8773. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  8774. return;
  8775. }
  8776. audioTrack = audioTrack || {
  8777. timelineStartInfo: {
  8778. baseMediaDecodeTime: self.baseMediaDecodeTime
  8779. },
  8780. codec: 'adts',
  8781. type: 'audio'
  8782. }; // hook up the audio segment stream to the first track with aac data
  8783. pipeline.coalesceStream.numberOfTracks++;
  8784. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  8785. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  8786. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  8787. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  8788. self.trigger('trackinfo', {
  8789. hasAudio: !!audioTrack,
  8790. hasVideo: !!videoTrack
  8791. });
  8792. }); // Re-emit any data coming from the coalesce stream to the outside world
  8793. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  8794. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  8795. addPipelineLogRetriggers(this, pipeline);
  8796. };
  8797. this.setupTsPipeline = function () {
  8798. var pipeline = {};
  8799. this.transmuxPipeline_ = pipeline;
  8800. pipeline.type = 'ts';
  8801. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  8802. pipeline.packetStream = new m2ts.TransportPacketStream();
  8803. pipeline.parseStream = new m2ts.TransportParseStream();
  8804. pipeline.elementaryStream = new m2ts.ElementaryStream();
  8805. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  8806. pipeline.adtsStream = new AdtsStream();
  8807. pipeline.h264Stream = new H264Stream();
  8808. pipeline.captionStream = new m2ts.CaptionStream(options);
  8809. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  8810. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  8811. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  8812. // demux the streams
  8813. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  8814. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  8815. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  8816. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  8817. pipeline.elementaryStream.on('data', function (data) {
  8818. var i;
  8819. if (data.type === 'metadata') {
  8820. i = data.tracks.length; // scan the tracks listed in the metadata
  8821. while (i--) {
  8822. if (!videoTrack && data.tracks[i].type === 'video') {
  8823. videoTrack = data.tracks[i];
  8824. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  8825. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  8826. audioTrack = data.tracks[i];
  8827. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  8828. }
  8829. } // hook up the video segment stream to the first track with h264 data
  8830. if (videoTrack && !pipeline.videoSegmentStream) {
  8831. pipeline.coalesceStream.numberOfTracks++;
  8832. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  8833. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  8834. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  8835. // When video emits timelineStartInfo data after a flush, we forward that
  8836. // info to the AudioSegmentStream, if it exists, because video timeline
  8837. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  8838. // because this is a particularly subtle form of timestamp alteration.
  8839. if (audioTrack && !options.keepOriginalTimestamps) {
  8840. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  8841. // very earliest DTS we have seen in video because Chrome will
  8842. // interpret any video track with a baseMediaDecodeTime that is
  8843. // non-zero as a gap.
  8844. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  8845. }
  8846. });
  8847. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  8848. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  8849. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  8850. if (audioTrack) {
  8851. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  8852. }
  8853. });
  8854. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  8855. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  8856. }
  8857. if (audioTrack && !pipeline.audioSegmentStream) {
  8858. // hook up the audio segment stream to the first track with aac data
  8859. pipeline.coalesceStream.numberOfTracks++;
  8860. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  8861. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  8862. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  8863. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  8864. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  8865. } // emit pmt info
  8866. self.trigger('trackinfo', {
  8867. hasAudio: !!audioTrack,
  8868. hasVideo: !!videoTrack
  8869. });
  8870. }
  8871. }); // Re-emit any data coming from the coalesce stream to the outside world
  8872. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  8873. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  8874. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  8875. self.trigger('id3Frame', id3Frame);
  8876. });
  8877. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  8878. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  8879. addPipelineLogRetriggers(this, pipeline);
  8880. }; // hook up the segment streams once track metadata is delivered
  8881. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  8882. var pipeline = this.transmuxPipeline_;
  8883. if (!options.keepOriginalTimestamps) {
  8884. this.baseMediaDecodeTime = baseMediaDecodeTime;
  8885. }
  8886. if (audioTrack) {
  8887. audioTrack.timelineStartInfo.dts = undefined;
  8888. audioTrack.timelineStartInfo.pts = undefined;
  8889. trackDecodeInfo.clearDtsInfo(audioTrack);
  8890. if (pipeline.audioTimestampRolloverStream) {
  8891. pipeline.audioTimestampRolloverStream.discontinuity();
  8892. }
  8893. }
  8894. if (videoTrack) {
  8895. if (pipeline.videoSegmentStream) {
  8896. pipeline.videoSegmentStream.gopCache_ = [];
  8897. }
  8898. videoTrack.timelineStartInfo.dts = undefined;
  8899. videoTrack.timelineStartInfo.pts = undefined;
  8900. trackDecodeInfo.clearDtsInfo(videoTrack);
  8901. pipeline.captionStream.reset();
  8902. }
  8903. if (pipeline.timestampRolloverStream) {
  8904. pipeline.timestampRolloverStream.discontinuity();
  8905. }
  8906. };
  8907. this.setAudioAppendStart = function (timestamp) {
  8908. if (audioTrack) {
  8909. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  8910. }
  8911. };
  8912. this.setRemux = function (val) {
  8913. var pipeline = this.transmuxPipeline_;
  8914. options.remux = val;
  8915. if (pipeline && pipeline.coalesceStream) {
  8916. pipeline.coalesceStream.setRemux(val);
  8917. }
  8918. };
  8919. this.alignGopsWith = function (gopsToAlignWith) {
  8920. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  8921. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  8922. }
  8923. };
  8924. this.getLogTrigger_ = function (key) {
  8925. var self = this;
  8926. return function (event) {
  8927. event.stream = key;
  8928. self.trigger('log', event);
  8929. };
  8930. }; // feed incoming data to the front of the parsing pipeline
  8931. this.push = function (data) {
  8932. if (hasFlushed) {
  8933. var isAac = isLikelyAacData(data);
  8934. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  8935. this.setupAacPipeline();
  8936. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  8937. this.setupTsPipeline();
  8938. }
  8939. hasFlushed = false;
  8940. }
  8941. this.transmuxPipeline_.headOfPipeline.push(data);
  8942. }; // flush any buffered data
  8943. this.flush = function () {
  8944. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  8945. this.transmuxPipeline_.headOfPipeline.flush();
  8946. };
  8947. this.endTimeline = function () {
  8948. this.transmuxPipeline_.headOfPipeline.endTimeline();
  8949. };
  8950. this.reset = function () {
  8951. if (this.transmuxPipeline_.headOfPipeline) {
  8952. this.transmuxPipeline_.headOfPipeline.reset();
  8953. }
  8954. }; // Caption data has to be reset when seeking outside buffered range
  8955. this.resetCaptions = function () {
  8956. if (this.transmuxPipeline_.captionStream) {
  8957. this.transmuxPipeline_.captionStream.reset();
  8958. }
  8959. };
  8960. };
  8961. Transmuxer.prototype = new Stream();
  8962. var transmuxer = {
  8963. Transmuxer: Transmuxer,
  8964. VideoSegmentStream: VideoSegmentStream,
  8965. AudioSegmentStream: AudioSegmentStream,
  8966. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  8967. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  8968. // exported for testing
  8969. generateSegmentTimingInfo: generateSegmentTimingInfo
  8970. };
  8971. /**
  8972. * mux.js
  8973. *
  8974. * Copyright (c) Brightcove
  8975. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8976. */
  8977. var toUnsigned$3 = function (value) {
  8978. return value >>> 0;
  8979. };
  8980. var toHexString$1 = function (value) {
  8981. return ('00' + value.toString(16)).slice(-2);
  8982. };
  8983. var bin = {
  8984. toUnsigned: toUnsigned$3,
  8985. toHexString: toHexString$1
  8986. };
  8987. var parseType$3 = function (buffer) {
  8988. var result = '';
  8989. result += String.fromCharCode(buffer[0]);
  8990. result += String.fromCharCode(buffer[1]);
  8991. result += String.fromCharCode(buffer[2]);
  8992. result += String.fromCharCode(buffer[3]);
  8993. return result;
  8994. };
  8995. var parseType_1 = parseType$3;
  8996. var toUnsigned$2 = bin.toUnsigned;
  8997. var parseType$2 = parseType_1;
  8998. var findBox$2 = function (data, path) {
  8999. var results = [],
  9000. i,
  9001. size,
  9002. type,
  9003. end,
  9004. subresults;
  9005. if (!path.length) {
  9006. // short-circuit the search for empty paths
  9007. return null;
  9008. }
  9009. for (i = 0; i < data.byteLength;) {
  9010. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  9011. type = parseType$2(data.subarray(i + 4, i + 8));
  9012. end = size > 1 ? i + size : data.byteLength;
  9013. if (type === path[0]) {
  9014. if (path.length === 1) {
  9015. // this is the end of the path and we've found the box we were
  9016. // looking for
  9017. results.push(data.subarray(i + 8, end));
  9018. } else {
  9019. // recursively search for the next box along the path
  9020. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  9021. if (subresults.length) {
  9022. results = results.concat(subresults);
  9023. }
  9024. }
  9025. }
  9026. i = end;
  9027. } // we've finished searching all of data
  9028. return results;
  9029. };
  9030. var findBox_1 = findBox$2;
  9031. var toUnsigned$1 = bin.toUnsigned;
  9032. var getUint64$2 = numbers.getUint64;
  9033. var tfdt = function (data) {
  9034. var result = {
  9035. version: data[0],
  9036. flags: new Uint8Array(data.subarray(1, 4))
  9037. };
  9038. if (result.version === 1) {
  9039. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  9040. } else {
  9041. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  9042. }
  9043. return result;
  9044. };
  9045. var parseTfdt$2 = tfdt;
  9046. var parseSampleFlags$1 = function (flags) {
  9047. return {
  9048. isLeading: (flags[0] & 0x0c) >>> 2,
  9049. dependsOn: flags[0] & 0x03,
  9050. isDependedOn: (flags[1] & 0xc0) >>> 6,
  9051. hasRedundancy: (flags[1] & 0x30) >>> 4,
  9052. paddingValue: (flags[1] & 0x0e) >>> 1,
  9053. isNonSyncSample: flags[1] & 0x01,
  9054. degradationPriority: flags[2] << 8 | flags[3]
  9055. };
  9056. };
  9057. var parseSampleFlags_1 = parseSampleFlags$1;
  9058. var parseSampleFlags = parseSampleFlags_1;
  9059. var trun = function (data) {
  9060. var result = {
  9061. version: data[0],
  9062. flags: new Uint8Array(data.subarray(1, 4)),
  9063. samples: []
  9064. },
  9065. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9066. // Flag interpretation
  9067. dataOffsetPresent = result.flags[2] & 0x01,
  9068. // compare with 2nd byte of 0x1
  9069. firstSampleFlagsPresent = result.flags[2] & 0x04,
  9070. // compare with 2nd byte of 0x4
  9071. sampleDurationPresent = result.flags[1] & 0x01,
  9072. // compare with 2nd byte of 0x100
  9073. sampleSizePresent = result.flags[1] & 0x02,
  9074. // compare with 2nd byte of 0x200
  9075. sampleFlagsPresent = result.flags[1] & 0x04,
  9076. // compare with 2nd byte of 0x400
  9077. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  9078. // compare with 2nd byte of 0x800
  9079. sampleCount = view.getUint32(4),
  9080. offset = 8,
  9081. sample;
  9082. if (dataOffsetPresent) {
  9083. // 32 bit signed integer
  9084. result.dataOffset = view.getInt32(offset);
  9085. offset += 4;
  9086. } // Overrides the flags for the first sample only. The order of
  9087. // optional values will be: duration, size, compositionTimeOffset
  9088. if (firstSampleFlagsPresent && sampleCount) {
  9089. sample = {
  9090. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  9091. };
  9092. offset += 4;
  9093. if (sampleDurationPresent) {
  9094. sample.duration = view.getUint32(offset);
  9095. offset += 4;
  9096. }
  9097. if (sampleSizePresent) {
  9098. sample.size = view.getUint32(offset);
  9099. offset += 4;
  9100. }
  9101. if (sampleCompositionTimeOffsetPresent) {
  9102. if (result.version === 1) {
  9103. sample.compositionTimeOffset = view.getInt32(offset);
  9104. } else {
  9105. sample.compositionTimeOffset = view.getUint32(offset);
  9106. }
  9107. offset += 4;
  9108. }
  9109. result.samples.push(sample);
  9110. sampleCount--;
  9111. }
  9112. while (sampleCount--) {
  9113. sample = {};
  9114. if (sampleDurationPresent) {
  9115. sample.duration = view.getUint32(offset);
  9116. offset += 4;
  9117. }
  9118. if (sampleSizePresent) {
  9119. sample.size = view.getUint32(offset);
  9120. offset += 4;
  9121. }
  9122. if (sampleFlagsPresent) {
  9123. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  9124. offset += 4;
  9125. }
  9126. if (sampleCompositionTimeOffsetPresent) {
  9127. if (result.version === 1) {
  9128. sample.compositionTimeOffset = view.getInt32(offset);
  9129. } else {
  9130. sample.compositionTimeOffset = view.getUint32(offset);
  9131. }
  9132. offset += 4;
  9133. }
  9134. result.samples.push(sample);
  9135. }
  9136. return result;
  9137. };
  9138. var parseTrun$2 = trun;
  9139. var tfhd = function (data) {
  9140. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9141. result = {
  9142. version: data[0],
  9143. flags: new Uint8Array(data.subarray(1, 4)),
  9144. trackId: view.getUint32(4)
  9145. },
  9146. baseDataOffsetPresent = result.flags[2] & 0x01,
  9147. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  9148. defaultSampleDurationPresent = result.flags[2] & 0x08,
  9149. defaultSampleSizePresent = result.flags[2] & 0x10,
  9150. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  9151. durationIsEmpty = result.flags[0] & 0x010000,
  9152. defaultBaseIsMoof = result.flags[0] & 0x020000,
  9153. i;
  9154. i = 8;
  9155. if (baseDataOffsetPresent) {
  9156. i += 4; // truncate top 4 bytes
  9157. // FIXME: should we read the full 64 bits?
  9158. result.baseDataOffset = view.getUint32(12);
  9159. i += 4;
  9160. }
  9161. if (sampleDescriptionIndexPresent) {
  9162. result.sampleDescriptionIndex = view.getUint32(i);
  9163. i += 4;
  9164. }
  9165. if (defaultSampleDurationPresent) {
  9166. result.defaultSampleDuration = view.getUint32(i);
  9167. i += 4;
  9168. }
  9169. if (defaultSampleSizePresent) {
  9170. result.defaultSampleSize = view.getUint32(i);
  9171. i += 4;
  9172. }
  9173. if (defaultSampleFlagsPresent) {
  9174. result.defaultSampleFlags = view.getUint32(i);
  9175. }
  9176. if (durationIsEmpty) {
  9177. result.durationIsEmpty = true;
  9178. }
  9179. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  9180. result.baseDataOffsetIsMoof = true;
  9181. }
  9182. return result;
  9183. };
  9184. var parseTfhd$2 = tfhd;
  9185. var win;
  9186. if (typeof window !== "undefined") {
  9187. win = window;
  9188. } else if (typeof commonjsGlobal !== "undefined") {
  9189. win = commonjsGlobal;
  9190. } else if (typeof self !== "undefined") {
  9191. win = self;
  9192. } else {
  9193. win = {};
  9194. }
  9195. var window_1 = win;
  9196. /**
  9197. * mux.js
  9198. *
  9199. * Copyright (c) Brightcove
  9200. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9201. *
  9202. * Reads in-band CEA-708 captions out of FMP4 segments.
  9203. * @see https://en.wikipedia.org/wiki/CEA-708
  9204. */
  9205. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  9206. var CaptionStream = captionStream.CaptionStream;
  9207. var findBox$1 = findBox_1;
  9208. var parseTfdt$1 = parseTfdt$2;
  9209. var parseTrun$1 = parseTrun$2;
  9210. var parseTfhd$1 = parseTfhd$2;
  9211. var window$2 = window_1;
  9212. /**
  9213. * Maps an offset in the mdat to a sample based on the the size of the samples.
  9214. * Assumes that `parseSamples` has been called first.
  9215. *
  9216. * @param {Number} offset - The offset into the mdat
  9217. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  9218. * @return {?Object} The matching sample, or null if no match was found.
  9219. *
  9220. * @see ISO-BMFF-12/2015, Section 8.8.8
  9221. **/
  9222. var mapToSample = function (offset, samples) {
  9223. var approximateOffset = offset;
  9224. for (var i = 0; i < samples.length; i++) {
  9225. var sample = samples[i];
  9226. if (approximateOffset < sample.size) {
  9227. return sample;
  9228. }
  9229. approximateOffset -= sample.size;
  9230. }
  9231. return null;
  9232. };
  9233. /**
  9234. * Finds SEI nal units contained in a Media Data Box.
  9235. * Assumes that `parseSamples` has been called first.
  9236. *
  9237. * @param {Uint8Array} avcStream - The bytes of the mdat
  9238. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  9239. * @param {Number} trackId - The trackId of this video track
  9240. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  9241. * The contents of the seiNal should match what is expected by
  9242. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  9243. *
  9244. * @see ISO-BMFF-12/2015, Section 8.1.1
  9245. * @see Rec. ITU-T H.264, 7.3.2.3.1
  9246. **/
  9247. var findSeiNals = function (avcStream, samples, trackId) {
  9248. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  9249. result = {
  9250. logs: [],
  9251. seiNals: []
  9252. },
  9253. seiNal,
  9254. i,
  9255. length,
  9256. lastMatchedSample;
  9257. for (i = 0; i + 4 < avcStream.length; i += length) {
  9258. length = avcView.getUint32(i);
  9259. i += 4; // Bail if this doesn't appear to be an H264 stream
  9260. if (length <= 0) {
  9261. continue;
  9262. }
  9263. switch (avcStream[i] & 0x1F) {
  9264. case 0x06:
  9265. var data = avcStream.subarray(i + 1, i + 1 + length);
  9266. var matchingSample = mapToSample(i, samples);
  9267. seiNal = {
  9268. nalUnitType: 'sei_rbsp',
  9269. size: length,
  9270. data: data,
  9271. escapedRBSP: discardEmulationPreventionBytes(data),
  9272. trackId: trackId
  9273. };
  9274. if (matchingSample) {
  9275. seiNal.pts = matchingSample.pts;
  9276. seiNal.dts = matchingSample.dts;
  9277. lastMatchedSample = matchingSample;
  9278. } else if (lastMatchedSample) {
  9279. // If a matching sample cannot be found, use the last
  9280. // sample's values as they should be as close as possible
  9281. seiNal.pts = lastMatchedSample.pts;
  9282. seiNal.dts = lastMatchedSample.dts;
  9283. } else {
  9284. result.logs.push({
  9285. level: 'warn',
  9286. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  9287. });
  9288. break;
  9289. }
  9290. result.seiNals.push(seiNal);
  9291. break;
  9292. }
  9293. }
  9294. return result;
  9295. };
  9296. /**
  9297. * Parses sample information out of Track Run Boxes and calculates
  9298. * the absolute presentation and decode timestamps of each sample.
  9299. *
  9300. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  9301. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  9302. @see ISO-BMFF-12/2015, Section 8.8.12
  9303. * @param {Object} tfhd - The parsed Track Fragment Header
  9304. * @see inspect.parseTfhd
  9305. * @return {Object[]} the parsed samples
  9306. *
  9307. * @see ISO-BMFF-12/2015, Section 8.8.8
  9308. **/
  9309. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  9310. var currentDts = baseMediaDecodeTime;
  9311. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  9312. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  9313. var trackId = tfhd.trackId;
  9314. var allSamples = [];
  9315. truns.forEach(function (trun) {
  9316. // Note: We currently do not parse the sample table as well
  9317. // as the trun. It's possible some sources will require this.
  9318. // moov > trak > mdia > minf > stbl
  9319. var trackRun = parseTrun$1(trun);
  9320. var samples = trackRun.samples;
  9321. samples.forEach(function (sample) {
  9322. if (sample.duration === undefined) {
  9323. sample.duration = defaultSampleDuration;
  9324. }
  9325. if (sample.size === undefined) {
  9326. sample.size = defaultSampleSize;
  9327. }
  9328. sample.trackId = trackId;
  9329. sample.dts = currentDts;
  9330. if (sample.compositionTimeOffset === undefined) {
  9331. sample.compositionTimeOffset = 0;
  9332. }
  9333. if (typeof currentDts === 'bigint') {
  9334. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  9335. currentDts += window$2.BigInt(sample.duration);
  9336. } else {
  9337. sample.pts = currentDts + sample.compositionTimeOffset;
  9338. currentDts += sample.duration;
  9339. }
  9340. });
  9341. allSamples = allSamples.concat(samples);
  9342. });
  9343. return allSamples;
  9344. };
  9345. /**
  9346. * Parses out caption nals from an FMP4 segment's video tracks.
  9347. *
  9348. * @param {Uint8Array} segment - The bytes of a single segment
  9349. * @param {Number} videoTrackId - The trackId of a video track in the segment
  9350. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  9351. * a list of seiNals found in that track
  9352. **/
  9353. var parseCaptionNals = function (segment, videoTrackId) {
  9354. // To get the samples
  9355. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  9356. var mdats = findBox$1(segment, ['mdat']);
  9357. var captionNals = {};
  9358. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  9359. mdats.forEach(function (mdat, index) {
  9360. var matchingTraf = trafs[index];
  9361. mdatTrafPairs.push({
  9362. mdat: mdat,
  9363. traf: matchingTraf
  9364. });
  9365. });
  9366. mdatTrafPairs.forEach(function (pair) {
  9367. var mdat = pair.mdat;
  9368. var traf = pair.traf;
  9369. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  9370. var headerInfo = parseTfhd$1(tfhd[0]);
  9371. var trackId = headerInfo.trackId;
  9372. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  9373. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  9374. var truns = findBox$1(traf, ['trun']);
  9375. var samples;
  9376. var result; // Only parse video data for the chosen video track
  9377. if (videoTrackId === trackId && truns.length > 0) {
  9378. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  9379. result = findSeiNals(mdat, samples, trackId);
  9380. if (!captionNals[trackId]) {
  9381. captionNals[trackId] = {
  9382. seiNals: [],
  9383. logs: []
  9384. };
  9385. }
  9386. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  9387. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  9388. }
  9389. });
  9390. return captionNals;
  9391. };
  9392. /**
  9393. * Parses out inband captions from an MP4 container and returns
  9394. * caption objects that can be used by WebVTT and the TextTrack API.
  9395. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  9396. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  9397. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  9398. *
  9399. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9400. * @param {Number} trackId - The id of the video track to parse
  9401. * @param {Number} timescale - The timescale for the video track from the init segment
  9402. *
  9403. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  9404. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  9405. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  9406. * @return {String} parsedCaptions[].text - The visible content of the caption
  9407. **/
  9408. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  9409. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9410. if (trackId === null) {
  9411. return null;
  9412. }
  9413. captionNals = parseCaptionNals(segment, trackId);
  9414. var trackNals = captionNals[trackId] || {};
  9415. return {
  9416. seiNals: trackNals.seiNals,
  9417. logs: trackNals.logs,
  9418. timescale: timescale
  9419. };
  9420. };
  9421. /**
  9422. * Converts SEI NALUs into captions that can be used by video.js
  9423. **/
  9424. var CaptionParser = function () {
  9425. var isInitialized = false;
  9426. var captionStream; // Stores segments seen before trackId and timescale are set
  9427. var segmentCache; // Stores video track ID of the track being parsed
  9428. var trackId; // Stores the timescale of the track being parsed
  9429. var timescale; // Stores captions parsed so far
  9430. var parsedCaptions; // Stores whether we are receiving partial data or not
  9431. var parsingPartial;
  9432. /**
  9433. * A method to indicate whether a CaptionParser has been initalized
  9434. * @returns {Boolean}
  9435. **/
  9436. this.isInitialized = function () {
  9437. return isInitialized;
  9438. };
  9439. /**
  9440. * Initializes the underlying CaptionStream, SEI NAL parsing
  9441. * and management, and caption collection
  9442. **/
  9443. this.init = function (options) {
  9444. captionStream = new CaptionStream();
  9445. isInitialized = true;
  9446. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  9447. captionStream.on('data', function (event) {
  9448. // Convert to seconds in the source's timescale
  9449. event.startTime = event.startPts / timescale;
  9450. event.endTime = event.endPts / timescale;
  9451. parsedCaptions.captions.push(event);
  9452. parsedCaptions.captionStreams[event.stream] = true;
  9453. });
  9454. captionStream.on('log', function (log) {
  9455. parsedCaptions.logs.push(log);
  9456. });
  9457. };
  9458. /**
  9459. * Determines if a new video track will be selected
  9460. * or if the timescale changed
  9461. * @return {Boolean}
  9462. **/
  9463. this.isNewInit = function (videoTrackIds, timescales) {
  9464. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  9465. return false;
  9466. }
  9467. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  9468. };
  9469. /**
  9470. * Parses out SEI captions and interacts with underlying
  9471. * CaptionStream to return dispatched captions
  9472. *
  9473. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9474. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  9475. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  9476. * @see parseEmbeddedCaptions
  9477. * @see m2ts/caption-stream.js
  9478. **/
  9479. this.parse = function (segment, videoTrackIds, timescales) {
  9480. var parsedData;
  9481. if (!this.isInitialized()) {
  9482. return null; // This is not likely to be a video segment
  9483. } else if (!videoTrackIds || !timescales) {
  9484. return null;
  9485. } else if (this.isNewInit(videoTrackIds, timescales)) {
  9486. // Use the first video track only as there is no
  9487. // mechanism to switch to other video tracks
  9488. trackId = videoTrackIds[0];
  9489. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  9490. // data until we have one.
  9491. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9492. } else if (trackId === null || !timescale) {
  9493. segmentCache.push(segment);
  9494. return null;
  9495. } // Now that a timescale and trackId is set, parse cached segments
  9496. while (segmentCache.length > 0) {
  9497. var cachedSegment = segmentCache.shift();
  9498. this.parse(cachedSegment, videoTrackIds, timescales);
  9499. }
  9500. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  9501. if (parsedData && parsedData.logs) {
  9502. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  9503. }
  9504. if (parsedData === null || !parsedData.seiNals) {
  9505. if (parsedCaptions.logs.length) {
  9506. return {
  9507. logs: parsedCaptions.logs,
  9508. captions: [],
  9509. captionStreams: []
  9510. };
  9511. }
  9512. return null;
  9513. }
  9514. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  9515. this.flushStream();
  9516. return parsedCaptions;
  9517. };
  9518. /**
  9519. * Pushes SEI NALUs onto CaptionStream
  9520. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  9521. * Assumes that `parseCaptionNals` has been called first
  9522. * @see m2ts/caption-stream.js
  9523. **/
  9524. this.pushNals = function (nals) {
  9525. if (!this.isInitialized() || !nals || nals.length === 0) {
  9526. return null;
  9527. }
  9528. nals.forEach(function (nal) {
  9529. captionStream.push(nal);
  9530. });
  9531. };
  9532. /**
  9533. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  9534. * @see m2ts/caption-stream.js
  9535. **/
  9536. this.flushStream = function () {
  9537. if (!this.isInitialized()) {
  9538. return null;
  9539. }
  9540. if (!parsingPartial) {
  9541. captionStream.flush();
  9542. } else {
  9543. captionStream.partialFlush();
  9544. }
  9545. };
  9546. /**
  9547. * Reset caption buckets for new data
  9548. **/
  9549. this.clearParsedCaptions = function () {
  9550. parsedCaptions.captions = [];
  9551. parsedCaptions.captionStreams = {};
  9552. parsedCaptions.logs = [];
  9553. };
  9554. /**
  9555. * Resets underlying CaptionStream
  9556. * @see m2ts/caption-stream.js
  9557. **/
  9558. this.resetCaptionStream = function () {
  9559. if (!this.isInitialized()) {
  9560. return null;
  9561. }
  9562. captionStream.reset();
  9563. };
  9564. /**
  9565. * Convenience method to clear all captions flushed from the
  9566. * CaptionStream and still being parsed
  9567. * @see m2ts/caption-stream.js
  9568. **/
  9569. this.clearAllCaptions = function () {
  9570. this.clearParsedCaptions();
  9571. this.resetCaptionStream();
  9572. };
  9573. /**
  9574. * Reset caption parser
  9575. **/
  9576. this.reset = function () {
  9577. segmentCache = [];
  9578. trackId = null;
  9579. timescale = null;
  9580. if (!parsedCaptions) {
  9581. parsedCaptions = {
  9582. captions: [],
  9583. // CC1, CC2, CC3, CC4
  9584. captionStreams: {},
  9585. logs: []
  9586. };
  9587. } else {
  9588. this.clearParsedCaptions();
  9589. }
  9590. this.resetCaptionStream();
  9591. };
  9592. this.reset();
  9593. };
  9594. var captionParser = CaptionParser;
  9595. /**
  9596. * Returns the first string in the data array ending with a null char '\0'
  9597. * @param {UInt8} data
  9598. * @returns the string with the null char
  9599. */
  9600. var uint8ToCString$1 = function (data) {
  9601. var index = 0;
  9602. var curChar = String.fromCharCode(data[index]);
  9603. var retString = '';
  9604. while (curChar !== '\0') {
  9605. retString += curChar;
  9606. index++;
  9607. curChar = String.fromCharCode(data[index]);
  9608. } // Add nullChar
  9609. retString += curChar;
  9610. return retString;
  9611. };
  9612. var string = {
  9613. uint8ToCString: uint8ToCString$1
  9614. };
  9615. var uint8ToCString = string.uint8ToCString;
  9616. var getUint64$1 = numbers.getUint64;
  9617. /**
  9618. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  9619. * References:
  9620. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  9621. * https://aomediacodec.github.io/id3-emsg/
  9622. *
  9623. * Takes emsg box data as a uint8 array and returns a emsg box object
  9624. * @param {UInt8Array} boxData data from emsg box
  9625. * @returns A parsed emsg box object
  9626. */
  9627. var parseEmsgBox = function (boxData) {
  9628. // version + flags
  9629. var offset = 4;
  9630. var version = boxData[0];
  9631. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  9632. if (version === 0) {
  9633. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  9634. offset += scheme_id_uri.length;
  9635. value = uint8ToCString(boxData.subarray(offset));
  9636. offset += value.length;
  9637. var dv = new DataView(boxData.buffer);
  9638. timescale = dv.getUint32(offset);
  9639. offset += 4;
  9640. presentation_time_delta = dv.getUint32(offset);
  9641. offset += 4;
  9642. event_duration = dv.getUint32(offset);
  9643. offset += 4;
  9644. id = dv.getUint32(offset);
  9645. offset += 4;
  9646. } else if (version === 1) {
  9647. var dv = new DataView(boxData.buffer);
  9648. timescale = dv.getUint32(offset);
  9649. offset += 4;
  9650. presentation_time = getUint64$1(boxData.subarray(offset));
  9651. offset += 8;
  9652. event_duration = dv.getUint32(offset);
  9653. offset += 4;
  9654. id = dv.getUint32(offset);
  9655. offset += 4;
  9656. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  9657. offset += scheme_id_uri.length;
  9658. value = uint8ToCString(boxData.subarray(offset));
  9659. offset += value.length;
  9660. }
  9661. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  9662. var emsgBox = {
  9663. scheme_id_uri,
  9664. value,
  9665. // if timescale is undefined or 0 set to 1
  9666. timescale: timescale ? timescale : 1,
  9667. presentation_time,
  9668. presentation_time_delta,
  9669. event_duration,
  9670. id,
  9671. message_data
  9672. };
  9673. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  9674. };
  9675. /**
  9676. * Scales a presentation time or time delta with an offset with a provided timescale
  9677. * @param {number} presentationTime
  9678. * @param {number} timescale
  9679. * @param {number} timeDelta
  9680. * @param {number} offset
  9681. * @returns the scaled time as a number
  9682. */
  9683. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  9684. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  9685. };
  9686. /**
  9687. * Checks the emsg box data for validity based on the version
  9688. * @param {number} version of the emsg box to validate
  9689. * @param {Object} emsg the emsg data to validate
  9690. * @returns if the box is valid as a boolean
  9691. */
  9692. var isValidEmsgBox = function (version, emsg) {
  9693. var hasScheme = emsg.scheme_id_uri !== '\0';
  9694. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  9695. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  9696. return !(version > 1) && isValidV0Box || isValidV1Box;
  9697. }; // Utility function to check if an object is defined
  9698. var isDefined = function (data) {
  9699. return data !== undefined || data !== null;
  9700. };
  9701. var emsg$1 = {
  9702. parseEmsgBox: parseEmsgBox,
  9703. scaleTime: scaleTime
  9704. };
  9705. /**
  9706. * mux.js
  9707. *
  9708. * Copyright (c) Brightcove
  9709. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9710. *
  9711. * Utilities to detect basic properties and metadata about MP4s.
  9712. */
  9713. var toUnsigned = bin.toUnsigned;
  9714. var toHexString = bin.toHexString;
  9715. var findBox = findBox_1;
  9716. var parseType$1 = parseType_1;
  9717. var emsg = emsg$1;
  9718. var parseTfhd = parseTfhd$2;
  9719. var parseTrun = parseTrun$2;
  9720. var parseTfdt = parseTfdt$2;
  9721. var getUint64 = numbers.getUint64;
  9722. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  9723. var window$1 = window_1;
  9724. var parseId3Frames = parseId3.parseId3Frames;
  9725. /**
  9726. * Parses an MP4 initialization segment and extracts the timescale
  9727. * values for any declared tracks. Timescale values indicate the
  9728. * number of clock ticks per second to assume for time-based values
  9729. * elsewhere in the MP4.
  9730. *
  9731. * To determine the start time of an MP4, you need two pieces of
  9732. * information: the timescale unit and the earliest base media decode
  9733. * time. Multiple timescales can be specified within an MP4 but the
  9734. * base media decode time is always expressed in the timescale from
  9735. * the media header box for the track:
  9736. * ```
  9737. * moov > trak > mdia > mdhd.timescale
  9738. * ```
  9739. * @param init {Uint8Array} the bytes of the init segment
  9740. * @return {object} a hash of track ids to timescale values or null if
  9741. * the init segment is malformed.
  9742. */
  9743. timescale = function (init) {
  9744. var result = {},
  9745. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  9746. return traks.reduce(function (result, trak) {
  9747. var tkhd, version, index, id, mdhd;
  9748. tkhd = findBox(trak, ['tkhd'])[0];
  9749. if (!tkhd) {
  9750. return null;
  9751. }
  9752. version = tkhd[0];
  9753. index = version === 0 ? 12 : 20;
  9754. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  9755. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  9756. if (!mdhd) {
  9757. return null;
  9758. }
  9759. version = mdhd[0];
  9760. index = version === 0 ? 12 : 20;
  9761. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  9762. return result;
  9763. }, result);
  9764. };
  9765. /**
  9766. * Determine the base media decode start time, in seconds, for an MP4
  9767. * fragment. If multiple fragments are specified, the earliest time is
  9768. * returned.
  9769. *
  9770. * The base media decode time can be parsed from track fragment
  9771. * metadata:
  9772. * ```
  9773. * moof > traf > tfdt.baseMediaDecodeTime
  9774. * ```
  9775. * It requires the timescale value from the mdhd to interpret.
  9776. *
  9777. * @param timescale {object} a hash of track ids to timescale values.
  9778. * @return {number} the earliest base media decode start time for the
  9779. * fragment, in seconds
  9780. */
  9781. startTime = function (timescale, fragment) {
  9782. var trafs; // we need info from two childrend of each track fragment box
  9783. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  9784. var lowestTime = trafs.reduce(function (acc, traf) {
  9785. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  9786. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  9787. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  9788. var tfdt = findBox(traf, ['tfdt'])[0];
  9789. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  9790. var baseTime; // version 1 is 64 bit
  9791. if (tfdt[0] === 1) {
  9792. baseTime = getUint64(tfdt.subarray(4, 12));
  9793. } else {
  9794. baseTime = dv.getUint32(4);
  9795. } // convert base time to seconds if it is a valid number.
  9796. let seconds;
  9797. if (typeof baseTime === 'bigint') {
  9798. seconds = baseTime / window$1.BigInt(scale);
  9799. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  9800. seconds = baseTime / scale;
  9801. }
  9802. if (seconds < Number.MAX_SAFE_INTEGER) {
  9803. seconds = Number(seconds);
  9804. }
  9805. if (seconds < acc) {
  9806. acc = seconds;
  9807. }
  9808. return acc;
  9809. }, Infinity);
  9810. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  9811. };
  9812. /**
  9813. * Determine the composition start, in seconds, for an MP4
  9814. * fragment.
  9815. *
  9816. * The composition start time of a fragment can be calculated using the base
  9817. * media decode time, composition time offset, and timescale, as follows:
  9818. *
  9819. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  9820. *
  9821. * All of the aforementioned information is contained within a media fragment's
  9822. * `traf` box, except for timescale info, which comes from the initialization
  9823. * segment, so a track id (also contained within a `traf`) is also necessary to
  9824. * associate it with a timescale
  9825. *
  9826. *
  9827. * @param timescales {object} - a hash of track ids to timescale values.
  9828. * @param fragment {Unit8Array} - the bytes of a media segment
  9829. * @return {number} the composition start time for the fragment, in seconds
  9830. **/
  9831. compositionStartTime = function (timescales, fragment) {
  9832. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  9833. var baseMediaDecodeTime = 0;
  9834. var compositionTimeOffset = 0;
  9835. var trackId;
  9836. if (trafBoxes && trafBoxes.length) {
  9837. // The spec states that track run samples contained within a `traf` box are contiguous, but
  9838. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  9839. // We will assume that they are, so we only need the first to calculate start time.
  9840. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  9841. var trun = findBox(trafBoxes[0], ['trun'])[0];
  9842. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  9843. if (tfhd) {
  9844. var parsedTfhd = parseTfhd(tfhd);
  9845. trackId = parsedTfhd.trackId;
  9846. }
  9847. if (tfdt) {
  9848. var parsedTfdt = parseTfdt(tfdt);
  9849. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  9850. }
  9851. if (trun) {
  9852. var parsedTrun = parseTrun(trun);
  9853. if (parsedTrun.samples && parsedTrun.samples.length) {
  9854. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  9855. }
  9856. }
  9857. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  9858. // specified.
  9859. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  9860. if (typeof baseMediaDecodeTime === 'bigint') {
  9861. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  9862. timescale = window$1.BigInt(timescale);
  9863. }
  9864. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  9865. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  9866. result = Number(result);
  9867. }
  9868. return result;
  9869. };
  9870. /**
  9871. * Find the trackIds of the video tracks in this source.
  9872. * Found by parsing the Handler Reference and Track Header Boxes:
  9873. * moov > trak > mdia > hdlr
  9874. * moov > trak > tkhd
  9875. *
  9876. * @param {Uint8Array} init - The bytes of the init segment for this source
  9877. * @return {Number[]} A list of trackIds
  9878. *
  9879. * @see ISO-BMFF-12/2015, Section 8.4.3
  9880. **/
  9881. getVideoTrackIds = function (init) {
  9882. var traks = findBox(init, ['moov', 'trak']);
  9883. var videoTrackIds = [];
  9884. traks.forEach(function (trak) {
  9885. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  9886. var tkhds = findBox(trak, ['tkhd']);
  9887. hdlrs.forEach(function (hdlr, index) {
  9888. var handlerType = parseType$1(hdlr.subarray(8, 12));
  9889. var tkhd = tkhds[index];
  9890. var view;
  9891. var version;
  9892. var trackId;
  9893. if (handlerType === 'vide') {
  9894. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  9895. version = view.getUint8(0);
  9896. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  9897. videoTrackIds.push(trackId);
  9898. }
  9899. });
  9900. });
  9901. return videoTrackIds;
  9902. };
  9903. getTimescaleFromMediaHeader = function (mdhd) {
  9904. // mdhd is a FullBox, meaning it will have its own version as the first byte
  9905. var version = mdhd[0];
  9906. var index = version === 0 ? 12 : 20;
  9907. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  9908. };
  9909. /**
  9910. * Get all the video, audio, and hint tracks from a non fragmented
  9911. * mp4 segment
  9912. */
  9913. getTracks = function (init) {
  9914. var traks = findBox(init, ['moov', 'trak']);
  9915. var tracks = [];
  9916. traks.forEach(function (trak) {
  9917. var track = {};
  9918. var tkhd = findBox(trak, ['tkhd'])[0];
  9919. var view, tkhdVersion; // id
  9920. if (tkhd) {
  9921. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  9922. tkhdVersion = view.getUint8(0);
  9923. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  9924. }
  9925. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  9926. if (hdlr) {
  9927. var type = parseType$1(hdlr.subarray(8, 12));
  9928. if (type === 'vide') {
  9929. track.type = 'video';
  9930. } else if (type === 'soun') {
  9931. track.type = 'audio';
  9932. } else {
  9933. track.type = type;
  9934. }
  9935. } // codec
  9936. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  9937. if (stsd) {
  9938. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  9939. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  9940. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  9941. var codecConfig, codecConfigType;
  9942. if (codecBox) {
  9943. // https://tools.ietf.org/html/rfc6381#section-3.3
  9944. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  9945. // we don't need anything but the "config" parameter of the
  9946. // avc1 codecBox
  9947. codecConfig = codecBox.subarray(78);
  9948. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  9949. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  9950. track.codec += '.'; // left padded with zeroes for single digit hex
  9951. // profile idc
  9952. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  9953. track.codec += toHexString(codecConfig[10]); // level idc
  9954. track.codec += toHexString(codecConfig[11]);
  9955. } else {
  9956. // TODO: show a warning that we couldn't parse the codec
  9957. // and are using the default
  9958. track.codec = 'avc1.4d400d';
  9959. }
  9960. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  9961. // we do not need anything but the streamDescriptor of the mp4a codecBox
  9962. codecConfig = codecBox.subarray(28);
  9963. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  9964. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  9965. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  9966. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  9967. } else {
  9968. // TODO: show a warning that we couldn't parse the codec
  9969. // and are using the default
  9970. track.codec = 'mp4a.40.2';
  9971. }
  9972. } else {
  9973. // flac, opus, etc
  9974. track.codec = track.codec.toLowerCase();
  9975. }
  9976. }
  9977. }
  9978. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  9979. if (mdhd) {
  9980. track.timescale = getTimescaleFromMediaHeader(mdhd);
  9981. }
  9982. tracks.push(track);
  9983. });
  9984. return tracks;
  9985. };
  9986. /**
  9987. * Returns an array of emsg ID3 data from the provided segmentData.
  9988. * An offset can also be provided as the Latest Arrival Time to calculate
  9989. * the Event Start Time of v0 EMSG boxes.
  9990. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  9991. *
  9992. * @param {Uint8Array} segmentData the segment byte array.
  9993. * @param {number} offset the segment start time or Latest Arrival Time,
  9994. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  9995. */
  9996. getEmsgID3 = function (segmentData, offset = 0) {
  9997. var emsgBoxes = findBox(segmentData, ['emsg']);
  9998. return emsgBoxes.map(data => {
  9999. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  10000. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  10001. return {
  10002. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  10003. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  10004. frames: parsedId3Frames
  10005. };
  10006. });
  10007. };
  10008. var probe$2 = {
  10009. // export mp4 inspector's findBox and parseType for backwards compatibility
  10010. findBox: findBox,
  10011. parseType: parseType$1,
  10012. timescale: timescale,
  10013. startTime: startTime,
  10014. compositionStartTime: compositionStartTime,
  10015. videoTrackIds: getVideoTrackIds,
  10016. tracks: getTracks,
  10017. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  10018. getEmsgID3: getEmsgID3
  10019. };
  10020. /**
  10021. * mux.js
  10022. *
  10023. * Copyright (c) Brightcove
  10024. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10025. *
  10026. * Utilities to detect basic properties and metadata about TS Segments.
  10027. */
  10028. var StreamTypes$1 = streamTypes;
  10029. var parsePid = function (packet) {
  10030. var pid = packet[1] & 0x1f;
  10031. pid <<= 8;
  10032. pid |= packet[2];
  10033. return pid;
  10034. };
  10035. var parsePayloadUnitStartIndicator = function (packet) {
  10036. return !!(packet[1] & 0x40);
  10037. };
  10038. var parseAdaptionField = function (packet) {
  10039. var offset = 0; // if an adaption field is present, its length is specified by the
  10040. // fifth byte of the TS packet header. The adaptation field is
  10041. // used to add stuffing to PES packets that don't fill a complete
  10042. // TS packet, and to specify some forms of timing and control data
  10043. // that we do not currently use.
  10044. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  10045. offset += packet[4] + 1;
  10046. }
  10047. return offset;
  10048. };
  10049. var parseType = function (packet, pmtPid) {
  10050. var pid = parsePid(packet);
  10051. if (pid === 0) {
  10052. return 'pat';
  10053. } else if (pid === pmtPid) {
  10054. return 'pmt';
  10055. } else if (pmtPid) {
  10056. return 'pes';
  10057. }
  10058. return null;
  10059. };
  10060. var parsePat = function (packet) {
  10061. var pusi = parsePayloadUnitStartIndicator(packet);
  10062. var offset = 4 + parseAdaptionField(packet);
  10063. if (pusi) {
  10064. offset += packet[offset] + 1;
  10065. }
  10066. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  10067. };
  10068. var parsePmt = function (packet) {
  10069. var programMapTable = {};
  10070. var pusi = parsePayloadUnitStartIndicator(packet);
  10071. var payloadOffset = 4 + parseAdaptionField(packet);
  10072. if (pusi) {
  10073. payloadOffset += packet[payloadOffset] + 1;
  10074. } // PMTs can be sent ahead of the time when they should actually
  10075. // take effect. We don't believe this should ever be the case
  10076. // for HLS but we'll ignore "forward" PMT declarations if we see
  10077. // them. Future PMT declarations have the current_next_indicator
  10078. // set to zero.
  10079. if (!(packet[payloadOffset + 5] & 0x01)) {
  10080. return;
  10081. }
  10082. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  10083. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  10084. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  10085. // long the program info descriptors are
  10086. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  10087. var offset = 12 + programInfoLength;
  10088. while (offset < tableEnd) {
  10089. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  10090. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  10091. // skip past the elementary stream descriptors, if present
  10092. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  10093. }
  10094. return programMapTable;
  10095. };
  10096. var parsePesType = function (packet, programMapTable) {
  10097. var pid = parsePid(packet);
  10098. var type = programMapTable[pid];
  10099. switch (type) {
  10100. case StreamTypes$1.H264_STREAM_TYPE:
  10101. return 'video';
  10102. case StreamTypes$1.ADTS_STREAM_TYPE:
  10103. return 'audio';
  10104. case StreamTypes$1.METADATA_STREAM_TYPE:
  10105. return 'timed-metadata';
  10106. default:
  10107. return null;
  10108. }
  10109. };
  10110. var parsePesTime = function (packet) {
  10111. var pusi = parsePayloadUnitStartIndicator(packet);
  10112. if (!pusi) {
  10113. return null;
  10114. }
  10115. var offset = 4 + parseAdaptionField(packet);
  10116. if (offset >= packet.byteLength) {
  10117. // From the H 222.0 MPEG-TS spec
  10118. // "For transport stream packets carrying PES packets, stuffing is needed when there
  10119. // is insufficient PES packet data to completely fill the transport stream packet
  10120. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  10121. // the sum of the lengths of the data elements in it, so that the payload bytes
  10122. // remaining after the adaptation field exactly accommodates the available PES packet
  10123. // data."
  10124. //
  10125. // If the offset is >= the length of the packet, then the packet contains no data
  10126. // and instead is just adaption field stuffing bytes
  10127. return null;
  10128. }
  10129. var pes = null;
  10130. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  10131. // and a DTS value. Determine what combination of values is
  10132. // available to work with.
  10133. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  10134. // performs all bitwise operations on 32-bit integers but javascript
  10135. // supports a much greater range (52-bits) of integer using standard
  10136. // mathematical operations.
  10137. // We construct a 31-bit value using bitwise operators over the 31
  10138. // most significant bits and then multiply by 4 (equal to a left-shift
  10139. // of 2) before we add the final 2 least significant bits of the
  10140. // timestamp (equal to an OR.)
  10141. if (ptsDtsFlags & 0xC0) {
  10142. pes = {}; // the PTS and DTS are not written out directly. For information
  10143. // on how they are encoded, see
  10144. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  10145. 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;
  10146. pes.pts *= 4; // Left shift by 2
  10147. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  10148. pes.dts = pes.pts;
  10149. if (ptsDtsFlags & 0x40) {
  10150. 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;
  10151. pes.dts *= 4; // Left shift by 2
  10152. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  10153. }
  10154. }
  10155. return pes;
  10156. };
  10157. var parseNalUnitType = function (type) {
  10158. switch (type) {
  10159. case 0x05:
  10160. return 'slice_layer_without_partitioning_rbsp_idr';
  10161. case 0x06:
  10162. return 'sei_rbsp';
  10163. case 0x07:
  10164. return 'seq_parameter_set_rbsp';
  10165. case 0x08:
  10166. return 'pic_parameter_set_rbsp';
  10167. case 0x09:
  10168. return 'access_unit_delimiter_rbsp';
  10169. default:
  10170. return null;
  10171. }
  10172. };
  10173. var videoPacketContainsKeyFrame = function (packet) {
  10174. var offset = 4 + parseAdaptionField(packet);
  10175. var frameBuffer = packet.subarray(offset);
  10176. var frameI = 0;
  10177. var frameSyncPoint = 0;
  10178. var foundKeyFrame = false;
  10179. var nalType; // advance the sync point to a NAL start, if necessary
  10180. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  10181. if (frameBuffer[frameSyncPoint + 2] === 1) {
  10182. // the sync point is properly aligned
  10183. frameI = frameSyncPoint + 5;
  10184. break;
  10185. }
  10186. }
  10187. while (frameI < frameBuffer.byteLength) {
  10188. // look at the current byte to determine if we've hit the end of
  10189. // a NAL unit boundary
  10190. switch (frameBuffer[frameI]) {
  10191. case 0:
  10192. // skip past non-sync sequences
  10193. if (frameBuffer[frameI - 1] !== 0) {
  10194. frameI += 2;
  10195. break;
  10196. } else if (frameBuffer[frameI - 2] !== 0) {
  10197. frameI++;
  10198. break;
  10199. }
  10200. if (frameSyncPoint + 3 !== frameI - 2) {
  10201. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10202. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10203. foundKeyFrame = true;
  10204. }
  10205. } // drop trailing zeroes
  10206. do {
  10207. frameI++;
  10208. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  10209. frameSyncPoint = frameI - 2;
  10210. frameI += 3;
  10211. break;
  10212. case 1:
  10213. // skip past non-sync sequences
  10214. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  10215. frameI += 3;
  10216. break;
  10217. }
  10218. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10219. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10220. foundKeyFrame = true;
  10221. }
  10222. frameSyncPoint = frameI - 2;
  10223. frameI += 3;
  10224. break;
  10225. default:
  10226. // the current byte isn't a one or zero, so it cannot be part
  10227. // of a sync sequence
  10228. frameI += 3;
  10229. break;
  10230. }
  10231. }
  10232. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  10233. frameI -= frameSyncPoint;
  10234. frameSyncPoint = 0; // parse the final nal
  10235. if (frameBuffer && frameBuffer.byteLength > 3) {
  10236. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10237. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10238. foundKeyFrame = true;
  10239. }
  10240. }
  10241. return foundKeyFrame;
  10242. };
  10243. var probe$1 = {
  10244. parseType: parseType,
  10245. parsePat: parsePat,
  10246. parsePmt: parsePmt,
  10247. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  10248. parsePesType: parsePesType,
  10249. parsePesTime: parsePesTime,
  10250. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  10251. };
  10252. /**
  10253. * mux.js
  10254. *
  10255. * Copyright (c) Brightcove
  10256. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10257. *
  10258. * Parse mpeg2 transport stream packets to extract basic timing information
  10259. */
  10260. var StreamTypes = streamTypes;
  10261. var handleRollover = timestampRolloverStream.handleRollover;
  10262. var probe = {};
  10263. probe.ts = probe$1;
  10264. probe.aac = utils;
  10265. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  10266. var MP2T_PACKET_LENGTH = 188,
  10267. // bytes
  10268. SYNC_BYTE = 0x47;
  10269. /**
  10270. * walks through segment data looking for pat and pmt packets to parse out
  10271. * program map table information
  10272. */
  10273. var parsePsi_ = function (bytes, pmt) {
  10274. var startIndex = 0,
  10275. endIndex = MP2T_PACKET_LENGTH,
  10276. packet,
  10277. type;
  10278. while (endIndex < bytes.byteLength) {
  10279. // Look for a pair of start and end sync bytes in the data..
  10280. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10281. // We found a packet
  10282. packet = bytes.subarray(startIndex, endIndex);
  10283. type = probe.ts.parseType(packet, pmt.pid);
  10284. switch (type) {
  10285. case 'pat':
  10286. pmt.pid = probe.ts.parsePat(packet);
  10287. break;
  10288. case 'pmt':
  10289. var table = probe.ts.parsePmt(packet);
  10290. pmt.table = pmt.table || {};
  10291. Object.keys(table).forEach(function (key) {
  10292. pmt.table[key] = table[key];
  10293. });
  10294. break;
  10295. }
  10296. startIndex += MP2T_PACKET_LENGTH;
  10297. endIndex += MP2T_PACKET_LENGTH;
  10298. continue;
  10299. } // If we get here, we have somehow become de-synchronized and we need to step
  10300. // forward one byte at a time until we find a pair of sync bytes that denote
  10301. // a packet
  10302. startIndex++;
  10303. endIndex++;
  10304. }
  10305. };
  10306. /**
  10307. * walks through the segment data from the start and end to get timing information
  10308. * for the first and last audio pes packets
  10309. */
  10310. var parseAudioPes_ = function (bytes, pmt, result) {
  10311. var startIndex = 0,
  10312. endIndex = MP2T_PACKET_LENGTH,
  10313. packet,
  10314. type,
  10315. pesType,
  10316. pusi,
  10317. parsed;
  10318. var endLoop = false; // Start walking from start of segment to get first audio packet
  10319. while (endIndex <= bytes.byteLength) {
  10320. // Look for a pair of start and end sync bytes in the data..
  10321. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10322. // We found a packet
  10323. packet = bytes.subarray(startIndex, endIndex);
  10324. type = probe.ts.parseType(packet, pmt.pid);
  10325. switch (type) {
  10326. case 'pes':
  10327. pesType = probe.ts.parsePesType(packet, pmt.table);
  10328. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10329. if (pesType === 'audio' && pusi) {
  10330. parsed = probe.ts.parsePesTime(packet);
  10331. if (parsed) {
  10332. parsed.type = 'audio';
  10333. result.audio.push(parsed);
  10334. endLoop = true;
  10335. }
  10336. }
  10337. break;
  10338. }
  10339. if (endLoop) {
  10340. break;
  10341. }
  10342. startIndex += MP2T_PACKET_LENGTH;
  10343. endIndex += MP2T_PACKET_LENGTH;
  10344. continue;
  10345. } // If we get here, we have somehow become de-synchronized and we need to step
  10346. // forward one byte at a time until we find a pair of sync bytes that denote
  10347. // a packet
  10348. startIndex++;
  10349. endIndex++;
  10350. } // Start walking from end of segment to get last audio packet
  10351. endIndex = bytes.byteLength;
  10352. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10353. endLoop = false;
  10354. while (startIndex >= 0) {
  10355. // Look for a pair of start and end sync bytes in the data..
  10356. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10357. // We found a packet
  10358. packet = bytes.subarray(startIndex, endIndex);
  10359. type = probe.ts.parseType(packet, pmt.pid);
  10360. switch (type) {
  10361. case 'pes':
  10362. pesType = probe.ts.parsePesType(packet, pmt.table);
  10363. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10364. if (pesType === 'audio' && pusi) {
  10365. parsed = probe.ts.parsePesTime(packet);
  10366. if (parsed) {
  10367. parsed.type = 'audio';
  10368. result.audio.push(parsed);
  10369. endLoop = true;
  10370. }
  10371. }
  10372. break;
  10373. }
  10374. if (endLoop) {
  10375. break;
  10376. }
  10377. startIndex -= MP2T_PACKET_LENGTH;
  10378. endIndex -= MP2T_PACKET_LENGTH;
  10379. continue;
  10380. } // If we get here, we have somehow become de-synchronized and we need to step
  10381. // forward one byte at a time until we find a pair of sync bytes that denote
  10382. // a packet
  10383. startIndex--;
  10384. endIndex--;
  10385. }
  10386. };
  10387. /**
  10388. * walks through the segment data from the start and end to get timing information
  10389. * for the first and last video pes packets as well as timing information for the first
  10390. * key frame.
  10391. */
  10392. var parseVideoPes_ = function (bytes, pmt, result) {
  10393. var startIndex = 0,
  10394. endIndex = MP2T_PACKET_LENGTH,
  10395. packet,
  10396. type,
  10397. pesType,
  10398. pusi,
  10399. parsed,
  10400. frame,
  10401. i,
  10402. pes;
  10403. var endLoop = false;
  10404. var currentFrame = {
  10405. data: [],
  10406. size: 0
  10407. }; // Start walking from start of segment to get first video packet
  10408. while (endIndex < bytes.byteLength) {
  10409. // Look for a pair of start and end sync bytes in the data..
  10410. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10411. // We found a packet
  10412. packet = bytes.subarray(startIndex, endIndex);
  10413. type = probe.ts.parseType(packet, pmt.pid);
  10414. switch (type) {
  10415. case 'pes':
  10416. pesType = probe.ts.parsePesType(packet, pmt.table);
  10417. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10418. if (pesType === 'video') {
  10419. if (pusi && !endLoop) {
  10420. parsed = probe.ts.parsePesTime(packet);
  10421. if (parsed) {
  10422. parsed.type = 'video';
  10423. result.video.push(parsed);
  10424. endLoop = true;
  10425. }
  10426. }
  10427. if (!result.firstKeyFrame) {
  10428. if (pusi) {
  10429. if (currentFrame.size !== 0) {
  10430. frame = new Uint8Array(currentFrame.size);
  10431. i = 0;
  10432. while (currentFrame.data.length) {
  10433. pes = currentFrame.data.shift();
  10434. frame.set(pes, i);
  10435. i += pes.byteLength;
  10436. }
  10437. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  10438. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  10439. // the keyframe seems to work fine with HLS playback
  10440. // and definitely preferable to a crash with TypeError...
  10441. if (firstKeyFrame) {
  10442. result.firstKeyFrame = firstKeyFrame;
  10443. result.firstKeyFrame.type = 'video';
  10444. } else {
  10445. // eslint-disable-next-line
  10446. 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.');
  10447. }
  10448. }
  10449. currentFrame.size = 0;
  10450. }
  10451. }
  10452. currentFrame.data.push(packet);
  10453. currentFrame.size += packet.byteLength;
  10454. }
  10455. }
  10456. break;
  10457. }
  10458. if (endLoop && result.firstKeyFrame) {
  10459. break;
  10460. }
  10461. startIndex += MP2T_PACKET_LENGTH;
  10462. endIndex += MP2T_PACKET_LENGTH;
  10463. continue;
  10464. } // If we get here, we have somehow become de-synchronized and we need to step
  10465. // forward one byte at a time until we find a pair of sync bytes that denote
  10466. // a packet
  10467. startIndex++;
  10468. endIndex++;
  10469. } // Start walking from end of segment to get last video packet
  10470. endIndex = bytes.byteLength;
  10471. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10472. endLoop = false;
  10473. while (startIndex >= 0) {
  10474. // Look for a pair of start and end sync bytes in the data..
  10475. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10476. // We found a packet
  10477. packet = bytes.subarray(startIndex, endIndex);
  10478. type = probe.ts.parseType(packet, pmt.pid);
  10479. switch (type) {
  10480. case 'pes':
  10481. pesType = probe.ts.parsePesType(packet, pmt.table);
  10482. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10483. if (pesType === 'video' && pusi) {
  10484. parsed = probe.ts.parsePesTime(packet);
  10485. if (parsed) {
  10486. parsed.type = 'video';
  10487. result.video.push(parsed);
  10488. endLoop = true;
  10489. }
  10490. }
  10491. break;
  10492. }
  10493. if (endLoop) {
  10494. break;
  10495. }
  10496. startIndex -= MP2T_PACKET_LENGTH;
  10497. endIndex -= MP2T_PACKET_LENGTH;
  10498. continue;
  10499. } // If we get here, we have somehow become de-synchronized and we need to step
  10500. // forward one byte at a time until we find a pair of sync bytes that denote
  10501. // a packet
  10502. startIndex--;
  10503. endIndex--;
  10504. }
  10505. };
  10506. /**
  10507. * Adjusts the timestamp information for the segment to account for
  10508. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  10509. */
  10510. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  10511. if (segmentInfo.audio && segmentInfo.audio.length) {
  10512. var audioBaseTimestamp = baseTimestamp;
  10513. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  10514. audioBaseTimestamp = segmentInfo.audio[0].dts;
  10515. }
  10516. segmentInfo.audio.forEach(function (info) {
  10517. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  10518. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  10519. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  10520. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  10521. });
  10522. }
  10523. if (segmentInfo.video && segmentInfo.video.length) {
  10524. var videoBaseTimestamp = baseTimestamp;
  10525. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  10526. videoBaseTimestamp = segmentInfo.video[0].dts;
  10527. }
  10528. segmentInfo.video.forEach(function (info) {
  10529. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  10530. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  10531. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  10532. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  10533. });
  10534. if (segmentInfo.firstKeyFrame) {
  10535. var frame = segmentInfo.firstKeyFrame;
  10536. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  10537. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  10538. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  10539. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  10540. }
  10541. }
  10542. };
  10543. /**
  10544. * inspects the aac data stream for start and end time information
  10545. */
  10546. var inspectAac_ = function (bytes) {
  10547. var endLoop = false,
  10548. audioCount = 0,
  10549. sampleRate = null,
  10550. timestamp = null,
  10551. frameSize = 0,
  10552. byteIndex = 0,
  10553. packet;
  10554. while (bytes.length - byteIndex >= 3) {
  10555. var type = probe.aac.parseType(bytes, byteIndex);
  10556. switch (type) {
  10557. case 'timed-metadata':
  10558. // Exit early because we don't have enough to parse
  10559. // the ID3 tag header
  10560. if (bytes.length - byteIndex < 10) {
  10561. endLoop = true;
  10562. break;
  10563. }
  10564. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  10565. // to emit a full packet
  10566. if (frameSize > bytes.length) {
  10567. endLoop = true;
  10568. break;
  10569. }
  10570. if (timestamp === null) {
  10571. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  10572. timestamp = probe.aac.parseAacTimestamp(packet);
  10573. }
  10574. byteIndex += frameSize;
  10575. break;
  10576. case 'audio':
  10577. // Exit early because we don't have enough to parse
  10578. // the ADTS frame header
  10579. if (bytes.length - byteIndex < 7) {
  10580. endLoop = true;
  10581. break;
  10582. }
  10583. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  10584. // to emit a full packet
  10585. if (frameSize > bytes.length) {
  10586. endLoop = true;
  10587. break;
  10588. }
  10589. if (sampleRate === null) {
  10590. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  10591. sampleRate = probe.aac.parseSampleRate(packet);
  10592. }
  10593. audioCount++;
  10594. byteIndex += frameSize;
  10595. break;
  10596. default:
  10597. byteIndex++;
  10598. break;
  10599. }
  10600. if (endLoop) {
  10601. return null;
  10602. }
  10603. }
  10604. if (sampleRate === null || timestamp === null) {
  10605. return null;
  10606. }
  10607. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  10608. var result = {
  10609. audio: [{
  10610. type: 'audio',
  10611. dts: timestamp,
  10612. pts: timestamp
  10613. }, {
  10614. type: 'audio',
  10615. dts: timestamp + audioCount * 1024 * audioTimescale,
  10616. pts: timestamp + audioCount * 1024 * audioTimescale
  10617. }]
  10618. };
  10619. return result;
  10620. };
  10621. /**
  10622. * inspects the transport stream segment data for start and end time information
  10623. * of the audio and video tracks (when present) as well as the first key frame's
  10624. * start time.
  10625. */
  10626. var inspectTs_ = function (bytes) {
  10627. var pmt = {
  10628. pid: null,
  10629. table: null
  10630. };
  10631. var result = {};
  10632. parsePsi_(bytes, pmt);
  10633. for (var pid in pmt.table) {
  10634. if (pmt.table.hasOwnProperty(pid)) {
  10635. var type = pmt.table[pid];
  10636. switch (type) {
  10637. case StreamTypes.H264_STREAM_TYPE:
  10638. result.video = [];
  10639. parseVideoPes_(bytes, pmt, result);
  10640. if (result.video.length === 0) {
  10641. delete result.video;
  10642. }
  10643. break;
  10644. case StreamTypes.ADTS_STREAM_TYPE:
  10645. result.audio = [];
  10646. parseAudioPes_(bytes, pmt, result);
  10647. if (result.audio.length === 0) {
  10648. delete result.audio;
  10649. }
  10650. break;
  10651. }
  10652. }
  10653. }
  10654. return result;
  10655. };
  10656. /**
  10657. * Inspects segment byte data and returns an object with start and end timing information
  10658. *
  10659. * @param {Uint8Array} bytes The segment byte data
  10660. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  10661. * timestamps for rollover. This value must be in 90khz clock.
  10662. * @return {Object} Object containing start and end frame timing info of segment.
  10663. */
  10664. var inspect = function (bytes, baseTimestamp) {
  10665. var isAacData = probe.aac.isLikelyAacData(bytes);
  10666. var result;
  10667. if (isAacData) {
  10668. result = inspectAac_(bytes);
  10669. } else {
  10670. result = inspectTs_(bytes);
  10671. }
  10672. if (!result || !result.audio && !result.video) {
  10673. return null;
  10674. }
  10675. adjustTimestamp_(result, baseTimestamp);
  10676. return result;
  10677. };
  10678. var tsInspector = {
  10679. inspect: inspect,
  10680. parseAudioPes_: parseAudioPes_
  10681. };
  10682. /* global self */
  10683. /**
  10684. * Re-emits transmuxer events by converting them into messages to the
  10685. * world outside the worker.
  10686. *
  10687. * @param {Object} transmuxer the transmuxer to wire events on
  10688. * @private
  10689. */
  10690. const wireTransmuxerEvents = function (self, transmuxer) {
  10691. transmuxer.on('data', function (segment) {
  10692. // transfer ownership of the underlying ArrayBuffer
  10693. // instead of doing a copy to save memory
  10694. // ArrayBuffers are transferable but generic TypedArrays are not
  10695. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  10696. const initArray = segment.initSegment;
  10697. segment.initSegment = {
  10698. data: initArray.buffer,
  10699. byteOffset: initArray.byteOffset,
  10700. byteLength: initArray.byteLength
  10701. };
  10702. const typedArray = segment.data;
  10703. segment.data = typedArray.buffer;
  10704. self.postMessage({
  10705. action: 'data',
  10706. segment,
  10707. byteOffset: typedArray.byteOffset,
  10708. byteLength: typedArray.byteLength
  10709. }, [segment.data]);
  10710. });
  10711. transmuxer.on('done', function (data) {
  10712. self.postMessage({
  10713. action: 'done'
  10714. });
  10715. });
  10716. transmuxer.on('gopInfo', function (gopInfo) {
  10717. self.postMessage({
  10718. action: 'gopInfo',
  10719. gopInfo
  10720. });
  10721. });
  10722. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  10723. const videoSegmentTimingInfo = {
  10724. start: {
  10725. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  10726. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  10727. },
  10728. end: {
  10729. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  10730. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  10731. },
  10732. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  10733. };
  10734. if (timingInfo.prependedContentDuration) {
  10735. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  10736. }
  10737. self.postMessage({
  10738. action: 'videoSegmentTimingInfo',
  10739. videoSegmentTimingInfo
  10740. });
  10741. });
  10742. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  10743. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  10744. const audioSegmentTimingInfo = {
  10745. start: {
  10746. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  10747. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  10748. },
  10749. end: {
  10750. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  10751. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  10752. },
  10753. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  10754. };
  10755. if (timingInfo.prependedContentDuration) {
  10756. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  10757. }
  10758. self.postMessage({
  10759. action: 'audioSegmentTimingInfo',
  10760. audioSegmentTimingInfo
  10761. });
  10762. });
  10763. transmuxer.on('id3Frame', function (id3Frame) {
  10764. self.postMessage({
  10765. action: 'id3Frame',
  10766. id3Frame
  10767. });
  10768. });
  10769. transmuxer.on('caption', function (caption) {
  10770. self.postMessage({
  10771. action: 'caption',
  10772. caption
  10773. });
  10774. });
  10775. transmuxer.on('trackinfo', function (trackInfo) {
  10776. self.postMessage({
  10777. action: 'trackinfo',
  10778. trackInfo
  10779. });
  10780. });
  10781. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  10782. // convert to video TS since we prioritize video time over audio
  10783. self.postMessage({
  10784. action: 'audioTimingInfo',
  10785. audioTimingInfo: {
  10786. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  10787. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  10788. }
  10789. });
  10790. });
  10791. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  10792. self.postMessage({
  10793. action: 'videoTimingInfo',
  10794. videoTimingInfo: {
  10795. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  10796. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  10797. }
  10798. });
  10799. });
  10800. transmuxer.on('log', function (log) {
  10801. self.postMessage({
  10802. action: 'log',
  10803. log
  10804. });
  10805. });
  10806. };
  10807. /**
  10808. * All incoming messages route through this hash. If no function exists
  10809. * to handle an incoming message, then we ignore the message.
  10810. *
  10811. * @class MessageHandlers
  10812. * @param {Object} options the options to initialize with
  10813. */
  10814. class MessageHandlers {
  10815. constructor(self, options) {
  10816. this.options = options || {};
  10817. this.self = self;
  10818. this.init();
  10819. }
  10820. /**
  10821. * initialize our web worker and wire all the events.
  10822. */
  10823. init() {
  10824. if (this.transmuxer) {
  10825. this.transmuxer.dispose();
  10826. }
  10827. this.transmuxer = new transmuxer.Transmuxer(this.options);
  10828. wireTransmuxerEvents(this.self, this.transmuxer);
  10829. }
  10830. pushMp4Captions(data) {
  10831. if (!this.captionParser) {
  10832. this.captionParser = new captionParser();
  10833. this.captionParser.init();
  10834. }
  10835. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  10836. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  10837. this.self.postMessage({
  10838. action: 'mp4Captions',
  10839. captions: parsed && parsed.captions || [],
  10840. logs: parsed && parsed.logs || [],
  10841. data: segment.buffer
  10842. }, [segment.buffer]);
  10843. }
  10844. probeMp4StartTime({
  10845. timescales,
  10846. data
  10847. }) {
  10848. const startTime = probe$2.startTime(timescales, data);
  10849. this.self.postMessage({
  10850. action: 'probeMp4StartTime',
  10851. startTime,
  10852. data
  10853. }, [data.buffer]);
  10854. }
  10855. probeMp4Tracks({
  10856. data
  10857. }) {
  10858. const tracks = probe$2.tracks(data);
  10859. this.self.postMessage({
  10860. action: 'probeMp4Tracks',
  10861. tracks,
  10862. data
  10863. }, [data.buffer]);
  10864. }
  10865. /**
  10866. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  10867. * internal "media time," as well as whether it contains video and/or audio.
  10868. *
  10869. * @private
  10870. * @param {Uint8Array} bytes - segment bytes
  10871. * @param {number} baseStartTime
  10872. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  10873. * This value should be in seconds, as it's converted to a 90khz clock within the
  10874. * function body.
  10875. * @return {Object} The start time of the current segment in "media time" as well as
  10876. * whether it contains video and/or audio
  10877. */
  10878. probeTs({
  10879. data,
  10880. baseStartTime
  10881. }) {
  10882. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  10883. const timeInfo = tsInspector.inspect(data, tsStartTime);
  10884. let result = null;
  10885. if (timeInfo) {
  10886. result = {
  10887. // each type's time info comes back as an array of 2 times, start and end
  10888. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  10889. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  10890. };
  10891. if (result.hasVideo) {
  10892. result.videoStart = timeInfo.video[0].ptsTime;
  10893. }
  10894. if (result.hasAudio) {
  10895. result.audioStart = timeInfo.audio[0].ptsTime;
  10896. }
  10897. }
  10898. this.self.postMessage({
  10899. action: 'probeTs',
  10900. result,
  10901. data
  10902. }, [data.buffer]);
  10903. }
  10904. clearAllMp4Captions() {
  10905. if (this.captionParser) {
  10906. this.captionParser.clearAllCaptions();
  10907. }
  10908. }
  10909. clearParsedMp4Captions() {
  10910. if (this.captionParser) {
  10911. this.captionParser.clearParsedCaptions();
  10912. }
  10913. }
  10914. /**
  10915. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  10916. * processing.
  10917. *
  10918. * @param {ArrayBuffer} data data to push into the muxer
  10919. */
  10920. push(data) {
  10921. // Cast array buffer to correct type for transmuxer
  10922. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  10923. this.transmuxer.push(segment);
  10924. }
  10925. /**
  10926. * Recreate the transmuxer so that the next segment added via `push`
  10927. * start with a fresh transmuxer.
  10928. */
  10929. reset() {
  10930. this.transmuxer.reset();
  10931. }
  10932. /**
  10933. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  10934. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  10935. * set relative to the first based on the PTS values.
  10936. *
  10937. * @param {Object} data used to set the timestamp offset in the muxer
  10938. */
  10939. setTimestampOffset(data) {
  10940. const timestampOffset = data.timestampOffset || 0;
  10941. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  10942. }
  10943. setAudioAppendStart(data) {
  10944. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  10945. }
  10946. setRemux(data) {
  10947. this.transmuxer.setRemux(data.remux);
  10948. }
  10949. /**
  10950. * Forces the pipeline to finish processing the last segment and emit it's
  10951. * results.
  10952. *
  10953. * @param {Object} data event data, not really used
  10954. */
  10955. flush(data) {
  10956. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  10957. self.postMessage({
  10958. action: 'done',
  10959. type: 'transmuxed'
  10960. });
  10961. }
  10962. endTimeline() {
  10963. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  10964. // timelines
  10965. self.postMessage({
  10966. action: 'endedtimeline',
  10967. type: 'transmuxed'
  10968. });
  10969. }
  10970. alignGopsWith(data) {
  10971. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  10972. }
  10973. }
  10974. /**
  10975. * Our web worker interface so that things can talk to mux.js
  10976. * that will be running in a web worker. the scope is passed to this by
  10977. * webworkify.
  10978. *
  10979. * @param {Object} self the scope for the web worker
  10980. */
  10981. self.onmessage = function (event) {
  10982. if (event.data.action === 'init' && event.data.options) {
  10983. this.messageHandlers = new MessageHandlers(self, event.data.options);
  10984. return;
  10985. }
  10986. if (!this.messageHandlers) {
  10987. this.messageHandlers = new MessageHandlers(self);
  10988. }
  10989. if (event.data && event.data.action && event.data.action !== 'init') {
  10990. if (this.messageHandlers[event.data.action]) {
  10991. this.messageHandlers[event.data.action](event.data);
  10992. }
  10993. }
  10994. };
  10995. }));
  10996. var TransmuxWorker = factory(workerCode$1);
  10997. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  10998. const handleData_ = (event, transmuxedData, callback) => {
  10999. const {
  11000. type,
  11001. initSegment,
  11002. captions,
  11003. captionStreams,
  11004. metadata,
  11005. videoFrameDtsTime,
  11006. videoFramePtsTime
  11007. } = event.data.segment;
  11008. transmuxedData.buffer.push({
  11009. captions,
  11010. captionStreams,
  11011. metadata
  11012. });
  11013. const boxes = event.data.segment.boxes || {
  11014. data: event.data.segment.data
  11015. };
  11016. const result = {
  11017. type,
  11018. // cast ArrayBuffer to TypedArray
  11019. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  11020. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  11021. };
  11022. if (typeof videoFrameDtsTime !== 'undefined') {
  11023. result.videoFrameDtsTime = videoFrameDtsTime;
  11024. }
  11025. if (typeof videoFramePtsTime !== 'undefined') {
  11026. result.videoFramePtsTime = videoFramePtsTime;
  11027. }
  11028. callback(result);
  11029. };
  11030. const handleDone_ = ({
  11031. transmuxedData,
  11032. callback
  11033. }) => {
  11034. // Previously we only returned data on data events,
  11035. // not on done events. Clear out the buffer to keep that consistent.
  11036. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  11037. // have received
  11038. callback(transmuxedData);
  11039. };
  11040. const handleGopInfo_ = (event, transmuxedData) => {
  11041. transmuxedData.gopInfo = event.data.gopInfo;
  11042. };
  11043. const processTransmux = options => {
  11044. const {
  11045. transmuxer,
  11046. bytes,
  11047. audioAppendStart,
  11048. gopsToAlignWith,
  11049. remux,
  11050. onData,
  11051. onTrackInfo,
  11052. onAudioTimingInfo,
  11053. onVideoTimingInfo,
  11054. onVideoSegmentTimingInfo,
  11055. onAudioSegmentTimingInfo,
  11056. onId3,
  11057. onCaptions,
  11058. onDone,
  11059. onEndedTimeline,
  11060. onTransmuxerLog,
  11061. isEndOfTimeline
  11062. } = options;
  11063. const transmuxedData = {
  11064. buffer: []
  11065. };
  11066. let waitForEndedTimelineEvent = isEndOfTimeline;
  11067. const handleMessage = event => {
  11068. if (transmuxer.currentTransmux !== options) {
  11069. // disposed
  11070. return;
  11071. }
  11072. if (event.data.action === 'data') {
  11073. handleData_(event, transmuxedData, onData);
  11074. }
  11075. if (event.data.action === 'trackinfo') {
  11076. onTrackInfo(event.data.trackInfo);
  11077. }
  11078. if (event.data.action === 'gopInfo') {
  11079. handleGopInfo_(event, transmuxedData);
  11080. }
  11081. if (event.data.action === 'audioTimingInfo') {
  11082. onAudioTimingInfo(event.data.audioTimingInfo);
  11083. }
  11084. if (event.data.action === 'videoTimingInfo') {
  11085. onVideoTimingInfo(event.data.videoTimingInfo);
  11086. }
  11087. if (event.data.action === 'videoSegmentTimingInfo') {
  11088. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  11089. }
  11090. if (event.data.action === 'audioSegmentTimingInfo') {
  11091. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  11092. }
  11093. if (event.data.action === 'id3Frame') {
  11094. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  11095. }
  11096. if (event.data.action === 'caption') {
  11097. onCaptions(event.data.caption);
  11098. }
  11099. if (event.data.action === 'endedtimeline') {
  11100. waitForEndedTimelineEvent = false;
  11101. onEndedTimeline();
  11102. }
  11103. if (event.data.action === 'log') {
  11104. onTransmuxerLog(event.data.log);
  11105. } // wait for the transmuxed event since we may have audio and video
  11106. if (event.data.type !== 'transmuxed') {
  11107. return;
  11108. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  11109. // of a timeline, that means there may still be data events before the segment
  11110. // processing can be considerred complete. In that case, the final event should be
  11111. // an "endedtimeline" event with the type "transmuxed."
  11112. if (waitForEndedTimelineEvent) {
  11113. return;
  11114. }
  11115. transmuxer.onmessage = null;
  11116. handleDone_({
  11117. transmuxedData,
  11118. callback: onDone
  11119. });
  11120. /* eslint-disable no-use-before-define */
  11121. dequeue(transmuxer);
  11122. /* eslint-enable */
  11123. };
  11124. transmuxer.onmessage = handleMessage;
  11125. if (audioAppendStart) {
  11126. transmuxer.postMessage({
  11127. action: 'setAudioAppendStart',
  11128. appendStart: audioAppendStart
  11129. });
  11130. } // allow empty arrays to be passed to clear out GOPs
  11131. if (Array.isArray(gopsToAlignWith)) {
  11132. transmuxer.postMessage({
  11133. action: 'alignGopsWith',
  11134. gopsToAlignWith
  11135. });
  11136. }
  11137. if (typeof remux !== 'undefined') {
  11138. transmuxer.postMessage({
  11139. action: 'setRemux',
  11140. remux
  11141. });
  11142. }
  11143. if (bytes.byteLength) {
  11144. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  11145. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  11146. transmuxer.postMessage({
  11147. action: 'push',
  11148. // Send the typed-array of data as an ArrayBuffer so that
  11149. // it can be sent as a "Transferable" and avoid the costly
  11150. // memory copy
  11151. data: buffer,
  11152. // To recreate the original typed-array, we need information
  11153. // about what portion of the ArrayBuffer it was a view into
  11154. byteOffset,
  11155. byteLength: bytes.byteLength
  11156. }, [buffer]);
  11157. }
  11158. if (isEndOfTimeline) {
  11159. transmuxer.postMessage({
  11160. action: 'endTimeline'
  11161. });
  11162. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  11163. // the end of the segment
  11164. transmuxer.postMessage({
  11165. action: 'flush'
  11166. });
  11167. };
  11168. const dequeue = transmuxer => {
  11169. transmuxer.currentTransmux = null;
  11170. if (transmuxer.transmuxQueue.length) {
  11171. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  11172. if (typeof transmuxer.currentTransmux === 'function') {
  11173. transmuxer.currentTransmux();
  11174. } else {
  11175. processTransmux(transmuxer.currentTransmux);
  11176. }
  11177. }
  11178. };
  11179. const processAction = (transmuxer, action) => {
  11180. transmuxer.postMessage({
  11181. action
  11182. });
  11183. dequeue(transmuxer);
  11184. };
  11185. const enqueueAction = (action, transmuxer) => {
  11186. if (!transmuxer.currentTransmux) {
  11187. transmuxer.currentTransmux = action;
  11188. processAction(transmuxer, action);
  11189. return;
  11190. }
  11191. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  11192. };
  11193. const reset = transmuxer => {
  11194. enqueueAction('reset', transmuxer);
  11195. };
  11196. const endTimeline = transmuxer => {
  11197. enqueueAction('endTimeline', transmuxer);
  11198. };
  11199. const transmux = options => {
  11200. if (!options.transmuxer.currentTransmux) {
  11201. options.transmuxer.currentTransmux = options;
  11202. processTransmux(options);
  11203. return;
  11204. }
  11205. options.transmuxer.transmuxQueue.push(options);
  11206. };
  11207. const createTransmuxer = options => {
  11208. const transmuxer = new TransmuxWorker();
  11209. transmuxer.currentTransmux = null;
  11210. transmuxer.transmuxQueue = [];
  11211. const term = transmuxer.terminate;
  11212. transmuxer.terminate = () => {
  11213. transmuxer.currentTransmux = null;
  11214. transmuxer.transmuxQueue.length = 0;
  11215. return term.call(transmuxer);
  11216. };
  11217. transmuxer.postMessage({
  11218. action: 'init',
  11219. options
  11220. });
  11221. return transmuxer;
  11222. };
  11223. var segmentTransmuxer = {
  11224. reset,
  11225. endTimeline,
  11226. transmux,
  11227. createTransmuxer
  11228. };
  11229. const workerCallback = function (options) {
  11230. const transmuxer = options.transmuxer;
  11231. const endAction = options.endAction || options.action;
  11232. const callback = options.callback;
  11233. const message = _extends({}, options, {
  11234. endAction: null,
  11235. transmuxer: null,
  11236. callback: null
  11237. });
  11238. const listenForEndEvent = event => {
  11239. if (event.data.action !== endAction) {
  11240. return;
  11241. }
  11242. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  11243. if (event.data.data) {
  11244. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  11245. if (options.data) {
  11246. options.data = event.data.data;
  11247. }
  11248. }
  11249. callback(event.data);
  11250. };
  11251. transmuxer.addEventListener('message', listenForEndEvent);
  11252. if (options.data) {
  11253. const isArrayBuffer = options.data instanceof ArrayBuffer;
  11254. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  11255. message.byteLength = options.data.byteLength;
  11256. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  11257. transmuxer.postMessage(message, transfers);
  11258. } else {
  11259. transmuxer.postMessage(message);
  11260. }
  11261. };
  11262. const REQUEST_ERRORS = {
  11263. FAILURE: 2,
  11264. TIMEOUT: -101,
  11265. ABORTED: -102
  11266. };
  11267. /**
  11268. * Abort all requests
  11269. *
  11270. * @param {Object} activeXhrs - an object that tracks all XHR requests
  11271. */
  11272. const abortAll = activeXhrs => {
  11273. activeXhrs.forEach(xhr => {
  11274. xhr.abort();
  11275. });
  11276. };
  11277. /**
  11278. * Gather important bandwidth stats once a request has completed
  11279. *
  11280. * @param {Object} request - the XHR request from which to gather stats
  11281. */
  11282. const getRequestStats = request => {
  11283. return {
  11284. bandwidth: request.bandwidth,
  11285. bytesReceived: request.bytesReceived || 0,
  11286. roundTripTime: request.roundTripTime || 0
  11287. };
  11288. };
  11289. /**
  11290. * If possible gather bandwidth stats as a request is in
  11291. * progress
  11292. *
  11293. * @param {Event} progressEvent - an event object from an XHR's progress event
  11294. */
  11295. const getProgressStats = progressEvent => {
  11296. const request = progressEvent.target;
  11297. const roundTripTime = Date.now() - request.requestTime;
  11298. const stats = {
  11299. bandwidth: Infinity,
  11300. bytesReceived: 0,
  11301. roundTripTime: roundTripTime || 0
  11302. };
  11303. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  11304. // because we should only use bandwidth stats on progress to determine when
  11305. // abort a request early due to insufficient bandwidth
  11306. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  11307. return stats;
  11308. };
  11309. /**
  11310. * Handle all error conditions in one place and return an object
  11311. * with all the information
  11312. *
  11313. * @param {Error|null} error - if non-null signals an error occured with the XHR
  11314. * @param {Object} request - the XHR request that possibly generated the error
  11315. */
  11316. const handleErrors = (error, request) => {
  11317. if (request.timedout) {
  11318. return {
  11319. status: request.status,
  11320. message: 'HLS request timed-out at URL: ' + request.uri,
  11321. code: REQUEST_ERRORS.TIMEOUT,
  11322. xhr: request
  11323. };
  11324. }
  11325. if (request.aborted) {
  11326. return {
  11327. status: request.status,
  11328. message: 'HLS request aborted at URL: ' + request.uri,
  11329. code: REQUEST_ERRORS.ABORTED,
  11330. xhr: request
  11331. };
  11332. }
  11333. if (error) {
  11334. return {
  11335. status: request.status,
  11336. message: 'HLS request errored at URL: ' + request.uri,
  11337. code: REQUEST_ERRORS.FAILURE,
  11338. xhr: request
  11339. };
  11340. }
  11341. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  11342. return {
  11343. status: request.status,
  11344. message: 'Empty HLS response at URL: ' + request.uri,
  11345. code: REQUEST_ERRORS.FAILURE,
  11346. xhr: request
  11347. };
  11348. }
  11349. return null;
  11350. };
  11351. /**
  11352. * Handle responses for key data and convert the key data to the correct format
  11353. * for the decryption step later
  11354. *
  11355. * @param {Object} segment - a simplified copy of the segmentInfo object
  11356. * from SegmentLoader
  11357. * @param {Array} objects - objects to add the key bytes to.
  11358. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11359. * this request
  11360. */
  11361. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  11362. const response = request.response;
  11363. const errorObj = handleErrors(error, request);
  11364. if (errorObj) {
  11365. return finishProcessingFn(errorObj, segment);
  11366. }
  11367. if (response.byteLength !== 16) {
  11368. return finishProcessingFn({
  11369. status: request.status,
  11370. message: 'Invalid HLS key at URL: ' + request.uri,
  11371. code: REQUEST_ERRORS.FAILURE,
  11372. xhr: request
  11373. }, segment);
  11374. }
  11375. const view = new DataView(response);
  11376. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  11377. for (let i = 0; i < objects.length; i++) {
  11378. objects[i].bytes = bytes;
  11379. }
  11380. return finishProcessingFn(null, segment);
  11381. };
  11382. const parseInitSegment = (segment, callback) => {
  11383. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  11384. // only know how to parse mp4 init segments at the moment
  11385. if (type !== 'mp4') {
  11386. const uri = segment.map.resolvedUri || segment.map.uri;
  11387. return callback({
  11388. internal: true,
  11389. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  11390. code: REQUEST_ERRORS.FAILURE
  11391. });
  11392. }
  11393. workerCallback({
  11394. action: 'probeMp4Tracks',
  11395. data: segment.map.bytes,
  11396. transmuxer: segment.transmuxer,
  11397. callback: ({
  11398. tracks,
  11399. data
  11400. }) => {
  11401. // transfer bytes back to us
  11402. segment.map.bytes = data;
  11403. tracks.forEach(function (track) {
  11404. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  11405. if (segment.map.tracks[track.type]) {
  11406. return;
  11407. }
  11408. segment.map.tracks[track.type] = track;
  11409. if (typeof track.id === 'number' && track.timescale) {
  11410. segment.map.timescales = segment.map.timescales || {};
  11411. segment.map.timescales[track.id] = track.timescale;
  11412. }
  11413. });
  11414. return callback(null);
  11415. }
  11416. });
  11417. };
  11418. /**
  11419. * Handle init-segment responses
  11420. *
  11421. * @param {Object} segment - a simplified copy of the segmentInfo object
  11422. * from SegmentLoader
  11423. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11424. * this request
  11425. */
  11426. const handleInitSegmentResponse = ({
  11427. segment,
  11428. finishProcessingFn
  11429. }) => (error, request) => {
  11430. const errorObj = handleErrors(error, request);
  11431. if (errorObj) {
  11432. return finishProcessingFn(errorObj, segment);
  11433. }
  11434. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  11435. // until the key request is done to decrypt.
  11436. if (segment.map.key) {
  11437. segment.map.encryptedBytes = bytes;
  11438. return finishProcessingFn(null, segment);
  11439. }
  11440. segment.map.bytes = bytes;
  11441. parseInitSegment(segment, function (parseError) {
  11442. if (parseError) {
  11443. parseError.xhr = request;
  11444. parseError.status = request.status;
  11445. return finishProcessingFn(parseError, segment);
  11446. }
  11447. finishProcessingFn(null, segment);
  11448. });
  11449. };
  11450. /**
  11451. * Response handler for segment-requests being sure to set the correct
  11452. * property depending on whether the segment is encryped or not
  11453. * Also records and keeps track of stats that are used for ABR purposes
  11454. *
  11455. * @param {Object} segment - a simplified copy of the segmentInfo object
  11456. * from SegmentLoader
  11457. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11458. * this request
  11459. */
  11460. const handleSegmentResponse = ({
  11461. segment,
  11462. finishProcessingFn,
  11463. responseType
  11464. }) => (error, request) => {
  11465. const errorObj = handleErrors(error, request);
  11466. if (errorObj) {
  11467. return finishProcessingFn(errorObj, segment);
  11468. }
  11469. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  11470. // thrown for two primary cases:
  11471. // 1. the mime type override stops working, or is not implemented for a specific
  11472. // browser
  11473. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  11474. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  11475. segment.stats = getRequestStats(request);
  11476. if (segment.key) {
  11477. segment.encryptedBytes = new Uint8Array(newBytes);
  11478. } else {
  11479. segment.bytes = new Uint8Array(newBytes);
  11480. }
  11481. return finishProcessingFn(null, segment);
  11482. };
  11483. const transmuxAndNotify = ({
  11484. segment,
  11485. bytes,
  11486. trackInfoFn,
  11487. timingInfoFn,
  11488. videoSegmentTimingInfoFn,
  11489. audioSegmentTimingInfoFn,
  11490. id3Fn,
  11491. captionsFn,
  11492. isEndOfTimeline,
  11493. endedTimelineFn,
  11494. dataFn,
  11495. doneFn,
  11496. onTransmuxerLog
  11497. }) => {
  11498. const fmp4Tracks = segment.map && segment.map.tracks || {};
  11499. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  11500. // One reason for this is that in the case of full segments, we want to trust start
  11501. // times from the probe, rather than the transmuxer.
  11502. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  11503. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  11504. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  11505. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  11506. const finish = () => transmux({
  11507. bytes,
  11508. transmuxer: segment.transmuxer,
  11509. audioAppendStart: segment.audioAppendStart,
  11510. gopsToAlignWith: segment.gopsToAlignWith,
  11511. remux: isMuxed,
  11512. onData: result => {
  11513. result.type = result.type === 'combined' ? 'video' : result.type;
  11514. dataFn(segment, result);
  11515. },
  11516. onTrackInfo: trackInfo => {
  11517. if (trackInfoFn) {
  11518. if (isMuxed) {
  11519. trackInfo.isMuxed = true;
  11520. }
  11521. trackInfoFn(segment, trackInfo);
  11522. }
  11523. },
  11524. onAudioTimingInfo: audioTimingInfo => {
  11525. // we only want the first start value we encounter
  11526. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  11527. audioStartFn(audioTimingInfo.start);
  11528. audioStartFn = null;
  11529. } // we want to continually update the end time
  11530. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  11531. audioEndFn(audioTimingInfo.end);
  11532. }
  11533. },
  11534. onVideoTimingInfo: videoTimingInfo => {
  11535. // we only want the first start value we encounter
  11536. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  11537. videoStartFn(videoTimingInfo.start);
  11538. videoStartFn = null;
  11539. } // we want to continually update the end time
  11540. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  11541. videoEndFn(videoTimingInfo.end);
  11542. }
  11543. },
  11544. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  11545. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  11546. },
  11547. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  11548. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  11549. },
  11550. onId3: (id3Frames, dispatchType) => {
  11551. id3Fn(segment, id3Frames, dispatchType);
  11552. },
  11553. onCaptions: captions => {
  11554. captionsFn(segment, [captions]);
  11555. },
  11556. isEndOfTimeline,
  11557. onEndedTimeline: () => {
  11558. endedTimelineFn();
  11559. },
  11560. onTransmuxerLog,
  11561. onDone: result => {
  11562. if (!doneFn) {
  11563. return;
  11564. }
  11565. result.type = result.type === 'combined' ? 'video' : result.type;
  11566. doneFn(null, segment, result);
  11567. }
  11568. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  11569. // Meaning cached frame data may corrupt our notion of where this segment
  11570. // really starts. To get around this, probe for the info needed.
  11571. workerCallback({
  11572. action: 'probeTs',
  11573. transmuxer: segment.transmuxer,
  11574. data: bytes,
  11575. baseStartTime: segment.baseStartTime,
  11576. callback: data => {
  11577. segment.bytes = bytes = data.data;
  11578. const probeResult = data.result;
  11579. if (probeResult) {
  11580. trackInfoFn(segment, {
  11581. hasAudio: probeResult.hasAudio,
  11582. hasVideo: probeResult.hasVideo,
  11583. isMuxed
  11584. });
  11585. trackInfoFn = null;
  11586. if (probeResult.hasAudio && !isMuxed) {
  11587. audioStartFn(probeResult.audioStart);
  11588. }
  11589. if (probeResult.hasVideo) {
  11590. videoStartFn(probeResult.videoStart);
  11591. }
  11592. audioStartFn = null;
  11593. videoStartFn = null;
  11594. }
  11595. finish();
  11596. }
  11597. });
  11598. };
  11599. const handleSegmentBytes = ({
  11600. segment,
  11601. bytes,
  11602. trackInfoFn,
  11603. timingInfoFn,
  11604. videoSegmentTimingInfoFn,
  11605. audioSegmentTimingInfoFn,
  11606. id3Fn,
  11607. captionsFn,
  11608. isEndOfTimeline,
  11609. endedTimelineFn,
  11610. dataFn,
  11611. doneFn,
  11612. onTransmuxerLog
  11613. }) => {
  11614. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  11615. // We should have a handler that fetches the number of bytes required
  11616. // to check if something is fmp4. This will allow us to save bandwidth
  11617. // because we can only exclude a playlist and abort requests
  11618. // by codec after trackinfo triggers.
  11619. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  11620. segment.isFmp4 = true;
  11621. const {
  11622. tracks
  11623. } = segment.map;
  11624. const trackInfo = {
  11625. isFmp4: true,
  11626. hasVideo: !!tracks.video,
  11627. hasAudio: !!tracks.audio
  11628. }; // if we have a audio track, with a codec that is not set to
  11629. // encrypted audio
  11630. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  11631. trackInfo.audioCodec = tracks.audio.codec;
  11632. } // if we have a video track, with a codec that is not set to
  11633. // encrypted video
  11634. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  11635. trackInfo.videoCodec = tracks.video.codec;
  11636. }
  11637. if (tracks.video && tracks.audio) {
  11638. trackInfo.isMuxed = true;
  11639. } // since we don't support appending fmp4 data on progress, we know we have the full
  11640. // segment here
  11641. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  11642. // time. The end time can be roughly calculated by the receiver using the duration.
  11643. //
  11644. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  11645. // that is the true start of the segment (where the playback engine should begin
  11646. // decoding).
  11647. const finishLoading = captions => {
  11648. // if the track still has audio at this point it is only possible
  11649. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  11650. // above.
  11651. // we make sure to use segment.bytes here as that
  11652. dataFn(segment, {
  11653. data: bytesAsUint8Array,
  11654. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  11655. });
  11656. if (captions && captions.length) {
  11657. captionsFn(segment, captions);
  11658. }
  11659. doneFn(null, segment, {});
  11660. };
  11661. workerCallback({
  11662. action: 'probeMp4StartTime',
  11663. timescales: segment.map.timescales,
  11664. data: bytesAsUint8Array,
  11665. transmuxer: segment.transmuxer,
  11666. callback: ({
  11667. data,
  11668. startTime
  11669. }) => {
  11670. // transfer bytes back to us
  11671. bytes = data.buffer;
  11672. segment.bytes = bytesAsUint8Array = data;
  11673. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  11674. timingInfoFn(segment, 'audio', 'start', startTime);
  11675. }
  11676. if (trackInfo.hasVideo) {
  11677. timingInfoFn(segment, 'video', 'start', startTime);
  11678. } // Run through the CaptionParser in case there are captions.
  11679. // Initialize CaptionParser if it hasn't been yet
  11680. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  11681. finishLoading();
  11682. return;
  11683. }
  11684. workerCallback({
  11685. action: 'pushMp4Captions',
  11686. endAction: 'mp4Captions',
  11687. transmuxer: segment.transmuxer,
  11688. data: bytesAsUint8Array,
  11689. timescales: segment.map.timescales,
  11690. trackIds: [tracks.video.id],
  11691. callback: message => {
  11692. // transfer bytes back to us
  11693. bytes = message.data.buffer;
  11694. segment.bytes = bytesAsUint8Array = message.data;
  11695. message.logs.forEach(function (log) {
  11696. onTransmuxerLog(merge(log, {
  11697. stream: 'mp4CaptionParser'
  11698. }));
  11699. });
  11700. finishLoading(message.captions);
  11701. }
  11702. });
  11703. }
  11704. });
  11705. return;
  11706. } // VTT or other segments that don't need processing
  11707. if (!segment.transmuxer) {
  11708. doneFn(null, segment, {});
  11709. return;
  11710. }
  11711. if (typeof segment.container === 'undefined') {
  11712. segment.container = detectContainerForBytes(bytesAsUint8Array);
  11713. }
  11714. if (segment.container !== 'ts' && segment.container !== 'aac') {
  11715. trackInfoFn(segment, {
  11716. hasAudio: false,
  11717. hasVideo: false
  11718. });
  11719. doneFn(null, segment, {});
  11720. return;
  11721. } // ts or aac
  11722. transmuxAndNotify({
  11723. segment,
  11724. bytes,
  11725. trackInfoFn,
  11726. timingInfoFn,
  11727. videoSegmentTimingInfoFn,
  11728. audioSegmentTimingInfoFn,
  11729. id3Fn,
  11730. captionsFn,
  11731. isEndOfTimeline,
  11732. endedTimelineFn,
  11733. dataFn,
  11734. doneFn,
  11735. onTransmuxerLog
  11736. });
  11737. };
  11738. const decrypt = function ({
  11739. id,
  11740. key,
  11741. encryptedBytes,
  11742. decryptionWorker
  11743. }, callback) {
  11744. const decryptionHandler = event => {
  11745. if (event.data.source === id) {
  11746. decryptionWorker.removeEventListener('message', decryptionHandler);
  11747. const decrypted = event.data.decrypted;
  11748. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  11749. }
  11750. };
  11751. decryptionWorker.addEventListener('message', decryptionHandler);
  11752. let keyBytes;
  11753. if (key.bytes.slice) {
  11754. keyBytes = key.bytes.slice();
  11755. } else {
  11756. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  11757. } // incrementally decrypt the bytes
  11758. decryptionWorker.postMessage(createTransferableMessage({
  11759. source: id,
  11760. encrypted: encryptedBytes,
  11761. key: keyBytes,
  11762. iv: key.iv
  11763. }), [encryptedBytes.buffer, keyBytes.buffer]);
  11764. };
  11765. /**
  11766. * Decrypt the segment via the decryption web worker
  11767. *
  11768. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  11769. * routines
  11770. * @param {Object} segment - a simplified copy of the segmentInfo object
  11771. * from SegmentLoader
  11772. * @param {Function} trackInfoFn - a callback that receives track info
  11773. * @param {Function} timingInfoFn - a callback that receives timing info
  11774. * @param {Function} videoSegmentTimingInfoFn
  11775. * a callback that receives video timing info based on media times and
  11776. * any adjustments made by the transmuxer
  11777. * @param {Function} audioSegmentTimingInfoFn
  11778. * a callback that receives audio timing info based on media times and
  11779. * any adjustments made by the transmuxer
  11780. * @param {boolean} isEndOfTimeline
  11781. * true if this segment represents the last segment in a timeline
  11782. * @param {Function} endedTimelineFn
  11783. * a callback made when a timeline is ended, will only be called if
  11784. * isEndOfTimeline is true
  11785. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  11786. * and ready to use
  11787. * @param {Function} doneFn - a callback that is executed after decryption has completed
  11788. */
  11789. const decryptSegment = ({
  11790. decryptionWorker,
  11791. segment,
  11792. trackInfoFn,
  11793. timingInfoFn,
  11794. videoSegmentTimingInfoFn,
  11795. audioSegmentTimingInfoFn,
  11796. id3Fn,
  11797. captionsFn,
  11798. isEndOfTimeline,
  11799. endedTimelineFn,
  11800. dataFn,
  11801. doneFn,
  11802. onTransmuxerLog
  11803. }) => {
  11804. decrypt({
  11805. id: segment.requestId,
  11806. key: segment.key,
  11807. encryptedBytes: segment.encryptedBytes,
  11808. decryptionWorker
  11809. }, decryptedBytes => {
  11810. segment.bytes = decryptedBytes;
  11811. handleSegmentBytes({
  11812. segment,
  11813. bytes: segment.bytes,
  11814. trackInfoFn,
  11815. timingInfoFn,
  11816. videoSegmentTimingInfoFn,
  11817. audioSegmentTimingInfoFn,
  11818. id3Fn,
  11819. captionsFn,
  11820. isEndOfTimeline,
  11821. endedTimelineFn,
  11822. dataFn,
  11823. doneFn,
  11824. onTransmuxerLog
  11825. });
  11826. });
  11827. };
  11828. /**
  11829. * This function waits for all XHRs to finish (with either success or failure)
  11830. * before continueing processing via it's callback. The function gathers errors
  11831. * from each request into a single errors array so that the error status for
  11832. * each request can be examined later.
  11833. *
  11834. * @param {Object} activeXhrs - an object that tracks all XHR requests
  11835. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  11836. * routines
  11837. * @param {Function} trackInfoFn - a callback that receives track info
  11838. * @param {Function} timingInfoFn - a callback that receives timing info
  11839. * @param {Function} videoSegmentTimingInfoFn
  11840. * a callback that receives video timing info based on media times and
  11841. * any adjustments made by the transmuxer
  11842. * @param {Function} audioSegmentTimingInfoFn
  11843. * a callback that receives audio timing info based on media times and
  11844. * any adjustments made by the transmuxer
  11845. * @param {Function} id3Fn - a callback that receives ID3 metadata
  11846. * @param {Function} captionsFn - a callback that receives captions
  11847. * @param {boolean} isEndOfTimeline
  11848. * true if this segment represents the last segment in a timeline
  11849. * @param {Function} endedTimelineFn
  11850. * a callback made when a timeline is ended, will only be called if
  11851. * isEndOfTimeline is true
  11852. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  11853. * and ready to use
  11854. * @param {Function} doneFn - a callback that is executed after all resources have been
  11855. * downloaded and any decryption completed
  11856. */
  11857. const waitForCompletion = ({
  11858. activeXhrs,
  11859. decryptionWorker,
  11860. trackInfoFn,
  11861. timingInfoFn,
  11862. videoSegmentTimingInfoFn,
  11863. audioSegmentTimingInfoFn,
  11864. id3Fn,
  11865. captionsFn,
  11866. isEndOfTimeline,
  11867. endedTimelineFn,
  11868. dataFn,
  11869. doneFn,
  11870. onTransmuxerLog
  11871. }) => {
  11872. let count = 0;
  11873. let didError = false;
  11874. return (error, segment) => {
  11875. if (didError) {
  11876. return;
  11877. }
  11878. if (error) {
  11879. didError = true; // If there are errors, we have to abort any outstanding requests
  11880. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  11881. // handle the aborted events from those requests, there are some cases where we may
  11882. // never get an aborted event. For instance, if the network connection is lost and
  11883. // there were two requests, the first may have triggered an error immediately, while
  11884. // the second request remains unsent. In that case, the aborted algorithm will not
  11885. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  11886. //
  11887. // We also can't rely on the ready state of the XHR, since the request that
  11888. // triggered the connection error may also show as a ready state of 0 (unsent).
  11889. // Therefore, we have to finish this group of requests immediately after the first
  11890. // seen error.
  11891. return doneFn(error, segment);
  11892. }
  11893. count += 1;
  11894. if (count === activeXhrs.length) {
  11895. const segmentFinish = function () {
  11896. if (segment.encryptedBytes) {
  11897. return decryptSegment({
  11898. decryptionWorker,
  11899. segment,
  11900. trackInfoFn,
  11901. timingInfoFn,
  11902. videoSegmentTimingInfoFn,
  11903. audioSegmentTimingInfoFn,
  11904. id3Fn,
  11905. captionsFn,
  11906. isEndOfTimeline,
  11907. endedTimelineFn,
  11908. dataFn,
  11909. doneFn,
  11910. onTransmuxerLog
  11911. });
  11912. } // Otherwise, everything is ready just continue
  11913. handleSegmentBytes({
  11914. segment,
  11915. bytes: segment.bytes,
  11916. trackInfoFn,
  11917. timingInfoFn,
  11918. videoSegmentTimingInfoFn,
  11919. audioSegmentTimingInfoFn,
  11920. id3Fn,
  11921. captionsFn,
  11922. isEndOfTimeline,
  11923. endedTimelineFn,
  11924. dataFn,
  11925. doneFn,
  11926. onTransmuxerLog
  11927. });
  11928. }; // Keep track of when *all* of the requests have completed
  11929. segment.endOfAllRequests = Date.now();
  11930. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  11931. return decrypt({
  11932. decryptionWorker,
  11933. // add -init to the "id" to differentiate between segment
  11934. // and init segment decryption, just in case they happen
  11935. // at the same time at some point in the future.
  11936. id: segment.requestId + '-init',
  11937. encryptedBytes: segment.map.encryptedBytes,
  11938. key: segment.map.key
  11939. }, decryptedBytes => {
  11940. segment.map.bytes = decryptedBytes;
  11941. parseInitSegment(segment, parseError => {
  11942. if (parseError) {
  11943. abortAll(activeXhrs);
  11944. return doneFn(parseError, segment);
  11945. }
  11946. segmentFinish();
  11947. });
  11948. });
  11949. }
  11950. segmentFinish();
  11951. }
  11952. };
  11953. };
  11954. /**
  11955. * Calls the abort callback if any request within the batch was aborted. Will only call
  11956. * the callback once per batch of requests, even if multiple were aborted.
  11957. *
  11958. * @param {Object} loadendState - state to check to see if the abort function was called
  11959. * @param {Function} abortFn - callback to call for abort
  11960. */
  11961. const handleLoadEnd = ({
  11962. loadendState,
  11963. abortFn
  11964. }) => event => {
  11965. const request = event.target;
  11966. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  11967. abortFn();
  11968. loadendState.calledAbortFn = true;
  11969. }
  11970. };
  11971. /**
  11972. * Simple progress event callback handler that gathers some stats before
  11973. * executing a provided callback with the `segment` object
  11974. *
  11975. * @param {Object} segment - a simplified copy of the segmentInfo object
  11976. * from SegmentLoader
  11977. * @param {Function} progressFn - a callback that is executed each time a progress event
  11978. * is received
  11979. * @param {Function} trackInfoFn - a callback that receives track info
  11980. * @param {Function} timingInfoFn - a callback that receives timing info
  11981. * @param {Function} videoSegmentTimingInfoFn
  11982. * a callback that receives video timing info based on media times and
  11983. * any adjustments made by the transmuxer
  11984. * @param {Function} audioSegmentTimingInfoFn
  11985. * a callback that receives audio timing info based on media times and
  11986. * any adjustments made by the transmuxer
  11987. * @param {boolean} isEndOfTimeline
  11988. * true if this segment represents the last segment in a timeline
  11989. * @param {Function} endedTimelineFn
  11990. * a callback made when a timeline is ended, will only be called if
  11991. * isEndOfTimeline is true
  11992. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  11993. * and ready to use
  11994. * @param {Event} event - the progress event object from XMLHttpRequest
  11995. */
  11996. const handleProgress = ({
  11997. segment,
  11998. progressFn,
  11999. trackInfoFn,
  12000. timingInfoFn,
  12001. videoSegmentTimingInfoFn,
  12002. audioSegmentTimingInfoFn,
  12003. id3Fn,
  12004. captionsFn,
  12005. isEndOfTimeline,
  12006. endedTimelineFn,
  12007. dataFn
  12008. }) => event => {
  12009. const request = event.target;
  12010. if (request.aborted) {
  12011. return;
  12012. }
  12013. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  12014. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  12015. segment.stats.firstBytesReceivedAt = Date.now();
  12016. }
  12017. return progressFn(event, segment);
  12018. };
  12019. /**
  12020. * Load all resources and does any processing necessary for a media-segment
  12021. *
  12022. * Features:
  12023. * decrypts the media-segment if it has a key uri and an iv
  12024. * aborts *all* requests if *any* one request fails
  12025. *
  12026. * The segment object, at minimum, has the following format:
  12027. * {
  12028. * resolvedUri: String,
  12029. * [transmuxer]: Object,
  12030. * [byterange]: {
  12031. * offset: Number,
  12032. * length: Number
  12033. * },
  12034. * [key]: {
  12035. * resolvedUri: String
  12036. * [byterange]: {
  12037. * offset: Number,
  12038. * length: Number
  12039. * },
  12040. * iv: {
  12041. * bytes: Uint32Array
  12042. * }
  12043. * },
  12044. * [map]: {
  12045. * resolvedUri: String,
  12046. * [byterange]: {
  12047. * offset: Number,
  12048. * length: Number
  12049. * },
  12050. * [bytes]: Uint8Array
  12051. * }
  12052. * }
  12053. * ...where [name] denotes optional properties
  12054. *
  12055. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  12056. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  12057. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  12058. * decryption routines
  12059. * @param {Object} segment - a simplified copy of the segmentInfo object
  12060. * from SegmentLoader
  12061. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  12062. * aborted
  12063. * @param {Function} progressFn - a callback that receives progress events from the main
  12064. * segment's xhr request
  12065. * @param {Function} trackInfoFn - a callback that receives track info
  12066. * @param {Function} timingInfoFn - a callback that receives timing info
  12067. * @param {Function} videoSegmentTimingInfoFn
  12068. * a callback that receives video timing info based on media times and
  12069. * any adjustments made by the transmuxer
  12070. * @param {Function} audioSegmentTimingInfoFn
  12071. * a callback that receives audio timing info based on media times and
  12072. * any adjustments made by the transmuxer
  12073. * @param {Function} id3Fn - a callback that receives ID3 metadata
  12074. * @param {Function} captionsFn - a callback that receives captions
  12075. * @param {boolean} isEndOfTimeline
  12076. * true if this segment represents the last segment in a timeline
  12077. * @param {Function} endedTimelineFn
  12078. * a callback made when a timeline is ended, will only be called if
  12079. * isEndOfTimeline is true
  12080. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  12081. * request, transmuxed if needed
  12082. * @param {Function} doneFn - a callback that is executed only once all requests have
  12083. * succeeded or failed
  12084. * @return {Function} a function that, when invoked, immediately aborts all
  12085. * outstanding requests
  12086. */
  12087. const mediaSegmentRequest = ({
  12088. xhr,
  12089. xhrOptions,
  12090. decryptionWorker,
  12091. segment,
  12092. abortFn,
  12093. progressFn,
  12094. trackInfoFn,
  12095. timingInfoFn,
  12096. videoSegmentTimingInfoFn,
  12097. audioSegmentTimingInfoFn,
  12098. id3Fn,
  12099. captionsFn,
  12100. isEndOfTimeline,
  12101. endedTimelineFn,
  12102. dataFn,
  12103. doneFn,
  12104. onTransmuxerLog
  12105. }) => {
  12106. const activeXhrs = [];
  12107. const finishProcessingFn = waitForCompletion({
  12108. activeXhrs,
  12109. decryptionWorker,
  12110. trackInfoFn,
  12111. timingInfoFn,
  12112. videoSegmentTimingInfoFn,
  12113. audioSegmentTimingInfoFn,
  12114. id3Fn,
  12115. captionsFn,
  12116. isEndOfTimeline,
  12117. endedTimelineFn,
  12118. dataFn,
  12119. doneFn,
  12120. onTransmuxerLog
  12121. }); // optionally, request the decryption key
  12122. if (segment.key && !segment.key.bytes) {
  12123. const objects = [segment.key];
  12124. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  12125. objects.push(segment.map.key);
  12126. }
  12127. const keyRequestOptions = merge(xhrOptions, {
  12128. uri: segment.key.resolvedUri,
  12129. responseType: 'arraybuffer'
  12130. });
  12131. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  12132. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  12133. activeXhrs.push(keyXhr);
  12134. } // optionally, request the associated media init segment
  12135. if (segment.map && !segment.map.bytes) {
  12136. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  12137. if (differentMapKey) {
  12138. const mapKeyRequestOptions = merge(xhrOptions, {
  12139. uri: segment.map.key.resolvedUri,
  12140. responseType: 'arraybuffer'
  12141. });
  12142. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  12143. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  12144. activeXhrs.push(mapKeyXhr);
  12145. }
  12146. const initSegmentOptions = merge(xhrOptions, {
  12147. uri: segment.map.resolvedUri,
  12148. responseType: 'arraybuffer',
  12149. headers: segmentXhrHeaders(segment.map)
  12150. });
  12151. const initSegmentRequestCallback = handleInitSegmentResponse({
  12152. segment,
  12153. finishProcessingFn
  12154. });
  12155. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  12156. activeXhrs.push(initSegmentXhr);
  12157. }
  12158. const segmentRequestOptions = merge(xhrOptions, {
  12159. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  12160. responseType: 'arraybuffer',
  12161. headers: segmentXhrHeaders(segment)
  12162. });
  12163. const segmentRequestCallback = handleSegmentResponse({
  12164. segment,
  12165. finishProcessingFn,
  12166. responseType: segmentRequestOptions.responseType
  12167. });
  12168. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  12169. segmentXhr.addEventListener('progress', handleProgress({
  12170. segment,
  12171. progressFn,
  12172. trackInfoFn,
  12173. timingInfoFn,
  12174. videoSegmentTimingInfoFn,
  12175. audioSegmentTimingInfoFn,
  12176. id3Fn,
  12177. captionsFn,
  12178. isEndOfTimeline,
  12179. endedTimelineFn,
  12180. dataFn
  12181. }));
  12182. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  12183. // multiple times, provide a shared state object
  12184. const loadendState = {};
  12185. activeXhrs.forEach(activeXhr => {
  12186. activeXhr.addEventListener('loadend', handleLoadEnd({
  12187. loadendState,
  12188. abortFn
  12189. }));
  12190. });
  12191. return () => abortAll(activeXhrs);
  12192. };
  12193. /**
  12194. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  12195. * codec strings, or translating codec strings into objects that can be examined.
  12196. */
  12197. const logFn$1 = logger('CodecUtils');
  12198. /**
  12199. * Returns a set of codec strings parsed from the playlist or the default
  12200. * codec strings if no codecs were specified in the playlist
  12201. *
  12202. * @param {Playlist} media the current media playlist
  12203. * @return {Object} an object with the video and audio codecs
  12204. */
  12205. const getCodecs = function (media) {
  12206. // if the codecs were explicitly specified, use them instead of the
  12207. // defaults
  12208. const mediaAttributes = media.attributes || {};
  12209. if (mediaAttributes.CODECS) {
  12210. return parseCodecs(mediaAttributes.CODECS);
  12211. }
  12212. };
  12213. const isMaat = (main, media) => {
  12214. const mediaAttributes = media.attributes || {};
  12215. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12216. };
  12217. const isMuxed = (main, media) => {
  12218. if (!isMaat(main, media)) {
  12219. return true;
  12220. }
  12221. const mediaAttributes = media.attributes || {};
  12222. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12223. for (const groupId in audioGroup) {
  12224. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  12225. // or there are listed playlists (the case for DASH, as the manifest will have already
  12226. // provided all of the details necessary to generate the audio playlist, as opposed to
  12227. // HLS' externally requested playlists), then the content is demuxed.
  12228. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  12229. return true;
  12230. }
  12231. }
  12232. return false;
  12233. };
  12234. const unwrapCodecList = function (codecList) {
  12235. const codecs = {};
  12236. codecList.forEach(({
  12237. mediaType,
  12238. type,
  12239. details
  12240. }) => {
  12241. codecs[mediaType] = codecs[mediaType] || [];
  12242. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  12243. });
  12244. Object.keys(codecs).forEach(function (mediaType) {
  12245. if (codecs[mediaType].length > 1) {
  12246. 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.`);
  12247. codecs[mediaType] = null;
  12248. return;
  12249. }
  12250. codecs[mediaType] = codecs[mediaType][0];
  12251. });
  12252. return codecs;
  12253. };
  12254. const codecCount = function (codecObj) {
  12255. let count = 0;
  12256. if (codecObj.audio) {
  12257. count++;
  12258. }
  12259. if (codecObj.video) {
  12260. count++;
  12261. }
  12262. return count;
  12263. };
  12264. /**
  12265. * Calculates the codec strings for a working configuration of
  12266. * SourceBuffers to play variant streams in a main playlist. If
  12267. * there is no possible working configuration, an empty object will be
  12268. * returned.
  12269. *
  12270. * @param main {Object} the m3u8 object for the main playlist
  12271. * @param media {Object} the m3u8 object for the variant playlist
  12272. * @return {Object} the codec strings.
  12273. *
  12274. * @private
  12275. */
  12276. const codecsForPlaylist = function (main, media) {
  12277. const mediaAttributes = media.attributes || {};
  12278. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  12279. // Put another way, there is no way to have a video-only multiple-audio HLS!
  12280. if (isMaat(main, media) && !codecInfo.audio) {
  12281. if (!isMuxed(main, media)) {
  12282. // It is possible for codecs to be specified on the audio media group playlist but
  12283. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  12284. // video are always separate (and separately specified).
  12285. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  12286. if (defaultCodecs.audio) {
  12287. codecInfo.audio = defaultCodecs.audio;
  12288. }
  12289. }
  12290. }
  12291. return codecInfo;
  12292. };
  12293. const logFn = logger('PlaylistSelector');
  12294. const representationToString = function (representation) {
  12295. if (!representation || !representation.playlist) {
  12296. return;
  12297. }
  12298. const playlist = representation.playlist;
  12299. return JSON.stringify({
  12300. id: playlist.id,
  12301. bandwidth: representation.bandwidth,
  12302. width: representation.width,
  12303. height: representation.height,
  12304. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  12305. });
  12306. }; // Utilities
  12307. /**
  12308. * Returns the CSS value for the specified property on an element
  12309. * using `getComputedStyle`. Firefox has a long-standing issue where
  12310. * getComputedStyle() may return null when running in an iframe with
  12311. * `display: none`.
  12312. *
  12313. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  12314. * @param {HTMLElement} el the htmlelement to work on
  12315. * @param {string} the proprety to get the style for
  12316. */
  12317. const safeGetComputedStyle = function (el, property) {
  12318. if (!el) {
  12319. return '';
  12320. }
  12321. const result = window$1.getComputedStyle(el);
  12322. if (!result) {
  12323. return '';
  12324. }
  12325. return result[property];
  12326. };
  12327. /**
  12328. * Resuable stable sort function
  12329. *
  12330. * @param {Playlists} array
  12331. * @param {Function} sortFn Different comparators
  12332. * @function stableSort
  12333. */
  12334. const stableSort = function (array, sortFn) {
  12335. const newArray = array.slice();
  12336. array.sort(function (left, right) {
  12337. const cmp = sortFn(left, right);
  12338. if (cmp === 0) {
  12339. return newArray.indexOf(left) - newArray.indexOf(right);
  12340. }
  12341. return cmp;
  12342. });
  12343. };
  12344. /**
  12345. * A comparator function to sort two playlist object by bandwidth.
  12346. *
  12347. * @param {Object} left a media playlist object
  12348. * @param {Object} right a media playlist object
  12349. * @return {number} Greater than zero if the bandwidth attribute of
  12350. * left is greater than the corresponding attribute of right. Less
  12351. * than zero if the bandwidth of right is greater than left and
  12352. * exactly zero if the two are equal.
  12353. */
  12354. const comparePlaylistBandwidth = function (left, right) {
  12355. let leftBandwidth;
  12356. let rightBandwidth;
  12357. if (left.attributes.BANDWIDTH) {
  12358. leftBandwidth = left.attributes.BANDWIDTH;
  12359. }
  12360. leftBandwidth = leftBandwidth || window$1.Number.MAX_VALUE;
  12361. if (right.attributes.BANDWIDTH) {
  12362. rightBandwidth = right.attributes.BANDWIDTH;
  12363. }
  12364. rightBandwidth = rightBandwidth || window$1.Number.MAX_VALUE;
  12365. return leftBandwidth - rightBandwidth;
  12366. };
  12367. /**
  12368. * A comparator function to sort two playlist object by resolution (width).
  12369. *
  12370. * @param {Object} left a media playlist object
  12371. * @param {Object} right a media playlist object
  12372. * @return {number} Greater than zero if the resolution.width attribute of
  12373. * left is greater than the corresponding attribute of right. Less
  12374. * than zero if the resolution.width of right is greater than left and
  12375. * exactly zero if the two are equal.
  12376. */
  12377. const comparePlaylistResolution = function (left, right) {
  12378. let leftWidth;
  12379. let rightWidth;
  12380. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  12381. leftWidth = left.attributes.RESOLUTION.width;
  12382. }
  12383. leftWidth = leftWidth || window$1.Number.MAX_VALUE;
  12384. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  12385. rightWidth = right.attributes.RESOLUTION.width;
  12386. }
  12387. rightWidth = rightWidth || window$1.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  12388. // have the same media dimensions/ resolution
  12389. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  12390. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  12391. }
  12392. return leftWidth - rightWidth;
  12393. };
  12394. /**
  12395. * Chooses the appropriate media playlist based on bandwidth and player size
  12396. *
  12397. * @param {Object} main
  12398. * Object representation of the main manifest
  12399. * @param {number} playerBandwidth
  12400. * Current calculated bandwidth of the player
  12401. * @param {number} playerWidth
  12402. * Current width of the player element (should account for the device pixel ratio)
  12403. * @param {number} playerHeight
  12404. * Current height of the player element (should account for the device pixel ratio)
  12405. * @param {boolean} limitRenditionByPlayerDimensions
  12406. * True if the player width and height should be used during the selection, false otherwise
  12407. * @param {Object} playlistController
  12408. * the current playlistController object
  12409. * @return {Playlist} the highest bitrate playlist less than the
  12410. * currently detected bandwidth, accounting for some amount of
  12411. * bandwidth variance
  12412. */
  12413. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  12414. // If we end up getting called before `main` is available, exit early
  12415. if (!main) {
  12416. return;
  12417. }
  12418. const options = {
  12419. bandwidth: playerBandwidth,
  12420. width: playerWidth,
  12421. height: playerHeight,
  12422. limitRenditionByPlayerDimensions
  12423. };
  12424. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  12425. if (Playlist.isAudioOnly(main)) {
  12426. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  12427. // at the buttom of this function for debugging.
  12428. options.audioOnly = true;
  12429. } // convert the playlists to an intermediary representation to make comparisons easier
  12430. let sortedPlaylistReps = playlists.map(playlist => {
  12431. let bandwidth;
  12432. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  12433. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  12434. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  12435. bandwidth = bandwidth || window$1.Number.MAX_VALUE;
  12436. return {
  12437. bandwidth,
  12438. width,
  12439. height,
  12440. playlist
  12441. };
  12442. });
  12443. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  12444. // incompatible configurations
  12445. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  12446. // api or excluded temporarily due to playback errors.
  12447. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  12448. if (!enabledPlaylistReps.length) {
  12449. // if there are no enabled playlists, then they have all been excluded or disabled
  12450. // by the user through the representations api. In this case, ignore exclusion and
  12451. // fallback to what the user wants by using playlists the user has not disabled.
  12452. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  12453. } // filter out any variant that has greater effective bitrate
  12454. // than the current estimated bandwidth
  12455. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  12456. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  12457. // and then taking the very first element
  12458. 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.
  12459. if (limitRenditionByPlayerDimensions === false) {
  12460. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  12461. if (chosenRep && chosenRep.playlist) {
  12462. let type = 'sortedPlaylistReps';
  12463. if (bandwidthBestRep) {
  12464. type = 'bandwidthBestRep';
  12465. }
  12466. if (enabledPlaylistReps[0]) {
  12467. type = 'enabledPlaylistReps';
  12468. }
  12469. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  12470. return chosenRep.playlist;
  12471. }
  12472. logFn('could not choose a playlist with options', options);
  12473. return null;
  12474. } // filter out playlists without resolution information
  12475. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  12476. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  12477. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  12478. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  12479. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  12480. let resolutionPlusOneList;
  12481. let resolutionPlusOneSmallest;
  12482. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  12483. // if there is no match of exact resolution
  12484. if (!resolutionBestRep) {
  12485. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  12486. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  12487. // is just-larger-than the video player
  12488. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  12489. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  12490. }
  12491. let leastPixelDiffRep; // If this selector proves to be better than others,
  12492. // resolutionPlusOneRep and resolutionBestRep and all
  12493. // the code involving them should be removed.
  12494. if (playlistController.leastPixelDiffSelector) {
  12495. // find the variant that is closest to the player's pixel size
  12496. const leastPixelDiffList = haveResolution.map(rep => {
  12497. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  12498. return rep;
  12499. }); // get the highest bandwidth, closest resolution playlist
  12500. stableSort(leastPixelDiffList, (left, right) => {
  12501. // sort by highest bandwidth if pixelDiff is the same
  12502. if (left.pixelDiff === right.pixelDiff) {
  12503. return right.bandwidth - left.bandwidth;
  12504. }
  12505. return left.pixelDiff - right.pixelDiff;
  12506. });
  12507. leastPixelDiffRep = leastPixelDiffList[0];
  12508. } // fallback chain of variants
  12509. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  12510. if (chosenRep && chosenRep.playlist) {
  12511. let type = 'sortedPlaylistReps';
  12512. if (leastPixelDiffRep) {
  12513. type = 'leastPixelDiffRep';
  12514. } else if (resolutionPlusOneRep) {
  12515. type = 'resolutionPlusOneRep';
  12516. } else if (resolutionBestRep) {
  12517. type = 'resolutionBestRep';
  12518. } else if (bandwidthBestRep) {
  12519. type = 'bandwidthBestRep';
  12520. } else if (enabledPlaylistReps[0]) {
  12521. type = 'enabledPlaylistReps';
  12522. }
  12523. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  12524. return chosenRep.playlist;
  12525. }
  12526. logFn('could not choose a playlist with options', options);
  12527. return null;
  12528. };
  12529. /**
  12530. * Chooses the appropriate media playlist based on the most recent
  12531. * bandwidth estimate and the player size.
  12532. *
  12533. * Expects to be called within the context of an instance of VhsHandler
  12534. *
  12535. * @return {Playlist} the highest bitrate playlist less than the
  12536. * currently detected bandwidth, accounting for some amount of
  12537. * bandwidth variance
  12538. */
  12539. const lastBandwidthSelector = function () {
  12540. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  12541. 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_);
  12542. };
  12543. /**
  12544. * Chooses the appropriate media playlist based on an
  12545. * exponential-weighted moving average of the bandwidth after
  12546. * filtering for player size.
  12547. *
  12548. * Expects to be called within the context of an instance of VhsHandler
  12549. *
  12550. * @param {number} decay - a number between 0 and 1. Higher values of
  12551. * this parameter will cause previous bandwidth estimates to lose
  12552. * significance more quickly.
  12553. * @return {Function} a function which can be invoked to create a new
  12554. * playlist selector function.
  12555. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  12556. */
  12557. const movingAverageBandwidthSelector = function (decay) {
  12558. let average = -1;
  12559. let lastSystemBandwidth = -1;
  12560. if (decay < 0 || decay > 1) {
  12561. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  12562. }
  12563. return function () {
  12564. const pixelRatio = this.useDevicePixelRatio ? window$1.devicePixelRatio || 1 : 1;
  12565. if (average < 0) {
  12566. average = this.systemBandwidth;
  12567. lastSystemBandwidth = this.systemBandwidth;
  12568. } // stop the average value from decaying for every 250ms
  12569. // when the systemBandwidth is constant
  12570. // and
  12571. // stop average from setting to a very low value when the
  12572. // systemBandwidth becomes 0 in case of chunk cancellation
  12573. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  12574. average = decay * this.systemBandwidth + (1 - decay) * average;
  12575. lastSystemBandwidth = this.systemBandwidth;
  12576. }
  12577. 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_);
  12578. };
  12579. };
  12580. /**
  12581. * Chooses the appropriate media playlist based on the potential to rebuffer
  12582. *
  12583. * @param {Object} settings
  12584. * Object of information required to use this selector
  12585. * @param {Object} settings.main
  12586. * Object representation of the main manifest
  12587. * @param {number} settings.currentTime
  12588. * The current time of the player
  12589. * @param {number} settings.bandwidth
  12590. * Current measured bandwidth
  12591. * @param {number} settings.duration
  12592. * Duration of the media
  12593. * @param {number} settings.segmentDuration
  12594. * Segment duration to be used in round trip time calculations
  12595. * @param {number} settings.timeUntilRebuffer
  12596. * Time left in seconds until the player has to rebuffer
  12597. * @param {number} settings.currentTimeline
  12598. * The current timeline segments are being loaded from
  12599. * @param {SyncController} settings.syncController
  12600. * SyncController for determining if we have a sync point for a given playlist
  12601. * @return {Object|null}
  12602. * {Object} return.playlist
  12603. * The highest bandwidth playlist with the least amount of rebuffering
  12604. * {Number} return.rebufferingImpact
  12605. * The amount of time in seconds switching to this playlist will rebuffer. A
  12606. * negative value means that switching will cause zero rebuffering.
  12607. */
  12608. const minRebufferMaxBandwidthSelector = function (settings) {
  12609. const {
  12610. main,
  12611. currentTime,
  12612. bandwidth,
  12613. duration,
  12614. segmentDuration,
  12615. timeUntilRebuffer,
  12616. currentTimeline,
  12617. syncController
  12618. } = settings; // filter out any playlists that have been excluded due to
  12619. // incompatible configurations
  12620. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  12621. // api or excluded temporarily due to playback errors.
  12622. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  12623. if (!enabledPlaylists.length) {
  12624. // if there are no enabled playlists, then they have all been excluded or disabled
  12625. // by the user through the representations api. In this case, ignore exclusion and
  12626. // fallback to what the user wants by using playlists the user has not disabled.
  12627. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  12628. }
  12629. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  12630. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  12631. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  12632. // sync request first. This will double the request time
  12633. const numRequests = syncPoint ? 1 : 2;
  12634. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  12635. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  12636. return {
  12637. playlist,
  12638. rebufferingImpact
  12639. };
  12640. });
  12641. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  12642. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  12643. if (noRebufferingPlaylists.length) {
  12644. return noRebufferingPlaylists[0];
  12645. }
  12646. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  12647. return rebufferingEstimates[0] || null;
  12648. };
  12649. /**
  12650. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  12651. * one with video. If no renditions with video exist, return the lowest audio rendition.
  12652. *
  12653. * Expects to be called within the context of an instance of VhsHandler
  12654. *
  12655. * @return {Object|null}
  12656. * {Object} return.playlist
  12657. * The lowest bitrate playlist that contains a video codec. If no such rendition
  12658. * exists pick the lowest audio rendition.
  12659. */
  12660. const lowestBitrateCompatibleVariantSelector = function () {
  12661. // filter out any playlists that have been excluded due to
  12662. // incompatible configurations or playback errors
  12663. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  12664. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  12665. // (this is not necessarily true, although it is generally true).
  12666. //
  12667. // If an entire manifest has no valid videos everything will get filtered
  12668. // out.
  12669. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  12670. return playlistsWithVideo[0] || null;
  12671. };
  12672. /**
  12673. * Combine all segments into a single Uint8Array
  12674. *
  12675. * @param {Object} segmentObj
  12676. * @return {Uint8Array} concatenated bytes
  12677. * @private
  12678. */
  12679. const concatSegments = segmentObj => {
  12680. let offset = 0;
  12681. let tempBuffer;
  12682. if (segmentObj.bytes) {
  12683. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  12684. segmentObj.segments.forEach(segment => {
  12685. tempBuffer.set(segment, offset);
  12686. offset += segment.byteLength;
  12687. });
  12688. }
  12689. return tempBuffer;
  12690. };
  12691. /**
  12692. * @file text-tracks.js
  12693. */
  12694. /**
  12695. * Create captions text tracks on video.js if they do not exist
  12696. *
  12697. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  12698. * @param {Object} tech the video.js tech
  12699. * @param {Object} captionStream the caption stream to create
  12700. * @private
  12701. */
  12702. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  12703. if (!inbandTextTracks[captionStream]) {
  12704. tech.trigger({
  12705. type: 'usage',
  12706. name: 'vhs-608'
  12707. });
  12708. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  12709. if (/^cc708_/.test(captionStream)) {
  12710. instreamId = 'SERVICE' + captionStream.split('_')[1];
  12711. }
  12712. const track = tech.textTracks().getTrackById(instreamId);
  12713. if (track) {
  12714. // Resuse an existing track with a CC# id because this was
  12715. // very likely created by videojs-contrib-hls from information
  12716. // in the m3u8 for us to use
  12717. inbandTextTracks[captionStream] = track;
  12718. } else {
  12719. // This section gets called when we have caption services that aren't specified in the manifest.
  12720. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  12721. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  12722. let label = captionStream;
  12723. let language = captionStream;
  12724. let def = false;
  12725. const captionService = captionServices[instreamId];
  12726. if (captionService) {
  12727. label = captionService.label;
  12728. language = captionService.language;
  12729. def = captionService.default;
  12730. } // Otherwise, create a track with the default `CC#` label and
  12731. // without a language
  12732. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  12733. kind: 'captions',
  12734. id: instreamId,
  12735. // TODO: investigate why this doesn't seem to turn the caption on by default
  12736. default: def,
  12737. label,
  12738. language
  12739. }, false).track;
  12740. }
  12741. }
  12742. };
  12743. /**
  12744. * Add caption text track data to a source handler given an array of captions
  12745. *
  12746. * @param {Object}
  12747. * @param {Object} inbandTextTracks the inband text tracks
  12748. * @param {number} timestampOffset the timestamp offset of the source buffer
  12749. * @param {Array} captionArray an array of caption data
  12750. * @private
  12751. */
  12752. const addCaptionData = function ({
  12753. inbandTextTracks,
  12754. captionArray,
  12755. timestampOffset
  12756. }) {
  12757. if (!captionArray) {
  12758. return;
  12759. }
  12760. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  12761. captionArray.forEach(caption => {
  12762. const track = caption.stream;
  12763. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  12764. });
  12765. };
  12766. /**
  12767. * Define properties on a cue for backwards compatability,
  12768. * but warn the user that the way that they are using it
  12769. * is depricated and will be removed at a later date.
  12770. *
  12771. * @param {Cue} cue the cue to add the properties on
  12772. * @private
  12773. */
  12774. const deprecateOldCue = function (cue) {
  12775. Object.defineProperties(cue.frame, {
  12776. id: {
  12777. get() {
  12778. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  12779. return cue.value.key;
  12780. }
  12781. },
  12782. value: {
  12783. get() {
  12784. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  12785. return cue.value.data;
  12786. }
  12787. },
  12788. privateData: {
  12789. get() {
  12790. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  12791. return cue.value.data;
  12792. }
  12793. }
  12794. });
  12795. };
  12796. /**
  12797. * Add metadata text track data to a source handler given an array of metadata
  12798. *
  12799. * @param {Object}
  12800. * @param {Object} inbandTextTracks the inband text tracks
  12801. * @param {Array} metadataArray an array of meta data
  12802. * @param {number} timestampOffset the timestamp offset of the source buffer
  12803. * @param {number} videoDuration the duration of the video
  12804. * @private
  12805. */
  12806. const addMetadata = ({
  12807. inbandTextTracks,
  12808. metadataArray,
  12809. timestampOffset,
  12810. videoDuration
  12811. }) => {
  12812. if (!metadataArray) {
  12813. return;
  12814. }
  12815. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  12816. const metadataTrack = inbandTextTracks.metadataTrack_;
  12817. if (!metadataTrack) {
  12818. return;
  12819. }
  12820. metadataArray.forEach(metadata => {
  12821. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  12822. // ignore this bit of metadata.
  12823. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  12824. // which is the "Title/Songname/Content description" frame
  12825. if (typeof time !== 'number' || window$1.isNaN(time) || time < 0 || !(time < Infinity)) {
  12826. return;
  12827. }
  12828. metadata.frames.forEach(frame => {
  12829. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  12830. cue.frame = frame;
  12831. cue.value = frame;
  12832. deprecateOldCue(cue);
  12833. metadataTrack.addCue(cue);
  12834. });
  12835. });
  12836. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  12837. return;
  12838. } // Updating the metadeta cues so that
  12839. // the endTime of each cue is the startTime of the next cue
  12840. // the endTime of last cue is the duration of the video
  12841. const cues = metadataTrack.cues;
  12842. const cuesArray = []; // Create a copy of the TextTrackCueList...
  12843. // ...disregarding cues with a falsey value
  12844. for (let i = 0; i < cues.length; i++) {
  12845. if (cues[i]) {
  12846. cuesArray.push(cues[i]);
  12847. }
  12848. } // Group cues by their startTime value
  12849. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  12850. const timeSlot = obj[cue.startTime] || [];
  12851. timeSlot.push(cue);
  12852. obj[cue.startTime] = timeSlot;
  12853. return obj;
  12854. }, {}); // Sort startTimes by ascending order
  12855. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  12856. sortedStartTimes.forEach((startTime, idx) => {
  12857. const cueGroup = cuesGroupedByStartTime[startTime];
  12858. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  12859. cueGroup.forEach(cue => {
  12860. cue.endTime = nextTime;
  12861. });
  12862. });
  12863. };
  12864. /**
  12865. * Create metadata text track on video.js if it does not exist
  12866. *
  12867. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  12868. * @param {string} dispatchType the inband metadata track dispatch type
  12869. * @param {Object} tech the video.js tech
  12870. * @private
  12871. */
  12872. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  12873. if (inbandTextTracks.metadataTrack_) {
  12874. return;
  12875. }
  12876. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  12877. kind: 'metadata',
  12878. label: 'Timed Metadata'
  12879. }, false).track;
  12880. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  12881. };
  12882. /**
  12883. * Remove cues from a track on video.js.
  12884. *
  12885. * @param {Double} start start of where we should remove the cue
  12886. * @param {Double} end end of where the we should remove the cue
  12887. * @param {Object} track the text track to remove the cues from
  12888. * @private
  12889. */
  12890. const removeCuesFromTrack = function (start, end, track) {
  12891. let i;
  12892. let cue;
  12893. if (!track) {
  12894. return;
  12895. }
  12896. if (!track.cues) {
  12897. return;
  12898. }
  12899. i = track.cues.length;
  12900. while (i--) {
  12901. cue = track.cues[i]; // Remove any cue within the provided start and end time
  12902. if (cue.startTime >= start && cue.endTime <= end) {
  12903. track.removeCue(cue);
  12904. }
  12905. }
  12906. };
  12907. /**
  12908. * Remove duplicate cues from a track on video.js (a cue is considered a
  12909. * duplicate if it has the same time interval and text as another)
  12910. *
  12911. * @param {Object} track the text track to remove the duplicate cues from
  12912. * @private
  12913. */
  12914. const removeDuplicateCuesFromTrack = function (track) {
  12915. const cues = track.cues;
  12916. if (!cues) {
  12917. return;
  12918. }
  12919. for (let i = 0; i < cues.length; i++) {
  12920. const duplicates = [];
  12921. let occurrences = 0;
  12922. for (let j = 0; j < cues.length; j++) {
  12923. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  12924. occurrences++;
  12925. if (occurrences > 1) {
  12926. duplicates.push(cues[j]);
  12927. }
  12928. }
  12929. }
  12930. if (duplicates.length) {
  12931. duplicates.forEach(dupe => track.removeCue(dupe));
  12932. }
  12933. }
  12934. };
  12935. /**
  12936. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  12937. * front of current time.
  12938. *
  12939. * @param {Array} buffer
  12940. * The current buffer of gop information
  12941. * @param {number} currentTime
  12942. * The current time
  12943. * @param {Double} mapping
  12944. * Offset to map display time to stream presentation time
  12945. * @return {Array}
  12946. * List of gops considered safe to append over
  12947. */
  12948. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  12949. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  12950. return [];
  12951. } // pts value for current time + 3 seconds to give a bit more wiggle room
  12952. const currentTimePts = Math.ceil((currentTime - mapping + 3) * ONE_SECOND_IN_TS);
  12953. let i;
  12954. for (i = 0; i < buffer.length; i++) {
  12955. if (buffer[i].pts > currentTimePts) {
  12956. break;
  12957. }
  12958. }
  12959. return buffer.slice(i);
  12960. };
  12961. /**
  12962. * Appends gop information (timing and byteLength) received by the transmuxer for the
  12963. * gops appended in the last call to appendBuffer
  12964. *
  12965. * @param {Array} buffer
  12966. * The current buffer of gop information
  12967. * @param {Array} gops
  12968. * List of new gop information
  12969. * @param {boolean} replace
  12970. * If true, replace the buffer with the new gop information. If false, append the
  12971. * new gop information to the buffer in the right location of time.
  12972. * @return {Array}
  12973. * Updated list of gop information
  12974. */
  12975. const updateGopBuffer = (buffer, gops, replace) => {
  12976. if (!gops.length) {
  12977. return buffer;
  12978. }
  12979. if (replace) {
  12980. // If we are in safe append mode, then completely overwrite the gop buffer
  12981. // with the most recent appeneded data. This will make sure that when appending
  12982. // future segments, we only try to align with gops that are both ahead of current
  12983. // time and in the last segment appended.
  12984. return gops.slice();
  12985. }
  12986. const start = gops[0].pts;
  12987. let i = 0;
  12988. for (i; i < buffer.length; i++) {
  12989. if (buffer[i].pts >= start) {
  12990. break;
  12991. }
  12992. }
  12993. return buffer.slice(0, i).concat(gops);
  12994. };
  12995. /**
  12996. * Removes gop information in buffer that overlaps with provided start and end
  12997. *
  12998. * @param {Array} buffer
  12999. * The current buffer of gop information
  13000. * @param {Double} start
  13001. * position to start the remove at
  13002. * @param {Double} end
  13003. * position to end the remove at
  13004. * @param {Double} mapping
  13005. * Offset to map display time to stream presentation time
  13006. */
  13007. const removeGopBuffer = (buffer, start, end, mapping) => {
  13008. const startPts = Math.ceil((start - mapping) * ONE_SECOND_IN_TS);
  13009. const endPts = Math.ceil((end - mapping) * ONE_SECOND_IN_TS);
  13010. const updatedBuffer = buffer.slice();
  13011. let i = buffer.length;
  13012. while (i--) {
  13013. if (buffer[i].pts <= endPts) {
  13014. break;
  13015. }
  13016. }
  13017. if (i === -1) {
  13018. // no removal because end of remove range is before start of buffer
  13019. return updatedBuffer;
  13020. }
  13021. let j = i + 1;
  13022. while (j--) {
  13023. if (buffer[j].pts <= startPts) {
  13024. break;
  13025. }
  13026. } // clamp remove range start to 0 index
  13027. j = Math.max(j, 0);
  13028. updatedBuffer.splice(j, i - j + 1);
  13029. return updatedBuffer;
  13030. };
  13031. const shallowEqual = function (a, b) {
  13032. // if both are undefined
  13033. // or one or the other is undefined
  13034. // they are not equal
  13035. if (!a && !b || !a && b || a && !b) {
  13036. return false;
  13037. } // they are the same object and thus, equal
  13038. if (a === b) {
  13039. return true;
  13040. } // sort keys so we can make sure they have
  13041. // all the same keys later.
  13042. const akeys = Object.keys(a).sort();
  13043. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  13044. if (akeys.length !== bkeys.length) {
  13045. return false;
  13046. }
  13047. for (let i = 0; i < akeys.length; i++) {
  13048. const key = akeys[i]; // different sorted keys, not equal
  13049. if (key !== bkeys[i]) {
  13050. return false;
  13051. } // different values, not equal
  13052. if (a[key] !== b[key]) {
  13053. return false;
  13054. }
  13055. }
  13056. return true;
  13057. };
  13058. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  13059. const QUOTA_EXCEEDED_ERR = 22;
  13060. /**
  13061. * The segment loader has no recourse except to fetch a segment in the
  13062. * current playlist and use the internal timestamps in that segment to
  13063. * generate a syncPoint. This function returns a good candidate index
  13064. * for that process.
  13065. *
  13066. * @param {Array} segments - the segments array from a playlist.
  13067. * @return {number} An index of a segment from the playlist to load
  13068. */
  13069. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  13070. segments = segments || [];
  13071. const timelineSegments = [];
  13072. let time = 0;
  13073. for (let i = 0; i < segments.length; i++) {
  13074. const segment = segments[i];
  13075. if (currentTimeline === segment.timeline) {
  13076. timelineSegments.push(i);
  13077. time += segment.duration;
  13078. if (time > targetTime) {
  13079. return i;
  13080. }
  13081. }
  13082. }
  13083. if (timelineSegments.length === 0) {
  13084. return 0;
  13085. } // default to the last timeline segment
  13086. return timelineSegments[timelineSegments.length - 1];
  13087. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  13088. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  13089. // as a start to prevent any potential issues with removing content too close to the
  13090. // playhead.
  13091. const MIN_BACK_BUFFER = 1; // in ms
  13092. const CHECK_BUFFER_DELAY = 500;
  13093. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  13094. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  13095. // not accurately reflect the rest of the content.
  13096. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  13097. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  13098. // Although these checks should most likely cover non 'main' types, for now it narrows
  13099. // the scope of our checks.
  13100. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  13101. return null;
  13102. }
  13103. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  13104. return 'Neither audio nor video found in segment.';
  13105. }
  13106. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  13107. 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.';
  13108. }
  13109. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  13110. 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.';
  13111. }
  13112. return null;
  13113. };
  13114. /**
  13115. * Calculates a time value that is safe to remove from the back buffer without interrupting
  13116. * playback.
  13117. *
  13118. * @param {TimeRange} seekable
  13119. * The current seekable range
  13120. * @param {number} currentTime
  13121. * The current time of the player
  13122. * @param {number} targetDuration
  13123. * The target duration of the current playlist
  13124. * @return {number}
  13125. * Time that is safe to remove from the back buffer without interrupting playback
  13126. */
  13127. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  13128. // 30 seconds before the playhead provides a safe default for trimming.
  13129. //
  13130. // Choosing a reasonable default is particularly important for high bitrate content and
  13131. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  13132. // throw an APPEND_BUFFER_ERR.
  13133. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  13134. if (seekable.length) {
  13135. // Some live playlists may have a shorter window of content than the full allowed back
  13136. // buffer. For these playlists, don't save content that's no longer within the window.
  13137. trimTime = Math.max(trimTime, seekable.start(0));
  13138. } // Don't remove within target duration of the current time to avoid the possibility of
  13139. // removing the GOP currently being played, as removing it can cause playback stalls.
  13140. const maxTrimTime = currentTime - targetDuration;
  13141. return Math.min(maxTrimTime, trimTime);
  13142. };
  13143. const segmentInfoString = segmentInfo => {
  13144. const {
  13145. startOfSegment,
  13146. duration,
  13147. segment,
  13148. part,
  13149. playlist: {
  13150. mediaSequence: seq,
  13151. id,
  13152. segments = []
  13153. },
  13154. mediaIndex: index,
  13155. partIndex,
  13156. timeline
  13157. } = segmentInfo;
  13158. const segmentLen = segments.length - 1;
  13159. let selection = 'mediaIndex/partIndex increment';
  13160. if (segmentInfo.getMediaInfoForTime) {
  13161. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  13162. } else if (segmentInfo.isSyncRequest) {
  13163. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  13164. }
  13165. if (segmentInfo.independent) {
  13166. selection += ` with independent ${segmentInfo.independent}`;
  13167. }
  13168. const hasPartIndex = typeof partIndex === 'number';
  13169. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  13170. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  13171. preloadSegment: segment
  13172. }) - 1 : 0;
  13173. 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}]`;
  13174. };
  13175. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  13176. /**
  13177. * Returns the timestamp offset to use for the segment.
  13178. *
  13179. * @param {number} segmentTimeline
  13180. * The timeline of the segment
  13181. * @param {number} currentTimeline
  13182. * The timeline currently being followed by the loader
  13183. * @param {number} startOfSegment
  13184. * The estimated segment start
  13185. * @param {TimeRange[]} buffered
  13186. * The loader's buffer
  13187. * @param {boolean} overrideCheck
  13188. * If true, no checks are made to see if the timestamp offset value should be set,
  13189. * but sets it directly to a value.
  13190. *
  13191. * @return {number|null}
  13192. * Either a number representing a new timestamp offset, or null if the segment is
  13193. * part of the same timeline
  13194. */
  13195. const timestampOffsetForSegment = ({
  13196. segmentTimeline,
  13197. currentTimeline,
  13198. startOfSegment,
  13199. buffered,
  13200. overrideCheck
  13201. }) => {
  13202. // Check to see if we are crossing a discontinuity to see if we need to set the
  13203. // timestamp offset on the transmuxer and source buffer.
  13204. //
  13205. // Previously, we changed the timestampOffset if the start of this segment was less than
  13206. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  13207. // behavior, especially around long running live streams.
  13208. if (!overrideCheck && segmentTimeline === currentTimeline) {
  13209. return null;
  13210. } // When changing renditions, it's possible to request a segment on an older timeline. For
  13211. // instance, given two renditions with the following:
  13212. //
  13213. // #EXTINF:10
  13214. // segment1
  13215. // #EXT-X-DISCONTINUITY
  13216. // #EXTINF:10
  13217. // segment2
  13218. // #EXTINF:10
  13219. // segment3
  13220. //
  13221. // And the current player state:
  13222. //
  13223. // current time: 8
  13224. // buffer: 0 => 20
  13225. //
  13226. // The next segment on the current rendition would be segment3, filling the buffer from
  13227. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  13228. // then the next segment to be requested will be segment1 from the new rendition in
  13229. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  13230. // content (since it would position segment1 of the new rendition starting at 20s). This
  13231. // case can be identified when the new segment's timeline is a prior value. Instead of
  13232. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  13233. // more accurate to the actual start time of the segment.
  13234. if (segmentTimeline < currentTimeline) {
  13235. return startOfSegment;
  13236. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  13237. // value uses the end of the last segment if it is available. While this value
  13238. // should often be correct, it's better to rely on the buffered end, as the new
  13239. // content post discontinuity should line up with the buffered end as if it were
  13240. // time 0 for the new content.
  13241. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  13242. };
  13243. /**
  13244. * Returns whether or not the loader should wait for a timeline change from the timeline
  13245. * change controller before processing the segment.
  13246. *
  13247. * Primary timing in VHS goes by video. This is different from most media players, as
  13248. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  13249. * will continue to use video as the primary timing source, due to the current logic and
  13250. * expectations built around it.
  13251. * Since the timing follows video, in order to maintain sync, the video loader is
  13252. * responsible for setting both audio and video source buffer timestamp offsets.
  13253. *
  13254. * Setting different values for audio and video source buffers could lead to
  13255. * desyncing. The following examples demonstrate some of the situations where this
  13256. * distinction is important. Note that all of these cases involve demuxed content. When
  13257. * content is muxed, the audio and video are packaged together, therefore syncing
  13258. * separate media playlists is not an issue.
  13259. *
  13260. * CASE 1: Audio prepares to load a new timeline before video:
  13261. *
  13262. * Timeline: 0 1
  13263. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13264. * Audio Loader: ^
  13265. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13266. * Video Loader ^
  13267. *
  13268. * In the above example, the audio loader is preparing to load the 6th segment, the first
  13269. * after a discontinuity, while the video loader is still loading the 5th segment, before
  13270. * the discontinuity.
  13271. *
  13272. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  13273. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  13274. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  13275. * the audio loader must provide the audioAppendStart value to trim the content in the
  13276. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  13277. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  13278. * segment until that value is provided.
  13279. *
  13280. * CASE 2: Video prepares to load a new timeline before audio:
  13281. *
  13282. * Timeline: 0 1
  13283. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13284. * Audio Loader: ^
  13285. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13286. * Video Loader ^
  13287. *
  13288. * In the above example, the video loader is preparing to load the 6th segment, the first
  13289. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  13290. * the discontinuity.
  13291. *
  13292. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  13293. * segment is loaded and processed, both the video and audio timestamp offsets will be
  13294. * set, since video is used as the primary timing source. This is to ensure content lines
  13295. * up appropriately, as any modifications to the video timing are reflected by audio when
  13296. * the video loader sets the audio and video timestamp offsets to the same value. However,
  13297. * setting the timestamp offset for audio before audio has had a chance to change
  13298. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  13299. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  13300. *
  13301. * CASE 3: When seeking, audio prepares to load a new timeline before video
  13302. *
  13303. * Timeline: 0 1
  13304. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13305. * Audio Loader: ^
  13306. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13307. * Video Loader ^
  13308. *
  13309. * In the above example, both audio and video loaders are loading segments from timeline
  13310. * 0, but imagine that the seek originated from timeline 1.
  13311. *
  13312. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  13313. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  13314. * must wait for the video loader to load its segment and update both the audio and video
  13315. * timestamp offsets before it may load and append its own segment. This is the case
  13316. * whether the seek results in a mismatched segment request (e.g., the audio loader
  13317. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  13318. * loaders choose to load the same segment index from each playlist, as the segments may
  13319. * not be aligned perfectly, even for matching segment indexes.
  13320. *
  13321. * @param {Object} timelinechangeController
  13322. * @param {number} currentTimeline
  13323. * The timeline currently being followed by the loader
  13324. * @param {number} segmentTimeline
  13325. * The timeline of the segment being loaded
  13326. * @param {('main'|'audio')} loaderType
  13327. * The loader type
  13328. * @param {boolean} audioDisabled
  13329. * Whether the audio is disabled for the loader. This should only be true when the
  13330. * loader may have muxed audio in its segment, but should not append it, e.g., for
  13331. * the main loader when an alternate audio playlist is active.
  13332. *
  13333. * @return {boolean}
  13334. * Whether the loader should wait for a timeline change from the timeline change
  13335. * controller before processing the segment
  13336. */
  13337. const shouldWaitForTimelineChange = ({
  13338. timelineChangeController,
  13339. currentTimeline,
  13340. segmentTimeline,
  13341. loaderType,
  13342. audioDisabled
  13343. }) => {
  13344. if (currentTimeline === segmentTimeline) {
  13345. return false;
  13346. }
  13347. if (loaderType === 'audio') {
  13348. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  13349. type: 'main'
  13350. }); // Audio loader should wait if:
  13351. //
  13352. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  13353. // * main hasn't yet changed to the timeline audio is looking to load
  13354. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  13355. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  13356. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  13357. // loader's segments (or the content is audio/video only and handled by the main
  13358. // loader).
  13359. if (loaderType === 'main' && audioDisabled) {
  13360. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  13361. type: 'audio'
  13362. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  13363. // change to the current timeline.
  13364. //
  13365. // Since the main loader is responsible for setting the timestamp offset for both
  13366. // audio and video, the main loader must wait for audio to be about to change to its
  13367. // timeline before setting the offset, otherwise, if audio is behind in loading,
  13368. // segments from the previous timeline would be adjusted by the new timestamp offset.
  13369. //
  13370. // This requirement means that video will not cross a timeline until the audio is
  13371. // about to cross to it, so that way audio and video will always cross the timeline
  13372. // together.
  13373. //
  13374. // In addition to normal timeline changes, these rules also apply to the start of a
  13375. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  13376. // that these rules apply to the first timeline change because if they did not, it's
  13377. // possible that the main loader will cross two timelines before the audio loader has
  13378. // crossed one. Logic may be implemented to handle the startup as a special case, but
  13379. // it's easier to simply treat all timeline changes the same.
  13380. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  13381. return false;
  13382. }
  13383. return true;
  13384. }
  13385. return false;
  13386. };
  13387. const mediaDuration = timingInfos => {
  13388. let maxDuration = 0;
  13389. ['video', 'audio'].forEach(function (type) {
  13390. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  13391. if (!typeTimingInfo) {
  13392. return;
  13393. }
  13394. const {
  13395. start,
  13396. end
  13397. } = typeTimingInfo;
  13398. let duration;
  13399. if (typeof start === 'bigint' || typeof end === 'bigint') {
  13400. duration = window$1.BigInt(end) - window$1.BigInt(start);
  13401. } else if (typeof start === 'number' && typeof end === 'number') {
  13402. duration = end - start;
  13403. }
  13404. if (typeof duration !== 'undefined' && duration > maxDuration) {
  13405. maxDuration = duration;
  13406. }
  13407. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  13408. // as we only need BigInt when we are above that.
  13409. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  13410. maxDuration = Number(maxDuration);
  13411. }
  13412. return maxDuration;
  13413. };
  13414. const segmentTooLong = ({
  13415. segmentDuration,
  13416. maxDuration
  13417. }) => {
  13418. // 0 duration segments are most likely due to metadata only segments or a lack of
  13419. // information.
  13420. if (!segmentDuration) {
  13421. return false;
  13422. } // For HLS:
  13423. //
  13424. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  13425. // The EXTINF duration of each Media Segment in the Playlist
  13426. // file, when rounded to the nearest integer, MUST be less than or equal
  13427. // to the target duration; longer segments can trigger playback stalls
  13428. // or other errors.
  13429. //
  13430. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  13431. // duration. Although that reported duration is occasionally approximate (i.e., not
  13432. // exact), a strict check may report that a segment is too long more often in DASH.
  13433. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  13434. };
  13435. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  13436. // Right now we aren't following DASH's timing model exactly, so only perform
  13437. // this check for HLS content.
  13438. if (sourceType !== 'hls') {
  13439. return null;
  13440. }
  13441. const segmentDuration = mediaDuration({
  13442. audioTimingInfo: segmentInfo.audioTimingInfo,
  13443. videoTimingInfo: segmentInfo.videoTimingInfo
  13444. }); // Don't report if we lack information.
  13445. //
  13446. // If the segment has a duration of 0 it is either a lack of information or a
  13447. // metadata only segment and shouldn't be reported here.
  13448. if (!segmentDuration) {
  13449. return null;
  13450. }
  13451. const targetDuration = segmentInfo.playlist.targetDuration;
  13452. const isSegmentWayTooLong = segmentTooLong({
  13453. segmentDuration,
  13454. maxDuration: targetDuration * 2
  13455. });
  13456. const isSegmentSlightlyTooLong = segmentTooLong({
  13457. segmentDuration,
  13458. maxDuration: targetDuration
  13459. });
  13460. 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';
  13461. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  13462. return {
  13463. severity: isSegmentWayTooLong ? 'warn' : 'info',
  13464. message: segmentTooLongMessage
  13465. };
  13466. }
  13467. return null;
  13468. };
  13469. /**
  13470. * An object that manages segment loading and appending.
  13471. *
  13472. * @class SegmentLoader
  13473. * @param {Object} options required and optional options
  13474. * @extends videojs.EventTarget
  13475. */
  13476. class SegmentLoader extends videojs.EventTarget {
  13477. constructor(settings, options = {}) {
  13478. super(); // check pre-conditions
  13479. if (!settings) {
  13480. throw new TypeError('Initialization settings are required');
  13481. }
  13482. if (typeof settings.currentTime !== 'function') {
  13483. throw new TypeError('No currentTime getter specified');
  13484. }
  13485. if (!settings.mediaSource) {
  13486. throw new TypeError('No MediaSource specified');
  13487. } // public properties
  13488. this.bandwidth = settings.bandwidth;
  13489. this.throughput = {
  13490. rate: 0,
  13491. count: 0
  13492. };
  13493. this.roundTrip = NaN;
  13494. this.resetStats_();
  13495. this.mediaIndex = null;
  13496. this.partIndex = null; // private settings
  13497. this.hasPlayed_ = settings.hasPlayed;
  13498. this.currentTime_ = settings.currentTime;
  13499. this.seekable_ = settings.seekable;
  13500. this.seeking_ = settings.seeking;
  13501. this.duration_ = settings.duration;
  13502. this.mediaSource_ = settings.mediaSource;
  13503. this.vhs_ = settings.vhs;
  13504. this.loaderType_ = settings.loaderType;
  13505. this.currentMediaInfo_ = void 0;
  13506. this.startingMediaInfo_ = void 0;
  13507. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  13508. this.goalBufferLength_ = settings.goalBufferLength;
  13509. this.sourceType_ = settings.sourceType;
  13510. this.sourceUpdater_ = settings.sourceUpdater;
  13511. this.inbandTextTracks_ = settings.inbandTextTracks;
  13512. this.state_ = 'INIT';
  13513. this.timelineChangeController_ = settings.timelineChangeController;
  13514. this.shouldSaveSegmentTimingInfo_ = true;
  13515. this.parse708captions_ = settings.parse708captions;
  13516. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  13517. this.captionServices_ = settings.captionServices;
  13518. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  13519. this.checkBufferTimeout_ = null;
  13520. this.error_ = void 0;
  13521. this.currentTimeline_ = -1;
  13522. this.pendingSegment_ = null;
  13523. this.xhrOptions_ = null;
  13524. this.pendingSegments_ = [];
  13525. this.audioDisabled_ = false;
  13526. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  13527. this.gopBuffer_ = [];
  13528. this.timeMapping_ = 0;
  13529. this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  13530. this.appendInitSegment_ = {
  13531. audio: true,
  13532. video: true
  13533. };
  13534. this.playlistOfLastInitSegment_ = {
  13535. audio: null,
  13536. video: null
  13537. };
  13538. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  13539. // information yet to start the loading process (e.g., if the audio loader wants to
  13540. // load a segment from the next timeline but the main loader hasn't yet crossed that
  13541. // timeline), then the load call will be added to the queue until it is ready to be
  13542. // processed.
  13543. this.loadQueue_ = [];
  13544. this.metadataQueue_ = {
  13545. id3: [],
  13546. caption: []
  13547. };
  13548. this.waitingOnRemove_ = false;
  13549. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  13550. this.activeInitSegmentId_ = null;
  13551. this.initSegments_ = {}; // HLSe playback
  13552. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  13553. this.keyCache_ = {};
  13554. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  13555. // between a time in the display time and a segment index within
  13556. // a playlist
  13557. this.syncController_ = settings.syncController;
  13558. this.syncPoint_ = {
  13559. segmentIndex: 0,
  13560. time: 0
  13561. };
  13562. this.transmuxer_ = this.createTransmuxer_();
  13563. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  13564. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  13565. this.mediaSource_.addEventListener('sourceopen', () => {
  13566. if (!this.isEndOfStream_()) {
  13567. this.ended_ = false;
  13568. }
  13569. }); // ...for determining the fetch location
  13570. this.fetchAtBuffer_ = false;
  13571. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  13572. Object.defineProperty(this, 'state', {
  13573. get() {
  13574. return this.state_;
  13575. },
  13576. set(newState) {
  13577. if (newState !== this.state_) {
  13578. this.logger_(`${this.state_} -> ${newState}`);
  13579. this.state_ = newState;
  13580. this.trigger('statechange');
  13581. }
  13582. }
  13583. });
  13584. this.sourceUpdater_.on('ready', () => {
  13585. if (this.hasEnoughInfoToAppend_()) {
  13586. this.processCallQueue_();
  13587. }
  13588. }); // Only the main loader needs to listen for pending timeline changes, as the main
  13589. // loader should wait for audio to be ready to change its timeline so that both main
  13590. // and audio timelines change together. For more details, see the
  13591. // shouldWaitForTimelineChange function.
  13592. if (this.loaderType_ === 'main') {
  13593. this.timelineChangeController_.on('pendingtimelinechange', () => {
  13594. if (this.hasEnoughInfoToAppend_()) {
  13595. this.processCallQueue_();
  13596. }
  13597. });
  13598. } // The main loader only listens on pending timeline changes, but the audio loader,
  13599. // since its loads follow main, needs to listen on timeline changes. For more details,
  13600. // see the shouldWaitForTimelineChange function.
  13601. if (this.loaderType_ === 'audio') {
  13602. this.timelineChangeController_.on('timelinechange', () => {
  13603. if (this.hasEnoughInfoToLoad_()) {
  13604. this.processLoadQueue_();
  13605. }
  13606. if (this.hasEnoughInfoToAppend_()) {
  13607. this.processCallQueue_();
  13608. }
  13609. });
  13610. }
  13611. }
  13612. createTransmuxer_() {
  13613. return segmentTransmuxer.createTransmuxer({
  13614. remux: false,
  13615. alignGopsAtEnd: this.safeAppend_,
  13616. keepOriginalTimestamps: true,
  13617. parse708captions: this.parse708captions_,
  13618. captionServices: this.captionServices_
  13619. });
  13620. }
  13621. /**
  13622. * reset all of our media stats
  13623. *
  13624. * @private
  13625. */
  13626. resetStats_() {
  13627. this.mediaBytesTransferred = 0;
  13628. this.mediaRequests = 0;
  13629. this.mediaRequestsAborted = 0;
  13630. this.mediaRequestsTimedout = 0;
  13631. this.mediaRequestsErrored = 0;
  13632. this.mediaTransferDuration = 0;
  13633. this.mediaSecondsLoaded = 0;
  13634. this.mediaAppends = 0;
  13635. }
  13636. /**
  13637. * dispose of the SegmentLoader and reset to the default state
  13638. */
  13639. dispose() {
  13640. this.trigger('dispose');
  13641. this.state = 'DISPOSED';
  13642. this.pause();
  13643. this.abort_();
  13644. if (this.transmuxer_) {
  13645. this.transmuxer_.terminate();
  13646. }
  13647. this.resetStats_();
  13648. if (this.checkBufferTimeout_) {
  13649. window$1.clearTimeout(this.checkBufferTimeout_);
  13650. }
  13651. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  13652. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  13653. }
  13654. this.off();
  13655. }
  13656. setAudio(enable) {
  13657. this.audioDisabled_ = !enable;
  13658. if (enable) {
  13659. this.appendInitSegment_.audio = true;
  13660. } else {
  13661. // remove current track audio if it gets disabled
  13662. this.sourceUpdater_.removeAudio(0, this.duration_());
  13663. }
  13664. }
  13665. /**
  13666. * abort anything that is currently doing on with the SegmentLoader
  13667. * and reset to a default state
  13668. */
  13669. abort() {
  13670. if (this.state !== 'WAITING') {
  13671. if (this.pendingSegment_) {
  13672. this.pendingSegment_ = null;
  13673. }
  13674. return;
  13675. }
  13676. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  13677. // since we are no longer "waiting" on any requests. XHR callback is not always run
  13678. // when the request is aborted. This will prevent the loader from being stuck in the
  13679. // WAITING state indefinitely.
  13680. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  13681. // next segment
  13682. if (!this.paused()) {
  13683. this.monitorBuffer_();
  13684. }
  13685. }
  13686. /**
  13687. * abort all pending xhr requests and null any pending segements
  13688. *
  13689. * @private
  13690. */
  13691. abort_() {
  13692. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  13693. this.pendingSegment_.abortRequests();
  13694. } // clear out the segment being processed
  13695. this.pendingSegment_ = null;
  13696. this.callQueue_ = [];
  13697. this.loadQueue_ = [];
  13698. this.metadataQueue_.id3 = [];
  13699. this.metadataQueue_.caption = [];
  13700. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  13701. this.waitingOnRemove_ = false;
  13702. window$1.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  13703. this.quotaExceededErrorRetryTimeout_ = null;
  13704. }
  13705. checkForAbort_(requestId) {
  13706. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  13707. // callback that happens should reset the state to READY so that loading can continue.
  13708. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  13709. this.state = 'READY';
  13710. return true;
  13711. }
  13712. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  13713. return true;
  13714. }
  13715. return false;
  13716. }
  13717. /**
  13718. * set an error on the segment loader and null out any pending segements
  13719. *
  13720. * @param {Error} error the error to set on the SegmentLoader
  13721. * @return {Error} the error that was set or that is currently set
  13722. */
  13723. error(error) {
  13724. if (typeof error !== 'undefined') {
  13725. this.logger_('error occurred:', error);
  13726. this.error_ = error;
  13727. }
  13728. this.pendingSegment_ = null;
  13729. return this.error_;
  13730. }
  13731. endOfStream() {
  13732. this.ended_ = true;
  13733. if (this.transmuxer_) {
  13734. // need to clear out any cached data to prepare for the new segment
  13735. segmentTransmuxer.reset(this.transmuxer_);
  13736. }
  13737. this.gopBuffer_.length = 0;
  13738. this.pause();
  13739. this.trigger('ended');
  13740. }
  13741. /**
  13742. * Indicates which time ranges are buffered
  13743. *
  13744. * @return {TimeRange}
  13745. * TimeRange object representing the current buffered ranges
  13746. */
  13747. buffered_() {
  13748. const trackInfo = this.getMediaInfo_();
  13749. if (!this.sourceUpdater_ || !trackInfo) {
  13750. return createTimeRanges();
  13751. }
  13752. if (this.loaderType_ === 'main') {
  13753. const {
  13754. hasAudio,
  13755. hasVideo,
  13756. isMuxed
  13757. } = trackInfo;
  13758. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  13759. return this.sourceUpdater_.buffered();
  13760. }
  13761. if (hasVideo) {
  13762. return this.sourceUpdater_.videoBuffered();
  13763. }
  13764. } // One case that can be ignored for now is audio only with alt audio,
  13765. // as we don't yet have proper support for that.
  13766. return this.sourceUpdater_.audioBuffered();
  13767. }
  13768. /**
  13769. * Gets and sets init segment for the provided map
  13770. *
  13771. * @param {Object} map
  13772. * The map object representing the init segment to get or set
  13773. * @param {boolean=} set
  13774. * If true, the init segment for the provided map should be saved
  13775. * @return {Object}
  13776. * map object for desired init segment
  13777. */
  13778. initSegmentForMap(map, set = false) {
  13779. if (!map) {
  13780. return null;
  13781. }
  13782. const id = initSegmentId(map);
  13783. let storedMap = this.initSegments_[id];
  13784. if (set && !storedMap && map.bytes) {
  13785. this.initSegments_[id] = storedMap = {
  13786. resolvedUri: map.resolvedUri,
  13787. byterange: map.byterange,
  13788. bytes: map.bytes,
  13789. tracks: map.tracks,
  13790. timescales: map.timescales
  13791. };
  13792. }
  13793. return storedMap || map;
  13794. }
  13795. /**
  13796. * Gets and sets key for the provided key
  13797. *
  13798. * @param {Object} key
  13799. * The key object representing the key to get or set
  13800. * @param {boolean=} set
  13801. * If true, the key for the provided key should be saved
  13802. * @return {Object}
  13803. * Key object for desired key
  13804. */
  13805. segmentKey(key, set = false) {
  13806. if (!key) {
  13807. return null;
  13808. }
  13809. const id = segmentKeyId(key);
  13810. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  13811. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  13812. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  13813. this.keyCache_[id] = storedKey = {
  13814. resolvedUri: key.resolvedUri,
  13815. bytes: key.bytes
  13816. };
  13817. }
  13818. const result = {
  13819. resolvedUri: (storedKey || key).resolvedUri
  13820. };
  13821. if (storedKey) {
  13822. result.bytes = storedKey.bytes;
  13823. }
  13824. return result;
  13825. }
  13826. /**
  13827. * Returns true if all configuration required for loading is present, otherwise false.
  13828. *
  13829. * @return {boolean} True if the all configuration is ready for loading
  13830. * @private
  13831. */
  13832. couldBeginLoading_() {
  13833. return this.playlist_ && !this.paused();
  13834. }
  13835. /**
  13836. * load a playlist and start to fill the buffer
  13837. */
  13838. load() {
  13839. // un-pause
  13840. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  13841. // specified
  13842. if (!this.playlist_) {
  13843. return;
  13844. } // if all the configuration is ready, initialize and begin loading
  13845. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  13846. return this.init_();
  13847. } // if we're in the middle of processing a segment already, don't
  13848. // kick off an additional segment request
  13849. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  13850. return;
  13851. }
  13852. this.state = 'READY';
  13853. }
  13854. /**
  13855. * Once all the starting parameters have been specified, begin
  13856. * operation. This method should only be invoked from the INIT
  13857. * state.
  13858. *
  13859. * @private
  13860. */
  13861. init_() {
  13862. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  13863. // audio data from the muxed content should be removed
  13864. this.resetEverything();
  13865. return this.monitorBuffer_();
  13866. }
  13867. /**
  13868. * set a playlist on the segment loader
  13869. *
  13870. * @param {PlaylistLoader} media the playlist to set on the segment loader
  13871. */
  13872. playlist(newPlaylist, options = {}) {
  13873. if (!newPlaylist) {
  13874. return;
  13875. }
  13876. const oldPlaylist = this.playlist_;
  13877. const segmentInfo = this.pendingSegment_;
  13878. this.playlist_ = newPlaylist;
  13879. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  13880. // is always our zero-time so force a sync update each time the playlist
  13881. // is refreshed from the server
  13882. //
  13883. // Use the INIT state to determine if playback has started, as the playlist sync info
  13884. // should be fixed once requests begin (as sync points are generated based on sync
  13885. // info), but not before then.
  13886. if (this.state === 'INIT') {
  13887. newPlaylist.syncInfo = {
  13888. mediaSequence: newPlaylist.mediaSequence,
  13889. time: 0
  13890. }; // Setting the date time mapping means mapping the program date time (if available)
  13891. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  13892. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  13893. // be updated as the playlist is refreshed before the loader starts loading, the
  13894. // program date time mapping needs to be updated as well.
  13895. //
  13896. // This mapping is only done for the main loader because a program date time should
  13897. // map equivalently between playlists.
  13898. if (this.loaderType_ === 'main') {
  13899. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  13900. }
  13901. }
  13902. let oldId = null;
  13903. if (oldPlaylist) {
  13904. if (oldPlaylist.id) {
  13905. oldId = oldPlaylist.id;
  13906. } else if (oldPlaylist.uri) {
  13907. oldId = oldPlaylist.uri;
  13908. }
  13909. }
  13910. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  13911. // in LIVE, we always want to update with new playlists (including refreshes)
  13912. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  13913. // buffering now
  13914. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  13915. return this.init_();
  13916. }
  13917. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  13918. if (this.mediaIndex !== null) {
  13919. // we must reset/resync the segment loader when we switch renditions and
  13920. // the segment loader is already synced to the previous rendition
  13921. // on playlist changes we want it to be possible to fetch
  13922. // at the buffer for vod but not for live. So we use resetLoader
  13923. // for live and resyncLoader for vod. We want this because
  13924. // if a playlist uses independent and non-independent segments/parts the
  13925. // buffer may not accurately reflect the next segment that we should try
  13926. // downloading.
  13927. if (!newPlaylist.endList) {
  13928. this.resetLoader();
  13929. } else {
  13930. this.resyncLoader();
  13931. }
  13932. }
  13933. this.currentMediaInfo_ = void 0;
  13934. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  13935. return;
  13936. } // we reloaded the same playlist so we are in a live scenario
  13937. // and we will likely need to adjust the mediaIndex
  13938. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  13939. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  13940. // this is important because we can abort a request and this value must be
  13941. // equal to the last appended mediaIndex
  13942. if (this.mediaIndex !== null) {
  13943. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  13944. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  13945. // new playlist was incremented by 1.
  13946. if (this.mediaIndex < 0) {
  13947. this.mediaIndex = null;
  13948. this.partIndex = null;
  13949. } else {
  13950. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  13951. // unless parts fell off of the playlist for this segment.
  13952. // In that case we need to reset partIndex and resync
  13953. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  13954. const mediaIndex = this.mediaIndex;
  13955. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  13956. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  13957. // as the part was dropped from our current playlists segment.
  13958. // The mediaIndex will still be valid so keep that around.
  13959. this.mediaIndex = mediaIndex;
  13960. }
  13961. }
  13962. } // update the mediaIndex on the SegmentInfo object
  13963. // this is important because we will update this.mediaIndex with this value
  13964. // in `handleAppendsDone_` after the segment has been successfully appended
  13965. if (segmentInfo) {
  13966. segmentInfo.mediaIndex -= mediaSequenceDiff;
  13967. if (segmentInfo.mediaIndex < 0) {
  13968. segmentInfo.mediaIndex = null;
  13969. segmentInfo.partIndex = null;
  13970. } else {
  13971. // we need to update the referenced segment so that timing information is
  13972. // saved for the new playlist's segment, however, if the segment fell off the
  13973. // playlist, we can leave the old reference and just lose the timing info
  13974. if (segmentInfo.mediaIndex >= 0) {
  13975. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  13976. }
  13977. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  13978. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  13979. }
  13980. }
  13981. }
  13982. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  13983. }
  13984. /**
  13985. * Prevent the loader from fetching additional segments. If there
  13986. * is a segment request outstanding, it will finish processing
  13987. * before the loader halts. A segment loader can be unpaused by
  13988. * calling load().
  13989. */
  13990. pause() {
  13991. if (this.checkBufferTimeout_) {
  13992. window$1.clearTimeout(this.checkBufferTimeout_);
  13993. this.checkBufferTimeout_ = null;
  13994. }
  13995. }
  13996. /**
  13997. * Returns whether the segment loader is fetching additional
  13998. * segments when given the opportunity. This property can be
  13999. * modified through calls to pause() and load().
  14000. */
  14001. paused() {
  14002. return this.checkBufferTimeout_ === null;
  14003. }
  14004. /**
  14005. * Delete all the buffered data and reset the SegmentLoader
  14006. *
  14007. * @param {Function} [done] an optional callback to be executed when the remove
  14008. * operation is complete
  14009. */
  14010. resetEverything(done) {
  14011. this.ended_ = false;
  14012. this.activeInitSegmentId_ = null;
  14013. this.appendInitSegment_ = {
  14014. audio: true,
  14015. video: true
  14016. };
  14017. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  14018. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  14019. // we then clamp the value to duration if necessary.
  14020. this.remove(0, Infinity, done); // clears fmp4 captions
  14021. if (this.transmuxer_) {
  14022. this.transmuxer_.postMessage({
  14023. action: 'clearAllMp4Captions'
  14024. }); // reset the cache in the transmuxer
  14025. this.transmuxer_.postMessage({
  14026. action: 'reset'
  14027. });
  14028. }
  14029. }
  14030. /**
  14031. * Force the SegmentLoader to resync and start loading around the currentTime instead
  14032. * of starting at the end of the buffer
  14033. *
  14034. * Useful for fast quality changes
  14035. */
  14036. resetLoader() {
  14037. this.fetchAtBuffer_ = false;
  14038. this.resyncLoader();
  14039. }
  14040. /**
  14041. * Force the SegmentLoader to restart synchronization and make a conservative guess
  14042. * before returning to the simple walk-forward method
  14043. */
  14044. resyncLoader() {
  14045. if (this.transmuxer_) {
  14046. // need to clear out any cached data to prepare for the new segment
  14047. segmentTransmuxer.reset(this.transmuxer_);
  14048. }
  14049. this.mediaIndex = null;
  14050. this.partIndex = null;
  14051. this.syncPoint_ = null;
  14052. this.isPendingTimestampOffset_ = false;
  14053. this.callQueue_ = [];
  14054. this.loadQueue_ = [];
  14055. this.metadataQueue_.id3 = [];
  14056. this.metadataQueue_.caption = [];
  14057. this.abort();
  14058. if (this.transmuxer_) {
  14059. this.transmuxer_.postMessage({
  14060. action: 'clearParsedMp4Captions'
  14061. });
  14062. }
  14063. }
  14064. /**
  14065. * Remove any data in the source buffer between start and end times
  14066. *
  14067. * @param {number} start - the start time of the region to remove from the buffer
  14068. * @param {number} end - the end time of the region to remove from the buffer
  14069. * @param {Function} [done] - an optional callback to be executed when the remove
  14070. * @param {boolean} force - force all remove operations to happen
  14071. * operation is complete
  14072. */
  14073. remove(start, end, done = () => {}, force = false) {
  14074. // clamp end to duration if we need to remove everything.
  14075. // This is due to a browser bug that causes issues if we remove to Infinity.
  14076. // videojs/videojs-contrib-hls#1225
  14077. if (end === Infinity) {
  14078. end = this.duration_();
  14079. } // skip removes that would throw an error
  14080. // commonly happens during a rendition switch at the start of a video
  14081. // from start 0 to end 0
  14082. if (end <= start) {
  14083. this.logger_('skipping remove because end ${end} is <= start ${start}');
  14084. return;
  14085. }
  14086. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  14087. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  14088. return;
  14089. } // set it to one to complete this function's removes
  14090. let removesRemaining = 1;
  14091. const removeFinished = () => {
  14092. removesRemaining--;
  14093. if (removesRemaining === 0) {
  14094. done();
  14095. }
  14096. };
  14097. if (force || !this.audioDisabled_) {
  14098. removesRemaining++;
  14099. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  14100. } // While it would be better to only remove video if the main loader has video, this
  14101. // should be safe with audio only as removeVideo will call back even if there's no
  14102. // video buffer.
  14103. //
  14104. // In theory we can check to see if there's video before calling the remove, but in
  14105. // the event that we're switching between renditions and from video to audio only
  14106. // (when we add support for that), we may need to clear the video contents despite
  14107. // what the new media will contain.
  14108. if (force || this.loaderType_ === 'main') {
  14109. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  14110. removesRemaining++;
  14111. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  14112. } // remove any captions and ID3 tags
  14113. for (const track in this.inbandTextTracks_) {
  14114. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  14115. }
  14116. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  14117. removeFinished();
  14118. }
  14119. /**
  14120. * (re-)schedule monitorBufferTick_ to run as soon as possible
  14121. *
  14122. * @private
  14123. */
  14124. monitorBuffer_() {
  14125. if (this.checkBufferTimeout_) {
  14126. window$1.clearTimeout(this.checkBufferTimeout_);
  14127. }
  14128. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), 1);
  14129. }
  14130. /**
  14131. * As long as the SegmentLoader is in the READY state, periodically
  14132. * invoke fillBuffer_().
  14133. *
  14134. * @private
  14135. */
  14136. monitorBufferTick_() {
  14137. if (this.state === 'READY') {
  14138. this.fillBuffer_();
  14139. }
  14140. if (this.checkBufferTimeout_) {
  14141. window$1.clearTimeout(this.checkBufferTimeout_);
  14142. }
  14143. this.checkBufferTimeout_ = window$1.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  14144. }
  14145. /**
  14146. * fill the buffer with segements unless the sourceBuffers are
  14147. * currently updating
  14148. *
  14149. * Note: this function should only ever be called by monitorBuffer_
  14150. * and never directly
  14151. *
  14152. * @private
  14153. */
  14154. fillBuffer_() {
  14155. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  14156. // except when we're ready for the next segment, this check can most likely be removed
  14157. if (this.sourceUpdater_.updating()) {
  14158. return;
  14159. } // see if we need to begin loading immediately
  14160. const segmentInfo = this.chooseNextRequest_();
  14161. if (!segmentInfo) {
  14162. return;
  14163. }
  14164. if (typeof segmentInfo.timestampOffset === 'number') {
  14165. this.isPendingTimestampOffset_ = false;
  14166. this.timelineChangeController_.pendingTimelineChange({
  14167. type: this.loaderType_,
  14168. from: this.currentTimeline_,
  14169. to: segmentInfo.timeline
  14170. });
  14171. }
  14172. this.loadSegment_(segmentInfo);
  14173. }
  14174. /**
  14175. * Determines if we should call endOfStream on the media source based
  14176. * on the state of the buffer or if appened segment was the final
  14177. * segment in the playlist.
  14178. *
  14179. * @param {number} [mediaIndex] the media index of segment we last appended
  14180. * @param {Object} [playlist] a media playlist object
  14181. * @return {boolean} do we need to call endOfStream on the MediaSource
  14182. */
  14183. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  14184. if (!playlist || !this.mediaSource_) {
  14185. return false;
  14186. }
  14187. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  14188. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  14189. 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
  14190. // so that MediaSources can trigger the `ended` event when it runs out of
  14191. // buffered data instead of waiting for me
  14192. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  14193. }
  14194. /**
  14195. * Determines what request should be made given current segment loader state.
  14196. *
  14197. * @return {Object} a request object that describes the segment/part to load
  14198. */
  14199. chooseNextRequest_() {
  14200. const buffered = this.buffered_();
  14201. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  14202. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  14203. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  14204. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  14205. const segments = this.playlist_.segments; // return no segment if:
  14206. // 1. we don't have segments
  14207. // 2. The video has not yet played and we already downloaded a segment
  14208. // 3. we already have enough buffered time
  14209. if (!segments.length || preloaded || haveEnoughBuffer) {
  14210. return null;
  14211. }
  14212. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  14213. const next = {
  14214. partIndex: null,
  14215. mediaIndex: null,
  14216. startOfSegment: null,
  14217. playlist: this.playlist_,
  14218. isSyncRequest: Boolean(!this.syncPoint_)
  14219. };
  14220. if (next.isSyncRequest) {
  14221. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  14222. } else if (this.mediaIndex !== null) {
  14223. const segment = segments[this.mediaIndex];
  14224. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  14225. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  14226. if (segment.parts && segment.parts[partIndex + 1]) {
  14227. next.mediaIndex = this.mediaIndex;
  14228. next.partIndex = partIndex + 1;
  14229. } else {
  14230. next.mediaIndex = this.mediaIndex + 1;
  14231. }
  14232. } else {
  14233. // Find the segment containing the end of the buffer or current time.
  14234. const {
  14235. segmentIndex,
  14236. startTime,
  14237. partIndex
  14238. } = Playlist.getMediaInfoForTime({
  14239. exactManifestTimings: this.exactManifestTimings,
  14240. playlist: this.playlist_,
  14241. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  14242. startingPartIndex: this.syncPoint_.partIndex,
  14243. startingSegmentIndex: this.syncPoint_.segmentIndex,
  14244. startTime: this.syncPoint_.time
  14245. });
  14246. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  14247. next.mediaIndex = segmentIndex;
  14248. next.startOfSegment = startTime;
  14249. next.partIndex = partIndex;
  14250. }
  14251. const nextSegment = segments[next.mediaIndex];
  14252. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  14253. // the next partIndex is invalid do not choose a next segment.
  14254. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  14255. return null;
  14256. } // if the next segment has parts, and we don't have a partIndex.
  14257. // Set partIndex to 0
  14258. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  14259. next.partIndex = 0;
  14260. nextPart = nextSegment.parts[0];
  14261. } // if we have no buffered data then we need to make sure
  14262. // that the next part we append is "independent" if possible.
  14263. // So we check if the previous part is independent, and request
  14264. // it if it is.
  14265. if (!bufferedTime && nextPart && !nextPart.independent) {
  14266. if (next.partIndex === 0) {
  14267. const lastSegment = segments[next.mediaIndex - 1];
  14268. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  14269. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  14270. next.mediaIndex -= 1;
  14271. next.partIndex = lastSegment.parts.length - 1;
  14272. next.independent = 'previous segment';
  14273. }
  14274. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  14275. next.partIndex -= 1;
  14276. next.independent = 'previous part';
  14277. }
  14278. }
  14279. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  14280. // 1. this is the last segment in the playlist
  14281. // 2. end of stream has been called on the media source already
  14282. // 3. the player is not seeking
  14283. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  14284. return null;
  14285. }
  14286. return this.generateSegmentInfo_(next);
  14287. }
  14288. generateSegmentInfo_(options) {
  14289. const {
  14290. independent,
  14291. playlist,
  14292. mediaIndex,
  14293. startOfSegment,
  14294. isSyncRequest,
  14295. partIndex,
  14296. forceTimestampOffset,
  14297. getMediaInfoForTime
  14298. } = options;
  14299. const segment = playlist.segments[mediaIndex];
  14300. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  14301. const segmentInfo = {
  14302. requestId: 'segment-loader-' + Math.random(),
  14303. // resolve the segment URL relative to the playlist
  14304. uri: part && part.resolvedUri || segment.resolvedUri,
  14305. // the segment's mediaIndex at the time it was requested
  14306. mediaIndex,
  14307. partIndex: part ? partIndex : null,
  14308. // whether or not to update the SegmentLoader's state with this
  14309. // segment's mediaIndex
  14310. isSyncRequest,
  14311. startOfSegment,
  14312. // the segment's playlist
  14313. playlist,
  14314. // unencrypted bytes of the segment
  14315. bytes: null,
  14316. // when a key is defined for this segment, the encrypted bytes
  14317. encryptedBytes: null,
  14318. // The target timestampOffset for this segment when we append it
  14319. // to the source buffer
  14320. timestampOffset: null,
  14321. // The timeline that the segment is in
  14322. timeline: segment.timeline,
  14323. // The expected duration of the segment in seconds
  14324. duration: part && part.duration || segment.duration,
  14325. // retain the segment in case the playlist updates while doing an async process
  14326. segment,
  14327. part,
  14328. byteLength: 0,
  14329. transmuxer: this.transmuxer_,
  14330. // type of getMediaInfoForTime that was used to get this segment
  14331. getMediaInfoForTime,
  14332. independent
  14333. };
  14334. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  14335. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  14336. segmentTimeline: segment.timeline,
  14337. currentTimeline: this.currentTimeline_,
  14338. startOfSegment,
  14339. buffered: this.buffered_(),
  14340. overrideCheck
  14341. });
  14342. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  14343. if (typeof audioBufferedEnd === 'number') {
  14344. // since the transmuxer is using the actual timing values, but the buffer is
  14345. // adjusted by the timestamp offset, we must adjust the value here
  14346. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  14347. }
  14348. if (this.sourceUpdater_.videoBuffered().length) {
  14349. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  14350. // adjusted by the timestmap offset, we must adjust the value here
  14351. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  14352. }
  14353. return segmentInfo;
  14354. } // get the timestampoffset for a segment,
  14355. // added so that vtt segment loader can override and prevent
  14356. // adding timestamp offsets.
  14357. timestampOffsetForSegment_(options) {
  14358. return timestampOffsetForSegment(options);
  14359. }
  14360. /**
  14361. * Determines if the network has enough bandwidth to complete the current segment
  14362. * request in a timely manner. If not, the request will be aborted early and bandwidth
  14363. * updated to trigger a playlist switch.
  14364. *
  14365. * @param {Object} stats
  14366. * Object containing stats about the request timing and size
  14367. * @private
  14368. */
  14369. earlyAbortWhenNeeded_(stats) {
  14370. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  14371. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  14372. // the lowestEnabledRendition.
  14373. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  14374. !this.playlist_.attributes.BANDWIDTH) {
  14375. return;
  14376. } // Wait at least 1 second since the first byte of data has been received before
  14377. // using the calculated bandwidth from the progress event to allow the bitrate
  14378. // to stabilize
  14379. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  14380. return;
  14381. }
  14382. const currentTime = this.currentTime_();
  14383. const measuredBandwidth = stats.bandwidth;
  14384. const segmentDuration = this.pendingSegment_.duration;
  14385. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  14386. // if we are only left with less than 1 second when the request completes.
  14387. // A negative timeUntilRebuffering indicates we are already rebuffering
  14388. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  14389. // is larger than the estimated time until the player runs out of forward buffer
  14390. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  14391. return;
  14392. }
  14393. const switchCandidate = minRebufferMaxBandwidthSelector({
  14394. main: this.vhs_.playlists.main,
  14395. currentTime,
  14396. bandwidth: measuredBandwidth,
  14397. duration: this.duration_(),
  14398. segmentDuration,
  14399. timeUntilRebuffer: timeUntilRebuffer$1,
  14400. currentTimeline: this.currentTimeline_,
  14401. syncController: this.syncController_
  14402. });
  14403. if (!switchCandidate) {
  14404. return;
  14405. }
  14406. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  14407. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  14408. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  14409. // potential round trip time of the new request so that we are not too aggressive
  14410. // with switching to a playlist that might save us a fraction of a second.
  14411. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  14412. minimumTimeSaving = 1;
  14413. }
  14414. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  14415. return;
  14416. } // set the bandwidth to that of the desired playlist being sure to scale by
  14417. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  14418. // don't trigger a bandwidthupdate as the bandwidth is artifial
  14419. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  14420. this.trigger('earlyabort');
  14421. }
  14422. handleAbort_(segmentInfo) {
  14423. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  14424. this.mediaRequestsAborted += 1;
  14425. }
  14426. /**
  14427. * XHR `progress` event handler
  14428. *
  14429. * @param {Event}
  14430. * The XHR `progress` event
  14431. * @param {Object} simpleSegment
  14432. * A simplified segment object copy
  14433. * @private
  14434. */
  14435. handleProgress_(event, simpleSegment) {
  14436. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14437. if (this.checkForAbort_(simpleSegment.requestId)) {
  14438. return;
  14439. }
  14440. this.trigger('progress');
  14441. }
  14442. handleTrackInfo_(simpleSegment, trackInfo) {
  14443. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14444. if (this.checkForAbort_(simpleSegment.requestId)) {
  14445. return;
  14446. }
  14447. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  14448. return;
  14449. }
  14450. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  14451. // Guard against cases where we're not getting track info at all until we are
  14452. // certain that all streams will provide it.
  14453. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  14454. this.appendInitSegment_ = {
  14455. audio: true,
  14456. video: true
  14457. };
  14458. this.startingMediaInfo_ = trackInfo;
  14459. this.currentMediaInfo_ = trackInfo;
  14460. this.logger_('trackinfo update', trackInfo);
  14461. this.trigger('trackinfo');
  14462. } // trackinfo may cause an abort if the trackinfo
  14463. // causes a codec change to an unsupported codec.
  14464. if (this.checkForAbort_(simpleSegment.requestId)) {
  14465. return;
  14466. } // set trackinfo on the pending segment so that
  14467. // it can append.
  14468. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  14469. if (this.hasEnoughInfoToAppend_()) {
  14470. this.processCallQueue_();
  14471. }
  14472. }
  14473. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  14474. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14475. if (this.checkForAbort_(simpleSegment.requestId)) {
  14476. return;
  14477. }
  14478. const segmentInfo = this.pendingSegment_;
  14479. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  14480. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  14481. segmentInfo[timingInfoProperty][timeType] = time;
  14482. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  14483. if (this.hasEnoughInfoToAppend_()) {
  14484. this.processCallQueue_();
  14485. }
  14486. }
  14487. handleCaptions_(simpleSegment, captionData) {
  14488. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14489. if (this.checkForAbort_(simpleSegment.requestId)) {
  14490. return;
  14491. } // This could only happen with fmp4 segments, but
  14492. // should still not happen in general
  14493. if (captionData.length === 0) {
  14494. this.logger_('SegmentLoader received no captions from a caption event');
  14495. return;
  14496. }
  14497. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  14498. // can be adjusted by the timestamp offset
  14499. if (!segmentInfo.hasAppendedData_) {
  14500. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  14501. return;
  14502. }
  14503. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  14504. const captionTracks = {}; // get total start/end and captions for each track/stream
  14505. captionData.forEach(caption => {
  14506. // caption.stream is actually a track name...
  14507. // set to the existing values in tracks or default values
  14508. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  14509. // Infinity, as any other value will be less than this
  14510. startTime: Infinity,
  14511. captions: [],
  14512. // 0 as an other value will be more than this
  14513. endTime: 0
  14514. };
  14515. const captionTrack = captionTracks[caption.stream];
  14516. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  14517. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  14518. captionTrack.captions.push(caption);
  14519. });
  14520. Object.keys(captionTracks).forEach(trackName => {
  14521. const {
  14522. startTime,
  14523. endTime,
  14524. captions
  14525. } = captionTracks[trackName];
  14526. const inbandTextTracks = this.inbandTextTracks_;
  14527. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  14528. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  14529. // We do this because a rendition change that also changes the timescale for captions
  14530. // will result in captions being re-parsed for certain segments. If we add them again
  14531. // without clearing we will have two of the same captions visible.
  14532. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  14533. addCaptionData({
  14534. captionArray: captions,
  14535. inbandTextTracks,
  14536. timestampOffset
  14537. });
  14538. }); // Reset stored captions since we added parsed
  14539. // captions to a text track at this point
  14540. if (this.transmuxer_) {
  14541. this.transmuxer_.postMessage({
  14542. action: 'clearParsedMp4Captions'
  14543. });
  14544. }
  14545. }
  14546. handleId3_(simpleSegment, id3Frames, dispatchType) {
  14547. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14548. if (this.checkForAbort_(simpleSegment.requestId)) {
  14549. return;
  14550. }
  14551. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  14552. if (!segmentInfo.hasAppendedData_) {
  14553. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  14554. return;
  14555. }
  14556. 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
  14557. // audio/video source with a metadata track, and an alt audio with a metadata track.
  14558. // However, this probably won't happen, and if it does it can be handled then.
  14559. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  14560. addMetadata({
  14561. inbandTextTracks: this.inbandTextTracks_,
  14562. metadataArray: id3Frames,
  14563. timestampOffset,
  14564. videoDuration: this.duration_()
  14565. });
  14566. }
  14567. processMetadataQueue_() {
  14568. this.metadataQueue_.id3.forEach(fn => fn());
  14569. this.metadataQueue_.caption.forEach(fn => fn());
  14570. this.metadataQueue_.id3 = [];
  14571. this.metadataQueue_.caption = [];
  14572. }
  14573. processCallQueue_() {
  14574. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  14575. // functions may check the length of the load queue and default to pushing themselves
  14576. // back onto the queue.
  14577. this.callQueue_ = [];
  14578. callQueue.forEach(fun => fun());
  14579. }
  14580. processLoadQueue_() {
  14581. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  14582. // functions may check the length of the load queue and default to pushing themselves
  14583. // back onto the queue.
  14584. this.loadQueue_ = [];
  14585. loadQueue.forEach(fun => fun());
  14586. }
  14587. /**
  14588. * Determines whether the loader has enough info to load the next segment.
  14589. *
  14590. * @return {boolean}
  14591. * Whether or not the loader has enough info to load the next segment
  14592. */
  14593. hasEnoughInfoToLoad_() {
  14594. // Since primary timing goes by video, only the audio loader potentially needs to wait
  14595. // to load.
  14596. if (this.loaderType_ !== 'audio') {
  14597. return true;
  14598. }
  14599. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  14600. // enough info to load.
  14601. if (!segmentInfo) {
  14602. return false;
  14603. } // The first segment can and should be loaded immediately so that source buffers are
  14604. // created together (before appending). Source buffer creation uses the presence of
  14605. // audio and video data to determine whether to create audio/video source buffers, and
  14606. // uses processed (transmuxed or parsed) media to determine the types required.
  14607. if (!this.getCurrentMediaInfo_()) {
  14608. return true;
  14609. }
  14610. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  14611. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  14612. // But in practice, there are a few reasons why it is better to wait until a loader
  14613. // is ready to append that segment before requesting and downloading:
  14614. //
  14615. // 1. Because audio and main loaders cross discontinuities together, if this loader
  14616. // is waiting for the other to catch up, then instead of requesting another
  14617. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  14618. // allotted to the loader currently behind.
  14619. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  14620. // is ready to be processed or not, isolating the queueing behavior to the loader.
  14621. // 3. The audio loader bases some of its segment properties on timing information
  14622. // provided by the main loader, meaning that, if the logic for waiting on
  14623. // processing was in media-segment-request, then it would also need to know how
  14624. // to re-generate the segment information after the main loader caught up.
  14625. shouldWaitForTimelineChange({
  14626. timelineChangeController: this.timelineChangeController_,
  14627. currentTimeline: this.currentTimeline_,
  14628. segmentTimeline: segmentInfo.timeline,
  14629. loaderType: this.loaderType_,
  14630. audioDisabled: this.audioDisabled_
  14631. })) {
  14632. return false;
  14633. }
  14634. return true;
  14635. }
  14636. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  14637. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  14638. }
  14639. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  14640. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  14641. }
  14642. getPendingSegmentPlaylist() {
  14643. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  14644. }
  14645. hasEnoughInfoToAppend_() {
  14646. if (!this.sourceUpdater_.ready()) {
  14647. return false;
  14648. } // If content needs to be removed or the loader is waiting on an append reattempt,
  14649. // then no additional content should be appended until the prior append is resolved.
  14650. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  14651. return false;
  14652. }
  14653. const segmentInfo = this.pendingSegment_;
  14654. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  14655. // we do not have information on this specific
  14656. // segment yet
  14657. if (!segmentInfo || !trackInfo) {
  14658. return false;
  14659. }
  14660. const {
  14661. hasAudio,
  14662. hasVideo,
  14663. isMuxed
  14664. } = trackInfo;
  14665. if (hasVideo && !segmentInfo.videoTimingInfo) {
  14666. return false;
  14667. } // muxed content only relies on video timing information for now.
  14668. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  14669. return false;
  14670. }
  14671. if (shouldWaitForTimelineChange({
  14672. timelineChangeController: this.timelineChangeController_,
  14673. currentTimeline: this.currentTimeline_,
  14674. segmentTimeline: segmentInfo.timeline,
  14675. loaderType: this.loaderType_,
  14676. audioDisabled: this.audioDisabled_
  14677. })) {
  14678. return false;
  14679. }
  14680. return true;
  14681. }
  14682. handleData_(simpleSegment, result) {
  14683. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14684. if (this.checkForAbort_(simpleSegment.requestId)) {
  14685. return;
  14686. } // If there's anything in the call queue, then this data came later and should be
  14687. // executed after the calls currently queued.
  14688. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  14689. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  14690. return;
  14691. }
  14692. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  14693. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  14694. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  14695. // logic may change behavior depending on the state, and changing state too early may
  14696. // inflate our estimates of bandwidth. In the future this should be re-examined to
  14697. // note more granular states.
  14698. // don't process and append data if the mediaSource is closed
  14699. if (this.mediaSource_.readyState === 'closed') {
  14700. return;
  14701. } // if this request included an initialization segment, save that data
  14702. // to the initSegment cache
  14703. if (simpleSegment.map) {
  14704. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  14705. segmentInfo.segment.map = simpleSegment.map;
  14706. } // if this request included a segment key, save that data in the cache
  14707. if (simpleSegment.key) {
  14708. this.segmentKey(simpleSegment.key, true);
  14709. }
  14710. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  14711. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  14712. if (segmentInfo.isFmp4) {
  14713. this.trigger('fmp4');
  14714. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  14715. } else {
  14716. const trackInfo = this.getCurrentMediaInfo_();
  14717. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  14718. let firstVideoFrameTimeForData;
  14719. if (useVideoTimingInfo) {
  14720. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  14721. } // Segment loader knows more about segment timing than the transmuxer (in certain
  14722. // aspects), so make any changes required for a more accurate start time.
  14723. // Don't set the end time yet, as the segment may not be finished processing.
  14724. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  14725. currentStart: segmentInfo.timingInfo.start,
  14726. playlist: segmentInfo.playlist,
  14727. mediaIndex: segmentInfo.mediaIndex,
  14728. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  14729. useVideoTimingInfo,
  14730. firstVideoFrameTimeForData,
  14731. videoTimingInfo: segmentInfo.videoTimingInfo,
  14732. audioTimingInfo: segmentInfo.audioTimingInfo
  14733. });
  14734. } // Init segments for audio and video only need to be appended in certain cases. Now
  14735. // that data is about to be appended, we can check the final cases to determine
  14736. // whether we should append an init segment.
  14737. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  14738. // as we use the start of the segment to offset the best guess (playlist provided)
  14739. // timestamp offset.
  14740. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  14741. // be appended or not.
  14742. if (segmentInfo.isSyncRequest) {
  14743. // first save/update our timing info for this segment.
  14744. // this is what allows us to choose an accurate segment
  14745. // and the main reason we make a sync request.
  14746. this.updateTimingInfoEnd_(segmentInfo);
  14747. this.syncController_.saveSegmentTimingInfo({
  14748. segmentInfo,
  14749. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  14750. });
  14751. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  14752. // after taking into account its timing info, do not append it.
  14753. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  14754. this.logger_('sync segment was incorrect, not appending');
  14755. return;
  14756. } // otherwise append it like any other segment as our guess was correct.
  14757. this.logger_('sync segment was correct, appending');
  14758. } // Save some state so that in the future anything waiting on first append (and/or
  14759. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  14760. // we need some notion of whether the timestamp offset or other relevant information
  14761. // has had a chance to be set.
  14762. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  14763. this.processMetadataQueue_();
  14764. this.appendData_(segmentInfo, result);
  14765. }
  14766. updateAppendInitSegmentStatus(segmentInfo, type) {
  14767. // alt audio doesn't manage timestamp offset
  14768. 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
  14769. // segment for each chunk
  14770. !segmentInfo.changedTimestampOffset) {
  14771. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  14772. // append init segments
  14773. this.appendInitSegment_ = {
  14774. audio: true,
  14775. video: true
  14776. };
  14777. }
  14778. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  14779. // make sure we append init segment on playlist changes, in case the media config
  14780. // changed
  14781. this.appendInitSegment_[type] = true;
  14782. }
  14783. }
  14784. getInitSegmentAndUpdateState_({
  14785. type,
  14786. initSegment,
  14787. map,
  14788. playlist
  14789. }) {
  14790. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  14791. // (Section 3) required to parse the applicable Media Segments. It applies to every
  14792. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  14793. // or until the end of the playlist."
  14794. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  14795. if (map) {
  14796. const id = initSegmentId(map);
  14797. if (this.activeInitSegmentId_ === id) {
  14798. // don't need to re-append the init segment if the ID matches
  14799. return null;
  14800. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  14801. // obtained) init segment
  14802. //
  14803. // this also caches the init segment for later use
  14804. initSegment = this.initSegmentForMap(map, true).bytes;
  14805. this.activeInitSegmentId_ = id;
  14806. } // We used to always prepend init segments for video, however, that shouldn't be
  14807. // necessary. Instead, we should only append on changes, similar to what we've always
  14808. // done for audio. This is more important (though may not be that important) for
  14809. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  14810. // appends.
  14811. if (initSegment && this.appendInitSegment_[type]) {
  14812. // Make sure we track the playlist that we last used for the init segment, so that
  14813. // we can re-append the init segment in the event that we get data from a new
  14814. // playlist. Discontinuities and track changes are handled in other sections.
  14815. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  14816. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  14817. // we are appending the muxer init segment
  14818. this.activeInitSegmentId_ = null;
  14819. return initSegment;
  14820. }
  14821. return null;
  14822. }
  14823. handleQuotaExceededError_({
  14824. segmentInfo,
  14825. type,
  14826. bytes
  14827. }, error) {
  14828. const audioBuffered = this.sourceUpdater_.audioBuffered();
  14829. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  14830. // should be cleared out during the buffer removals. However, log in case it helps
  14831. // debug.
  14832. if (audioBuffered.length > 1) {
  14833. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  14834. }
  14835. if (videoBuffered.length > 1) {
  14836. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  14837. }
  14838. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  14839. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  14840. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  14841. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  14842. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  14843. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  14844. // allow for appends of segments this size). In the future, it may be possible to
  14845. // split up the segment and append in pieces, but for now, error out this playlist
  14846. // in an attempt to switch to a more manageable rendition.
  14847. 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(', ')}, `);
  14848. this.error({
  14849. message: 'Quota exceeded error with append of a single segment of content',
  14850. excludeUntil: Infinity
  14851. });
  14852. this.trigger('error');
  14853. return;
  14854. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  14855. // that the segment-loader should block on future events until this one is handled, so
  14856. // that it doesn't keep moving onto further segments. Adding the call to the call
  14857. // queue will prevent further appends until waitingOnRemove_ and
  14858. // quotaExceededErrorRetryTimeout_ are cleared.
  14859. //
  14860. // Note that this will only block the current loader. In the case of demuxed content,
  14861. // the other load may keep filling as fast as possible. In practice, this should be
  14862. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  14863. // source buffer, or video fills without enough room for audio to append (and without
  14864. // the availability of clearing out seconds of back buffer to make room for audio).
  14865. // But it might still be good to handle this case in the future as a TODO.
  14866. this.waitingOnRemove_ = true;
  14867. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  14868. segmentInfo,
  14869. type,
  14870. bytes
  14871. }));
  14872. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  14873. // before retrying.
  14874. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  14875. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  14876. this.remove(0, timeToRemoveUntil, () => {
  14877. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  14878. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  14879. // attempts (since we can't clear less than the minimum)
  14880. this.quotaExceededErrorRetryTimeout_ = window$1.setTimeout(() => {
  14881. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  14882. this.quotaExceededErrorRetryTimeout_ = null;
  14883. this.processCallQueue_();
  14884. }, MIN_BACK_BUFFER * 1000);
  14885. }, true);
  14886. }
  14887. handleAppendError_({
  14888. segmentInfo,
  14889. type,
  14890. bytes
  14891. }, error) {
  14892. // if there's no error, nothing to do
  14893. if (!error) {
  14894. return;
  14895. }
  14896. if (error.code === QUOTA_EXCEEDED_ERR) {
  14897. this.handleQuotaExceededError_({
  14898. segmentInfo,
  14899. type,
  14900. bytes
  14901. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  14902. // to trigger an append error.
  14903. return;
  14904. }
  14905. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  14906. 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.
  14907. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  14908. //
  14909. // Trigger a special error so that it can be handled separately from normal,
  14910. // recoverable errors.
  14911. this.trigger('appenderror');
  14912. }
  14913. appendToSourceBuffer_({
  14914. segmentInfo,
  14915. type,
  14916. initSegment,
  14917. data,
  14918. bytes
  14919. }) {
  14920. // If this is a re-append, bytes were already created and don't need to be recreated
  14921. if (!bytes) {
  14922. const segments = [data];
  14923. let byteLength = data.byteLength;
  14924. if (initSegment) {
  14925. // if the media initialization segment is changing, append it before the content
  14926. // segment
  14927. segments.unshift(initSegment);
  14928. byteLength += initSegment.byteLength;
  14929. } // Technically we should be OK appending the init segment separately, however, we
  14930. // haven't yet tested that, and prepending is how we have always done things.
  14931. bytes = concatSegments({
  14932. bytes: byteLength,
  14933. segments
  14934. });
  14935. }
  14936. this.sourceUpdater_.appendBuffer({
  14937. segmentInfo,
  14938. type,
  14939. bytes
  14940. }, this.handleAppendError_.bind(this, {
  14941. segmentInfo,
  14942. type,
  14943. bytes
  14944. }));
  14945. }
  14946. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  14947. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  14948. return;
  14949. }
  14950. const segment = this.pendingSegment_.segment;
  14951. const timingInfoProperty = `${type}TimingInfo`;
  14952. if (!segment[timingInfoProperty]) {
  14953. segment[timingInfoProperty] = {};
  14954. }
  14955. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  14956. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  14957. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  14958. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  14959. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  14960. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  14961. }
  14962. appendData_(segmentInfo, result) {
  14963. const {
  14964. type,
  14965. data
  14966. } = result;
  14967. if (!data || !data.byteLength) {
  14968. return;
  14969. }
  14970. if (type === 'audio' && this.audioDisabled_) {
  14971. return;
  14972. }
  14973. const initSegment = this.getInitSegmentAndUpdateState_({
  14974. type,
  14975. initSegment: result.initSegment,
  14976. playlist: segmentInfo.playlist,
  14977. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  14978. });
  14979. this.appendToSourceBuffer_({
  14980. segmentInfo,
  14981. type,
  14982. initSegment,
  14983. data
  14984. });
  14985. }
  14986. /**
  14987. * load a specific segment from a request into the buffer
  14988. *
  14989. * @private
  14990. */
  14991. loadSegment_(segmentInfo) {
  14992. this.state = 'WAITING';
  14993. this.pendingSegment_ = segmentInfo;
  14994. this.trimBackBuffer_(segmentInfo);
  14995. if (typeof segmentInfo.timestampOffset === 'number') {
  14996. if (this.transmuxer_) {
  14997. this.transmuxer_.postMessage({
  14998. action: 'clearAllMp4Captions'
  14999. });
  15000. }
  15001. }
  15002. if (!this.hasEnoughInfoToLoad_()) {
  15003. this.loadQueue_.push(() => {
  15004. // regenerate the audioAppendStart, timestampOffset, etc as they
  15005. // may have changed since this function was added to the queue.
  15006. const options = _extends({}, segmentInfo, {
  15007. forceTimestampOffset: true
  15008. });
  15009. _extends(segmentInfo, this.generateSegmentInfo_(options));
  15010. this.isPendingTimestampOffset_ = false;
  15011. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15012. });
  15013. return;
  15014. }
  15015. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15016. }
  15017. updateTransmuxerAndRequestSegment_(segmentInfo) {
  15018. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  15019. // the transmuxer still needs to be updated before then.
  15020. //
  15021. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  15022. // offset must be passed to the transmuxer for stream correcting adjustments.
  15023. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  15024. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  15025. segmentInfo.gopsToAlignWith = [];
  15026. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  15027. this.transmuxer_.postMessage({
  15028. action: 'reset'
  15029. });
  15030. this.transmuxer_.postMessage({
  15031. action: 'setTimestampOffset',
  15032. timestampOffset: segmentInfo.timestampOffset
  15033. });
  15034. }
  15035. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  15036. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  15037. const isWalkingForward = this.mediaIndex !== null;
  15038. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  15039. // the first timeline
  15040. segmentInfo.timeline > 0;
  15041. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  15042. 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),
  15043. // then this init segment has never been seen before and should be appended.
  15044. //
  15045. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  15046. // both to true and leave the decision of whether to append the init segment to append time.
  15047. if (simpleSegment.map && !simpleSegment.map.bytes) {
  15048. this.logger_('going to request init segment.');
  15049. this.appendInitSegment_ = {
  15050. video: true,
  15051. audio: true
  15052. };
  15053. }
  15054. segmentInfo.abortRequests = mediaSegmentRequest({
  15055. xhr: this.vhs_.xhr,
  15056. xhrOptions: this.xhrOptions_,
  15057. decryptionWorker: this.decrypter_,
  15058. segment: simpleSegment,
  15059. abortFn: this.handleAbort_.bind(this, segmentInfo),
  15060. progressFn: this.handleProgress_.bind(this),
  15061. trackInfoFn: this.handleTrackInfo_.bind(this),
  15062. timingInfoFn: this.handleTimingInfo_.bind(this),
  15063. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  15064. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  15065. captionsFn: this.handleCaptions_.bind(this),
  15066. isEndOfTimeline,
  15067. endedTimelineFn: () => {
  15068. this.logger_('received endedtimeline callback');
  15069. },
  15070. id3Fn: this.handleId3_.bind(this),
  15071. dataFn: this.handleData_.bind(this),
  15072. doneFn: this.segmentRequestFinished_.bind(this),
  15073. onTransmuxerLog: ({
  15074. message,
  15075. level,
  15076. stream
  15077. }) => {
  15078. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  15079. }
  15080. });
  15081. }
  15082. /**
  15083. * trim the back buffer so that we don't have too much data
  15084. * in the source buffer
  15085. *
  15086. * @private
  15087. *
  15088. * @param {Object} segmentInfo - the current segment
  15089. */
  15090. trimBackBuffer_(segmentInfo) {
  15091. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  15092. // buffer and a very conservative "garbage collector"
  15093. // We manually clear out the old buffer to ensure
  15094. // we don't trigger the QuotaExceeded error
  15095. // on the source buffer during subsequent appends
  15096. if (removeToTime > 0) {
  15097. this.remove(0, removeToTime);
  15098. }
  15099. }
  15100. /**
  15101. * created a simplified copy of the segment object with just the
  15102. * information necessary to perform the XHR and decryption
  15103. *
  15104. * @private
  15105. *
  15106. * @param {Object} segmentInfo - the current segment
  15107. * @return {Object} a simplified segment object copy
  15108. */
  15109. createSimplifiedSegmentObj_(segmentInfo) {
  15110. const segment = segmentInfo.segment;
  15111. const part = segmentInfo.part;
  15112. const simpleSegment = {
  15113. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  15114. byterange: part ? part.byterange : segment.byterange,
  15115. requestId: segmentInfo.requestId,
  15116. transmuxer: segmentInfo.transmuxer,
  15117. audioAppendStart: segmentInfo.audioAppendStart,
  15118. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  15119. part: segmentInfo.part
  15120. };
  15121. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  15122. if (previousSegment && previousSegment.timeline === segment.timeline) {
  15123. // The baseStartTime of a segment is used to handle rollover when probing the TS
  15124. // segment to retrieve timing information. Since the probe only looks at the media's
  15125. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  15126. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  15127. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  15128. // seconds of media time, so should be used here. The previous segment is used since
  15129. // the end of the previous segment should represent the beginning of the current
  15130. // segment, so long as they are on the same timeline.
  15131. if (previousSegment.videoTimingInfo) {
  15132. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  15133. } else if (previousSegment.audioTimingInfo) {
  15134. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  15135. }
  15136. }
  15137. if (segment.key) {
  15138. // if the media sequence is greater than 2^32, the IV will be incorrect
  15139. // assuming 10s segments, that would be about 1300 years
  15140. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  15141. simpleSegment.key = this.segmentKey(segment.key);
  15142. simpleSegment.key.iv = iv;
  15143. }
  15144. if (segment.map) {
  15145. simpleSegment.map = this.initSegmentForMap(segment.map);
  15146. }
  15147. return simpleSegment;
  15148. }
  15149. saveTransferStats_(stats) {
  15150. // every request counts as a media request even if it has been aborted
  15151. // or canceled due to a timeout
  15152. this.mediaRequests += 1;
  15153. if (stats) {
  15154. this.mediaBytesTransferred += stats.bytesReceived;
  15155. this.mediaTransferDuration += stats.roundTripTime;
  15156. }
  15157. }
  15158. saveBandwidthRelatedStats_(duration, stats) {
  15159. // byteLength will be used for throughput, and should be based on bytes receieved,
  15160. // which we only know at the end of the request and should reflect total bytes
  15161. // downloaded rather than just bytes processed from components of the segment
  15162. this.pendingSegment_.byteLength = stats.bytesReceived;
  15163. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  15164. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  15165. return;
  15166. }
  15167. this.bandwidth = stats.bandwidth;
  15168. this.roundTrip = stats.roundTripTime;
  15169. }
  15170. handleTimeout_() {
  15171. // although the VTT segment loader bandwidth isn't really used, it's good to
  15172. // maintain functinality between segment loaders
  15173. this.mediaRequestsTimedout += 1;
  15174. this.bandwidth = 1;
  15175. this.roundTrip = NaN;
  15176. this.trigger('bandwidthupdate');
  15177. this.trigger('timeout');
  15178. }
  15179. /**
  15180. * Handle the callback from the segmentRequest function and set the
  15181. * associated SegmentLoader state and errors if necessary
  15182. *
  15183. * @private
  15184. */
  15185. segmentRequestFinished_(error, simpleSegment, result) {
  15186. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  15187. // check the call queue directly since this function doesn't need to deal with any
  15188. // data, and can continue even if the source buffers are not set up and we didn't get
  15189. // any data from the segment
  15190. if (this.callQueue_.length) {
  15191. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  15192. return;
  15193. }
  15194. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  15195. if (!this.pendingSegment_) {
  15196. return;
  15197. } // the request was aborted and the SegmentLoader has already started
  15198. // another request. this can happen when the timeout for an aborted
  15199. // request triggers due to a limitation in the XHR library
  15200. // do not count this as any sort of request or we risk double-counting
  15201. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  15202. return;
  15203. } // an error occurred from the active pendingSegment_ so reset everything
  15204. if (error) {
  15205. this.pendingSegment_ = null;
  15206. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  15207. if (error.code === REQUEST_ERRORS.ABORTED) {
  15208. return;
  15209. }
  15210. this.pause(); // the error is really just that at least one of the requests timed-out
  15211. // set the bandwidth to a very low value and trigger an ABR switch to
  15212. // take emergency action
  15213. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  15214. this.handleTimeout_();
  15215. return;
  15216. } // if control-flow has arrived here, then the error is real
  15217. // emit an error event to exclude the current playlist
  15218. this.mediaRequestsErrored += 1;
  15219. this.error(error);
  15220. this.trigger('error');
  15221. return;
  15222. }
  15223. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  15224. // generated for ABR purposes
  15225. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  15226. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  15227. if (result.gopInfo) {
  15228. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  15229. } // Although we may have already started appending on progress, we shouldn't switch the
  15230. // state away from loading until we are officially done loading the segment data.
  15231. this.state = 'APPENDING'; // used for testing
  15232. this.trigger('appending');
  15233. this.waitForAppendsToComplete_(segmentInfo);
  15234. }
  15235. setTimeMapping_(timeline) {
  15236. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  15237. if (timelineMapping !== null) {
  15238. this.timeMapping_ = timelineMapping;
  15239. }
  15240. }
  15241. updateMediaSecondsLoaded_(segment) {
  15242. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  15243. this.mediaSecondsLoaded += segment.end - segment.start;
  15244. } else {
  15245. this.mediaSecondsLoaded += segment.duration;
  15246. }
  15247. }
  15248. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  15249. if (timestampOffset === null) {
  15250. return false;
  15251. } // note that we're potentially using the same timestamp offset for both video and
  15252. // audio
  15253. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15254. return true;
  15255. }
  15256. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15257. return true;
  15258. }
  15259. return false;
  15260. }
  15261. trueSegmentStart_({
  15262. currentStart,
  15263. playlist,
  15264. mediaIndex,
  15265. firstVideoFrameTimeForData,
  15266. currentVideoTimestampOffset,
  15267. useVideoTimingInfo,
  15268. videoTimingInfo,
  15269. audioTimingInfo
  15270. }) {
  15271. if (typeof currentStart !== 'undefined') {
  15272. // if start was set once, keep using it
  15273. return currentStart;
  15274. }
  15275. if (!useVideoTimingInfo) {
  15276. return audioTimingInfo.start;
  15277. }
  15278. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  15279. // within that segment. Since the transmuxer maintains a cache of incomplete data
  15280. // from and/or the last frame seen, the start time may reflect a frame that starts
  15281. // in the previous segment. Check for that case and ensure the start time is
  15282. // accurate for the segment.
  15283. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  15284. return firstVideoFrameTimeForData;
  15285. }
  15286. return videoTimingInfo.start;
  15287. }
  15288. waitForAppendsToComplete_(segmentInfo) {
  15289. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  15290. if (!trackInfo) {
  15291. this.error({
  15292. message: 'No starting media returned, likely due to an unsupported media format.',
  15293. playlistExclusionDuration: Infinity
  15294. });
  15295. this.trigger('error');
  15296. return;
  15297. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  15298. // on each queue this loader is responsible for to ensure that the appends are
  15299. // complete.
  15300. const {
  15301. hasAudio,
  15302. hasVideo,
  15303. isMuxed
  15304. } = trackInfo;
  15305. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  15306. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  15307. segmentInfo.waitingOnAppends = 0; // segments with no data
  15308. if (!segmentInfo.hasAppendedData_) {
  15309. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  15310. // When there's no audio or video data in the segment, there's no audio or video
  15311. // timing information.
  15312. //
  15313. // If there's no audio or video timing information, then the timestamp offset
  15314. // can't be adjusted to the appropriate value for the transmuxer and source
  15315. // buffers.
  15316. //
  15317. // Therefore, the next segment should be used to set the timestamp offset.
  15318. this.isPendingTimestampOffset_ = true;
  15319. } // override settings for metadata only segments
  15320. segmentInfo.timingInfo = {
  15321. start: 0
  15322. };
  15323. segmentInfo.waitingOnAppends++;
  15324. if (!this.isPendingTimestampOffset_) {
  15325. // update the timestampoffset
  15326. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  15327. // no video/audio data.
  15328. this.processMetadataQueue_();
  15329. } // append is "done" instantly with no data.
  15330. this.checkAppendsDone_(segmentInfo);
  15331. return;
  15332. } // Since source updater could call back synchronously, do the increments first.
  15333. if (waitForVideo) {
  15334. segmentInfo.waitingOnAppends++;
  15335. }
  15336. if (waitForAudio) {
  15337. segmentInfo.waitingOnAppends++;
  15338. }
  15339. if (waitForVideo) {
  15340. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15341. }
  15342. if (waitForAudio) {
  15343. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15344. }
  15345. }
  15346. checkAppendsDone_(segmentInfo) {
  15347. if (this.checkForAbort_(segmentInfo.requestId)) {
  15348. return;
  15349. }
  15350. segmentInfo.waitingOnAppends--;
  15351. if (segmentInfo.waitingOnAppends === 0) {
  15352. this.handleAppendsDone_();
  15353. }
  15354. }
  15355. checkForIllegalMediaSwitch(trackInfo) {
  15356. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  15357. if (illegalMediaSwitchError) {
  15358. this.error({
  15359. message: illegalMediaSwitchError,
  15360. playlistExclusionDuration: Infinity
  15361. });
  15362. this.trigger('error');
  15363. return true;
  15364. }
  15365. return false;
  15366. }
  15367. updateSourceBufferTimestampOffset_(segmentInfo) {
  15368. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  15369. // priority, timing-wise, so we must wait
  15370. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  15371. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  15372. this.loaderType_ !== 'main') {
  15373. return;
  15374. }
  15375. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  15376. // the timing info here comes from video. In the event that the audio is longer than
  15377. // the video, this will trim the start of the audio.
  15378. // This also trims any offset from 0 at the beginning of the media
  15379. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  15380. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  15381. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  15382. timingInfo: segmentInfo.timingInfo
  15383. }); // In the event that there are part segment downloads, each will try to update the
  15384. // timestamp offset. Retaining this bit of state prevents us from updating in the
  15385. // future (within the same segment), however, there may be a better way to handle it.
  15386. segmentInfo.changedTimestampOffset = true;
  15387. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15388. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  15389. didChange = true;
  15390. }
  15391. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15392. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  15393. didChange = true;
  15394. }
  15395. if (didChange) {
  15396. this.trigger('timestampoffset');
  15397. }
  15398. }
  15399. getSegmentStartTimeForTimestampOffsetCalculation_({
  15400. videoTimingInfo,
  15401. audioTimingInfo,
  15402. timingInfo
  15403. }) {
  15404. if (!this.useDtsForTimestampOffset_) {
  15405. return timingInfo.start;
  15406. }
  15407. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  15408. return videoTimingInfo.transmuxedDecodeStart;
  15409. } // handle audio only
  15410. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  15411. return audioTimingInfo.transmuxedDecodeStart;
  15412. } // handle content not transmuxed (e.g., MP4)
  15413. return timingInfo.start;
  15414. }
  15415. updateTimingInfoEnd_(segmentInfo) {
  15416. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  15417. const trackInfo = this.getMediaInfo_();
  15418. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  15419. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  15420. if (!prioritizedTimingInfo) {
  15421. return;
  15422. }
  15423. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  15424. // current example is the case of fmp4), so use the rough duration to calculate an
  15425. // end time.
  15426. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  15427. }
  15428. /**
  15429. * callback to run when appendBuffer is finished. detects if we are
  15430. * in a good state to do things with the data we got, or if we need
  15431. * to wait for more
  15432. *
  15433. * @private
  15434. */
  15435. handleAppendsDone_() {
  15436. // appendsdone can cause an abort
  15437. if (this.pendingSegment_) {
  15438. this.trigger('appendsdone');
  15439. }
  15440. if (!this.pendingSegment_) {
  15441. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  15442. // all appending cases?
  15443. if (!this.paused()) {
  15444. this.monitorBuffer_();
  15445. }
  15446. return;
  15447. }
  15448. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  15449. // best to wait until all appends are done so we're sure that the primary media is
  15450. // finished (and we have its end time).
  15451. this.updateTimingInfoEnd_(segmentInfo);
  15452. if (this.shouldSaveSegmentTimingInfo_) {
  15453. // Timeline mappings should only be saved for the main loader. This is for multiple
  15454. // reasons:
  15455. //
  15456. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  15457. // and the main loader try to save the timeline mapping, whichever comes later
  15458. // will overwrite the first. In theory this is OK, as the mappings should be the
  15459. // same, however, it breaks for (2)
  15460. // 2) In the event of a live stream, the initial live point will make for a somewhat
  15461. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  15462. // the mapping will be off for one of the streams, dependent on which one was
  15463. // first saved (see (1)).
  15464. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  15465. //
  15466. // Since the audio loader will wait for the main loader to load the first segment,
  15467. // the main loader will save the first timeline mapping, and ensure that there won't
  15468. // be a case where audio loads two segments without saving a mapping (thus leading
  15469. // to missing segment timing info).
  15470. this.syncController_.saveSegmentTimingInfo({
  15471. segmentInfo,
  15472. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  15473. });
  15474. }
  15475. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  15476. if (segmentDurationMessage) {
  15477. if (segmentDurationMessage.severity === 'warn') {
  15478. videojs.log.warn(segmentDurationMessage.message);
  15479. } else {
  15480. this.logger_(segmentDurationMessage.message);
  15481. }
  15482. }
  15483. this.recordThroughput_(segmentInfo);
  15484. this.pendingSegment_ = null;
  15485. this.state = 'READY';
  15486. if (segmentInfo.isSyncRequest) {
  15487. this.trigger('syncinfoupdate'); // if the sync request was not appended
  15488. // then it was not the correct segment.
  15489. // throw it away and use the data it gave us
  15490. // to get the correct one.
  15491. if (!segmentInfo.hasAppendedData_) {
  15492. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  15493. return;
  15494. }
  15495. }
  15496. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  15497. this.addSegmentMetadataCue_(segmentInfo);
  15498. this.fetchAtBuffer_ = true;
  15499. if (this.currentTimeline_ !== segmentInfo.timeline) {
  15500. this.timelineChangeController_.lastTimelineChange({
  15501. type: this.loaderType_,
  15502. from: this.currentTimeline_,
  15503. to: segmentInfo.timeline
  15504. }); // If audio is not disabled, the main segment loader is responsible for updating
  15505. // the audio timeline as well. If the content is video only, this won't have any
  15506. // impact.
  15507. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  15508. this.timelineChangeController_.lastTimelineChange({
  15509. type: 'audio',
  15510. from: this.currentTimeline_,
  15511. to: segmentInfo.timeline
  15512. });
  15513. }
  15514. }
  15515. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  15516. // the following conditional otherwise it may consider this a bad "guess"
  15517. // and attempt to resync when the post-update seekable window and live
  15518. // point would mean that this was the perfect segment to fetch
  15519. this.trigger('syncinfoupdate');
  15520. const segment = segmentInfo.segment;
  15521. const part = segmentInfo.part;
  15522. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  15523. 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
  15524. // the currentTime_ that means that our conservative guess was too conservative.
  15525. // In that case, reset the loader state so that we try to use any information gained
  15526. // from the previous request to create a new, more accurate, sync-point.
  15527. if (badSegmentGuess || badPartGuess) {
  15528. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  15529. this.resetEverything();
  15530. return;
  15531. }
  15532. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  15533. // and conservatively guess
  15534. if (isWalkingForward) {
  15535. this.trigger('bandwidthupdate');
  15536. }
  15537. this.trigger('progress');
  15538. this.mediaIndex = segmentInfo.mediaIndex;
  15539. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  15540. // buffer, end the stream. this ensures the "ended" event will
  15541. // fire if playback reaches that point.
  15542. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  15543. this.endOfStream();
  15544. } // used for testing
  15545. this.trigger('appended');
  15546. if (segmentInfo.hasAppendedData_) {
  15547. this.mediaAppends++;
  15548. }
  15549. if (!this.paused()) {
  15550. this.monitorBuffer_();
  15551. }
  15552. }
  15553. /**
  15554. * Records the current throughput of the decrypt, transmux, and append
  15555. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  15556. * moving average of the throughput. `throughput.count` is the number of
  15557. * data points in the average.
  15558. *
  15559. * @private
  15560. * @param {Object} segmentInfo the object returned by loadSegment
  15561. */
  15562. recordThroughput_(segmentInfo) {
  15563. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  15564. 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}`);
  15565. return;
  15566. }
  15567. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  15568. // by zero in the case where the throughput is ridiculously high
  15569. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  15570. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  15571. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  15572. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  15573. }
  15574. /**
  15575. * Adds a cue to the segment-metadata track with some metadata information about the
  15576. * segment
  15577. *
  15578. * @private
  15579. * @param {Object} segmentInfo
  15580. * the object returned by loadSegment
  15581. * @method addSegmentMetadataCue_
  15582. */
  15583. addSegmentMetadataCue_(segmentInfo) {
  15584. if (!this.segmentMetadataTrack_) {
  15585. return;
  15586. }
  15587. const segment = segmentInfo.segment;
  15588. const start = segment.start;
  15589. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  15590. if (!finite(start) || !finite(end)) {
  15591. return;
  15592. }
  15593. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  15594. const Cue = window$1.WebKitDataCue || window$1.VTTCue;
  15595. const value = {
  15596. custom: segment.custom,
  15597. dateTimeObject: segment.dateTimeObject,
  15598. dateTimeString: segment.dateTimeString,
  15599. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  15600. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  15601. codecs: segmentInfo.playlist.attributes.CODECS,
  15602. byteLength: segmentInfo.byteLength,
  15603. uri: segmentInfo.uri,
  15604. timeline: segmentInfo.timeline,
  15605. playlist: segmentInfo.playlist.id,
  15606. start,
  15607. end
  15608. };
  15609. const data = JSON.stringify(value);
  15610. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  15611. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  15612. cue.value = value;
  15613. this.segmentMetadataTrack_.addCue(cue);
  15614. }
  15615. }
  15616. function noop() {}
  15617. const toTitleCase = function (string) {
  15618. if (typeof string !== 'string') {
  15619. return string;
  15620. }
  15621. return string.replace(/./, w => w.toUpperCase());
  15622. };
  15623. /**
  15624. * @file source-updater.js
  15625. */
  15626. const bufferTypes = ['video', 'audio'];
  15627. const updating = (type, sourceUpdater) => {
  15628. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15629. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  15630. };
  15631. const nextQueueIndexOfType = (type, queue) => {
  15632. for (let i = 0; i < queue.length; i++) {
  15633. const queueEntry = queue[i];
  15634. if (queueEntry.type === 'mediaSource') {
  15635. // If the next entry is a media source entry (uses multiple source buffers), block
  15636. // processing to allow it to go through first.
  15637. return null;
  15638. }
  15639. if (queueEntry.type === type) {
  15640. return i;
  15641. }
  15642. }
  15643. return null;
  15644. };
  15645. const shiftQueue = (type, sourceUpdater) => {
  15646. if (sourceUpdater.queue.length === 0) {
  15647. return;
  15648. }
  15649. let queueIndex = 0;
  15650. let queueEntry = sourceUpdater.queue[queueIndex];
  15651. if (queueEntry.type === 'mediaSource') {
  15652. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  15653. sourceUpdater.queue.shift();
  15654. queueEntry.action(sourceUpdater);
  15655. if (queueEntry.doneFn) {
  15656. queueEntry.doneFn();
  15657. } // Only specific source buffer actions must wait for async updateend events. Media
  15658. // Source actions process synchronously. Therefore, both audio and video source
  15659. // buffers are now clear to process the next queue entries.
  15660. shiftQueue('audio', sourceUpdater);
  15661. shiftQueue('video', sourceUpdater);
  15662. } // Media Source actions require both source buffers, so if the media source action
  15663. // couldn't process yet (because one or both source buffers are busy), block other
  15664. // queue actions until both are available and the media source action can process.
  15665. return;
  15666. }
  15667. if (type === 'mediaSource') {
  15668. // If the queue was shifted by a media source action (this happens when pushing a
  15669. // media source action onto the queue), then it wasn't from an updateend event from an
  15670. // audio or video source buffer, so there's no change from previous state, and no
  15671. // processing should be done.
  15672. return;
  15673. } // Media source queue entries don't need to consider whether the source updater is
  15674. // started (i.e., source buffers are created) as they don't need the source buffers, but
  15675. // source buffer queue entries do.
  15676. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  15677. return;
  15678. }
  15679. if (queueEntry.type !== type) {
  15680. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  15681. if (queueIndex === null) {
  15682. // Either there's no queue entry that uses this source buffer type in the queue, or
  15683. // there's a media source queue entry before the next entry of this type, in which
  15684. // case wait for that action to process first.
  15685. return;
  15686. }
  15687. queueEntry = sourceUpdater.queue[queueIndex];
  15688. }
  15689. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  15690. //
  15691. // The queue pending operation must be set before the action is performed in the event
  15692. // that the action results in a synchronous event that is acted upon. For instance, if
  15693. // an exception is thrown that can be handled, it's possible that new actions will be
  15694. // appended to an empty queue and immediately executed, but would not have the correct
  15695. // pending information if this property was set after the action was performed.
  15696. sourceUpdater.queuePending[type] = queueEntry;
  15697. queueEntry.action(type, sourceUpdater);
  15698. if (!queueEntry.doneFn) {
  15699. // synchronous operation, process next entry
  15700. sourceUpdater.queuePending[type] = null;
  15701. shiftQueue(type, sourceUpdater);
  15702. return;
  15703. }
  15704. };
  15705. const cleanupBuffer = (type, sourceUpdater) => {
  15706. const buffer = sourceUpdater[`${type}Buffer`];
  15707. const titleType = toTitleCase(type);
  15708. if (!buffer) {
  15709. return;
  15710. }
  15711. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  15712. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  15713. sourceUpdater.codecs[type] = null;
  15714. sourceUpdater[`${type}Buffer`] = null;
  15715. };
  15716. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  15717. const actions = {
  15718. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  15719. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15720. // or the media source does not contain this source buffer.
  15721. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15722. return;
  15723. }
  15724. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  15725. try {
  15726. sourceBuffer.appendBuffer(bytes);
  15727. } catch (e) {
  15728. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  15729. sourceUpdater.queuePending[type] = null;
  15730. onError(e);
  15731. }
  15732. },
  15733. remove: (start, end) => (type, sourceUpdater) => {
  15734. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15735. // or the media source does not contain this source buffer.
  15736. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15737. return;
  15738. }
  15739. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  15740. try {
  15741. sourceBuffer.remove(start, end);
  15742. } catch (e) {
  15743. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  15744. }
  15745. },
  15746. timestampOffset: offset => (type, sourceUpdater) => {
  15747. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15748. // or the media source does not contain this source buffer.
  15749. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15750. return;
  15751. }
  15752. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  15753. sourceBuffer.timestampOffset = offset;
  15754. },
  15755. callback: callback => (type, sourceUpdater) => {
  15756. callback();
  15757. },
  15758. endOfStream: error => sourceUpdater => {
  15759. if (sourceUpdater.mediaSource.readyState !== 'open') {
  15760. return;
  15761. }
  15762. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  15763. try {
  15764. sourceUpdater.mediaSource.endOfStream(error);
  15765. } catch (e) {
  15766. videojs.log.warn('Failed to call media source endOfStream', e);
  15767. }
  15768. },
  15769. duration: duration => sourceUpdater => {
  15770. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  15771. try {
  15772. sourceUpdater.mediaSource.duration = duration;
  15773. } catch (e) {
  15774. videojs.log.warn('Failed to set media source duration', e);
  15775. }
  15776. },
  15777. abort: () => (type, sourceUpdater) => {
  15778. if (sourceUpdater.mediaSource.readyState !== 'open') {
  15779. return;
  15780. }
  15781. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15782. // or the media source does not contain this source buffer.
  15783. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15784. return;
  15785. }
  15786. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  15787. try {
  15788. sourceBuffer.abort();
  15789. } catch (e) {
  15790. videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
  15791. }
  15792. },
  15793. addSourceBuffer: (type, codec) => sourceUpdater => {
  15794. const titleType = toTitleCase(type);
  15795. const mime = getMimeForCodec(codec);
  15796. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  15797. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  15798. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  15799. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  15800. sourceUpdater.codecs[type] = codec;
  15801. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  15802. },
  15803. removeSourceBuffer: type => sourceUpdater => {
  15804. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15805. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  15806. // or the media source does not contain this source buffer.
  15807. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15808. return;
  15809. }
  15810. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  15811. try {
  15812. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  15813. } catch (e) {
  15814. videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  15815. }
  15816. },
  15817. changeType: codec => (type, sourceUpdater) => {
  15818. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15819. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  15820. // or the media source does not contain this source buffer.
  15821. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15822. return;
  15823. } // do not update codec if we don't need to.
  15824. if (sourceUpdater.codecs[type] === codec) {
  15825. return;
  15826. }
  15827. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  15828. sourceBuffer.changeType(mime);
  15829. sourceUpdater.codecs[type] = codec;
  15830. }
  15831. };
  15832. const pushQueue = ({
  15833. type,
  15834. sourceUpdater,
  15835. action,
  15836. doneFn,
  15837. name
  15838. }) => {
  15839. sourceUpdater.queue.push({
  15840. type,
  15841. action,
  15842. doneFn,
  15843. name
  15844. });
  15845. shiftQueue(type, sourceUpdater);
  15846. };
  15847. const onUpdateend = (type, sourceUpdater) => e => {
  15848. // Although there should, in theory, be a pending action for any updateend receieved,
  15849. // there are some actions that may trigger updateend events without set definitions in
  15850. // the w3c spec. For instance, setting the duration on the media source may trigger
  15851. // updateend events on source buffers. This does not appear to be in the spec. As such,
  15852. // if we encounter an updateend without a corresponding pending action from our queue
  15853. // for that source buffer type, process the next action.
  15854. if (sourceUpdater.queuePending[type]) {
  15855. const doneFn = sourceUpdater.queuePending[type].doneFn;
  15856. sourceUpdater.queuePending[type] = null;
  15857. if (doneFn) {
  15858. // if there's an error, report it
  15859. doneFn(sourceUpdater[`${type}Error_`]);
  15860. }
  15861. }
  15862. shiftQueue(type, sourceUpdater);
  15863. };
  15864. /**
  15865. * A queue of callbacks to be serialized and applied when a
  15866. * MediaSource and its associated SourceBuffers are not in the
  15867. * updating state. It is used by the segment loader to update the
  15868. * underlying SourceBuffers when new data is loaded, for instance.
  15869. *
  15870. * @class SourceUpdater
  15871. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  15872. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  15873. */
  15874. class SourceUpdater extends videojs.EventTarget {
  15875. constructor(mediaSource) {
  15876. super();
  15877. this.mediaSource = mediaSource;
  15878. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  15879. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  15880. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  15881. this.audioTimestampOffset_ = 0;
  15882. this.videoTimestampOffset_ = 0;
  15883. this.queue = [];
  15884. this.queuePending = {
  15885. audio: null,
  15886. video: null
  15887. };
  15888. this.delayedAudioAppendQueue_ = [];
  15889. this.videoAppendQueued_ = false;
  15890. this.codecs = {};
  15891. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  15892. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  15893. this.onVideoError_ = e => {
  15894. // used for debugging
  15895. this.videoError_ = e;
  15896. };
  15897. this.onAudioError_ = e => {
  15898. // used for debugging
  15899. this.audioError_ = e;
  15900. };
  15901. this.createdSourceBuffers_ = false;
  15902. this.initializedEme_ = false;
  15903. this.triggeredReady_ = false;
  15904. }
  15905. initializedEme() {
  15906. this.initializedEme_ = true;
  15907. this.triggerReady();
  15908. }
  15909. hasCreatedSourceBuffers() {
  15910. // if false, likely waiting on one of the segment loaders to get enough data to create
  15911. // source buffers
  15912. return this.createdSourceBuffers_;
  15913. }
  15914. hasInitializedAnyEme() {
  15915. return this.initializedEme_;
  15916. }
  15917. ready() {
  15918. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  15919. }
  15920. createSourceBuffers(codecs) {
  15921. if (this.hasCreatedSourceBuffers()) {
  15922. // already created them before
  15923. return;
  15924. } // the intial addOrChangeSourceBuffers will always be
  15925. // two add buffers.
  15926. this.addOrChangeSourceBuffers(codecs);
  15927. this.createdSourceBuffers_ = true;
  15928. this.trigger('createdsourcebuffers');
  15929. this.triggerReady();
  15930. }
  15931. triggerReady() {
  15932. // only allow ready to be triggered once, this prevents the case
  15933. // where:
  15934. // 1. we trigger createdsourcebuffers
  15935. // 2. ie 11 synchronously initializates eme
  15936. // 3. the synchronous initialization causes us to trigger ready
  15937. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  15938. if (this.ready() && !this.triggeredReady_) {
  15939. this.triggeredReady_ = true;
  15940. this.trigger('ready');
  15941. }
  15942. }
  15943. /**
  15944. * Add a type of source buffer to the media source.
  15945. *
  15946. * @param {string} type
  15947. * The type of source buffer to add.
  15948. *
  15949. * @param {string} codec
  15950. * The codec to add the source buffer with.
  15951. */
  15952. addSourceBuffer(type, codec) {
  15953. pushQueue({
  15954. type: 'mediaSource',
  15955. sourceUpdater: this,
  15956. action: actions.addSourceBuffer(type, codec),
  15957. name: 'addSourceBuffer'
  15958. });
  15959. }
  15960. /**
  15961. * call abort on a source buffer.
  15962. *
  15963. * @param {string} type
  15964. * The type of source buffer to call abort on.
  15965. */
  15966. abort(type) {
  15967. pushQueue({
  15968. type,
  15969. sourceUpdater: this,
  15970. action: actions.abort(type),
  15971. name: 'abort'
  15972. });
  15973. }
  15974. /**
  15975. * Call removeSourceBuffer and remove a specific type
  15976. * of source buffer on the mediaSource.
  15977. *
  15978. * @param {string} type
  15979. * The type of source buffer to remove.
  15980. */
  15981. removeSourceBuffer(type) {
  15982. if (!this.canRemoveSourceBuffer()) {
  15983. videojs.log.error('removeSourceBuffer is not supported!');
  15984. return;
  15985. }
  15986. pushQueue({
  15987. type: 'mediaSource',
  15988. sourceUpdater: this,
  15989. action: actions.removeSourceBuffer(type),
  15990. name: 'removeSourceBuffer'
  15991. });
  15992. }
  15993. /**
  15994. * Whether or not the removeSourceBuffer function is supported
  15995. * on the mediaSource.
  15996. *
  15997. * @return {boolean}
  15998. * if removeSourceBuffer can be called.
  15999. */
  16000. canRemoveSourceBuffer() {
  16001. // IE reports that it supports removeSourceBuffer, but often throws
  16002. // errors when attempting to use the function. So we report that it
  16003. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  16004. // throws errors, so we report that it does not support this as well.
  16005. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window$1.MediaSource && window$1.MediaSource.prototype && typeof window$1.MediaSource.prototype.removeSourceBuffer === 'function';
  16006. }
  16007. /**
  16008. * Whether or not the changeType function is supported
  16009. * on our SourceBuffers.
  16010. *
  16011. * @return {boolean}
  16012. * if changeType can be called.
  16013. */
  16014. static canChangeType() {
  16015. return window$1.SourceBuffer && window$1.SourceBuffer.prototype && typeof window$1.SourceBuffer.prototype.changeType === 'function';
  16016. }
  16017. /**
  16018. * Whether or not the changeType function is supported
  16019. * on our SourceBuffers.
  16020. *
  16021. * @return {boolean}
  16022. * if changeType can be called.
  16023. */
  16024. canChangeType() {
  16025. return this.constructor.canChangeType();
  16026. }
  16027. /**
  16028. * Call the changeType function on a source buffer, given the code and type.
  16029. *
  16030. * @param {string} type
  16031. * The type of source buffer to call changeType on.
  16032. *
  16033. * @param {string} codec
  16034. * The codec string to change type with on the source buffer.
  16035. */
  16036. changeType(type, codec) {
  16037. if (!this.canChangeType()) {
  16038. videojs.log.error('changeType is not supported!');
  16039. return;
  16040. }
  16041. pushQueue({
  16042. type,
  16043. sourceUpdater: this,
  16044. action: actions.changeType(codec),
  16045. name: 'changeType'
  16046. });
  16047. }
  16048. /**
  16049. * Add source buffers with a codec or, if they are already created,
  16050. * call changeType on source buffers using changeType.
  16051. *
  16052. * @param {Object} codecs
  16053. * Codecs to switch to
  16054. */
  16055. addOrChangeSourceBuffers(codecs) {
  16056. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  16057. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  16058. }
  16059. Object.keys(codecs).forEach(type => {
  16060. const codec = codecs[type];
  16061. if (!this.hasCreatedSourceBuffers()) {
  16062. return this.addSourceBuffer(type, codec);
  16063. }
  16064. if (this.canChangeType()) {
  16065. this.changeType(type, codec);
  16066. }
  16067. });
  16068. }
  16069. /**
  16070. * Queue an update to append an ArrayBuffer.
  16071. *
  16072. * @param {MediaObject} object containing audioBytes and/or videoBytes
  16073. * @param {Function} done the function to call when done
  16074. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  16075. */
  16076. appendBuffer(options, doneFn) {
  16077. const {
  16078. segmentInfo,
  16079. type,
  16080. bytes
  16081. } = options;
  16082. this.processedAppend_ = true;
  16083. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  16084. this.delayedAudioAppendQueue_.push([options, doneFn]);
  16085. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  16086. return;
  16087. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  16088. // not be fired. This means that the queue will be blocked until the next action
  16089. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  16090. // these errors by calling the doneFn with the specific error.
  16091. const onError = doneFn;
  16092. pushQueue({
  16093. type,
  16094. sourceUpdater: this,
  16095. action: actions.appendBuffer(bytes, segmentInfo || {
  16096. mediaIndex: -1
  16097. }, onError),
  16098. doneFn,
  16099. name: 'appendBuffer'
  16100. });
  16101. if (type === 'video') {
  16102. this.videoAppendQueued_ = true;
  16103. if (!this.delayedAudioAppendQueue_.length) {
  16104. return;
  16105. }
  16106. const queue = this.delayedAudioAppendQueue_.slice();
  16107. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  16108. this.delayedAudioAppendQueue_.length = 0;
  16109. queue.forEach(que => {
  16110. this.appendBuffer.apply(this, que);
  16111. });
  16112. }
  16113. }
  16114. /**
  16115. * Get the audio buffer's buffered timerange.
  16116. *
  16117. * @return {TimeRange}
  16118. * The audio buffer's buffered time range
  16119. */
  16120. audioBuffered() {
  16121. // no media source/source buffer or it isn't in the media sources
  16122. // source buffer list
  16123. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  16124. return createTimeRanges();
  16125. }
  16126. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  16127. }
  16128. /**
  16129. * Get the video buffer's buffered timerange.
  16130. *
  16131. * @return {TimeRange}
  16132. * The video buffer's buffered time range
  16133. */
  16134. videoBuffered() {
  16135. // no media source/source buffer or it isn't in the media sources
  16136. // source buffer list
  16137. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  16138. return createTimeRanges();
  16139. }
  16140. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  16141. }
  16142. /**
  16143. * Get a combined video/audio buffer's buffered timerange.
  16144. *
  16145. * @return {TimeRange}
  16146. * the combined time range
  16147. */
  16148. buffered() {
  16149. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  16150. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  16151. if (audio && !video) {
  16152. return this.audioBuffered();
  16153. }
  16154. if (video && !audio) {
  16155. return this.videoBuffered();
  16156. }
  16157. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  16158. }
  16159. /**
  16160. * Add a callback to the queue that will set duration on the mediaSource.
  16161. *
  16162. * @param {number} duration
  16163. * The duration to set
  16164. *
  16165. * @param {Function} [doneFn]
  16166. * function to run after duration has been set.
  16167. */
  16168. setDuration(duration, doneFn = noop) {
  16169. // In order to set the duration on the media source, it's necessary to wait for all
  16170. // source buffers to no longer be updating. "If the updating attribute equals true on
  16171. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16172. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16173. pushQueue({
  16174. type: 'mediaSource',
  16175. sourceUpdater: this,
  16176. action: actions.duration(duration),
  16177. name: 'duration',
  16178. doneFn
  16179. });
  16180. }
  16181. /**
  16182. * Add a mediaSource endOfStream call to the queue
  16183. *
  16184. * @param {Error} [error]
  16185. * Call endOfStream with an error
  16186. *
  16187. * @param {Function} [doneFn]
  16188. * A function that should be called when the
  16189. * endOfStream call has finished.
  16190. */
  16191. endOfStream(error = null, doneFn = noop) {
  16192. if (typeof error !== 'string') {
  16193. error = undefined;
  16194. } // In order to set the duration on the media source, it's necessary to wait for all
  16195. // source buffers to no longer be updating. "If the updating attribute equals true on
  16196. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16197. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16198. pushQueue({
  16199. type: 'mediaSource',
  16200. sourceUpdater: this,
  16201. action: actions.endOfStream(error),
  16202. name: 'endOfStream',
  16203. doneFn
  16204. });
  16205. }
  16206. /**
  16207. * Queue an update to remove a time range from the buffer.
  16208. *
  16209. * @param {number} start where to start the removal
  16210. * @param {number} end where to end the removal
  16211. * @param {Function} [done=noop] optional callback to be executed when the remove
  16212. * operation is complete
  16213. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16214. */
  16215. removeAudio(start, end, done = noop) {
  16216. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  16217. done();
  16218. return;
  16219. }
  16220. pushQueue({
  16221. type: 'audio',
  16222. sourceUpdater: this,
  16223. action: actions.remove(start, end),
  16224. doneFn: done,
  16225. name: 'remove'
  16226. });
  16227. }
  16228. /**
  16229. * Queue an update to remove a time range from the buffer.
  16230. *
  16231. * @param {number} start where to start the removal
  16232. * @param {number} end where to end the removal
  16233. * @param {Function} [done=noop] optional callback to be executed when the remove
  16234. * operation is complete
  16235. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16236. */
  16237. removeVideo(start, end, done = noop) {
  16238. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  16239. done();
  16240. return;
  16241. }
  16242. pushQueue({
  16243. type: 'video',
  16244. sourceUpdater: this,
  16245. action: actions.remove(start, end),
  16246. doneFn: done,
  16247. name: 'remove'
  16248. });
  16249. }
  16250. /**
  16251. * Whether the underlying sourceBuffer is updating or not
  16252. *
  16253. * @return {boolean} the updating status of the SourceBuffer
  16254. */
  16255. updating() {
  16256. // the audio/video source buffer is updating
  16257. if (updating('audio', this) || updating('video', this)) {
  16258. return true;
  16259. }
  16260. return false;
  16261. }
  16262. /**
  16263. * Set/get the timestampoffset on the audio SourceBuffer
  16264. *
  16265. * @return {number} the timestamp offset
  16266. */
  16267. audioTimestampOffset(offset) {
  16268. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  16269. this.audioTimestampOffset_ !== offset) {
  16270. pushQueue({
  16271. type: 'audio',
  16272. sourceUpdater: this,
  16273. action: actions.timestampOffset(offset),
  16274. name: 'timestampOffset'
  16275. });
  16276. this.audioTimestampOffset_ = offset;
  16277. }
  16278. return this.audioTimestampOffset_;
  16279. }
  16280. /**
  16281. * Set/get the timestampoffset on the video SourceBuffer
  16282. *
  16283. * @return {number} the timestamp offset
  16284. */
  16285. videoTimestampOffset(offset) {
  16286. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  16287. this.videoTimestampOffset !== offset) {
  16288. pushQueue({
  16289. type: 'video',
  16290. sourceUpdater: this,
  16291. action: actions.timestampOffset(offset),
  16292. name: 'timestampOffset'
  16293. });
  16294. this.videoTimestampOffset_ = offset;
  16295. }
  16296. return this.videoTimestampOffset_;
  16297. }
  16298. /**
  16299. * Add a function to the queue that will be called
  16300. * when it is its turn to run in the audio queue.
  16301. *
  16302. * @param {Function} callback
  16303. * The callback to queue.
  16304. */
  16305. audioQueueCallback(callback) {
  16306. if (!this.audioBuffer) {
  16307. return;
  16308. }
  16309. pushQueue({
  16310. type: 'audio',
  16311. sourceUpdater: this,
  16312. action: actions.callback(callback),
  16313. name: 'callback'
  16314. });
  16315. }
  16316. /**
  16317. * Add a function to the queue that will be called
  16318. * when it is its turn to run in the video queue.
  16319. *
  16320. * @param {Function} callback
  16321. * The callback to queue.
  16322. */
  16323. videoQueueCallback(callback) {
  16324. if (!this.videoBuffer) {
  16325. return;
  16326. }
  16327. pushQueue({
  16328. type: 'video',
  16329. sourceUpdater: this,
  16330. action: actions.callback(callback),
  16331. name: 'callback'
  16332. });
  16333. }
  16334. /**
  16335. * dispose of the source updater and the underlying sourceBuffer
  16336. */
  16337. dispose() {
  16338. this.trigger('dispose');
  16339. bufferTypes.forEach(type => {
  16340. this.abort(type);
  16341. if (this.canRemoveSourceBuffer()) {
  16342. this.removeSourceBuffer(type);
  16343. } else {
  16344. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  16345. }
  16346. });
  16347. this.videoAppendQueued_ = false;
  16348. this.delayedAudioAppendQueue_.length = 0;
  16349. if (this.sourceopenListener_) {
  16350. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  16351. }
  16352. this.off();
  16353. }
  16354. }
  16355. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  16356. /**
  16357. * @file vtt-segment-loader.js
  16358. */
  16359. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  16360. class NoVttJsError extends Error {
  16361. constructor() {
  16362. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  16363. }
  16364. }
  16365. /**
  16366. * An object that manages segment loading and appending.
  16367. *
  16368. * @class VTTSegmentLoader
  16369. * @param {Object} options required and optional options
  16370. * @extends videojs.EventTarget
  16371. */
  16372. class VTTSegmentLoader extends SegmentLoader {
  16373. constructor(settings, options = {}) {
  16374. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  16375. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  16376. this.mediaSource_ = null;
  16377. this.subtitlesTrack_ = null;
  16378. this.loaderType_ = 'subtitle';
  16379. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  16380. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  16381. // the sync controller leads to improper behavior.
  16382. this.shouldSaveSegmentTimingInfo_ = false;
  16383. }
  16384. createTransmuxer_() {
  16385. // don't need to transmux any subtitles
  16386. return null;
  16387. }
  16388. /**
  16389. * Indicates which time ranges are buffered
  16390. *
  16391. * @return {TimeRange}
  16392. * TimeRange object representing the current buffered ranges
  16393. */
  16394. buffered_() {
  16395. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  16396. return createTimeRanges();
  16397. }
  16398. const cues = this.subtitlesTrack_.cues;
  16399. const start = cues[0].startTime;
  16400. const end = cues[cues.length - 1].startTime;
  16401. return createTimeRanges([[start, end]]);
  16402. }
  16403. /**
  16404. * Gets and sets init segment for the provided map
  16405. *
  16406. * @param {Object} map
  16407. * The map object representing the init segment to get or set
  16408. * @param {boolean=} set
  16409. * If true, the init segment for the provided map should be saved
  16410. * @return {Object}
  16411. * map object for desired init segment
  16412. */
  16413. initSegmentForMap(map, set = false) {
  16414. if (!map) {
  16415. return null;
  16416. }
  16417. const id = initSegmentId(map);
  16418. let storedMap = this.initSegments_[id];
  16419. if (set && !storedMap && map.bytes) {
  16420. // append WebVTT line terminators to the media initialization segment if it exists
  16421. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  16422. // requires two or more WebVTT line terminators between the WebVTT header and the
  16423. // rest of the file
  16424. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  16425. const combinedSegment = new Uint8Array(combinedByteLength);
  16426. combinedSegment.set(map.bytes);
  16427. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  16428. this.initSegments_[id] = storedMap = {
  16429. resolvedUri: map.resolvedUri,
  16430. byterange: map.byterange,
  16431. bytes: combinedSegment
  16432. };
  16433. }
  16434. return storedMap || map;
  16435. }
  16436. /**
  16437. * Returns true if all configuration required for loading is present, otherwise false.
  16438. *
  16439. * @return {boolean} True if the all configuration is ready for loading
  16440. * @private
  16441. */
  16442. couldBeginLoading_() {
  16443. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  16444. }
  16445. /**
  16446. * Once all the starting parameters have been specified, begin
  16447. * operation. This method should only be invoked from the INIT
  16448. * state.
  16449. *
  16450. * @private
  16451. */
  16452. init_() {
  16453. this.state = 'READY';
  16454. this.resetEverything();
  16455. return this.monitorBuffer_();
  16456. }
  16457. /**
  16458. * Set a subtitle track on the segment loader to add subtitles to
  16459. *
  16460. * @param {TextTrack=} track
  16461. * The text track to add loaded subtitles to
  16462. * @return {TextTrack}
  16463. * Returns the subtitles track
  16464. */
  16465. track(track) {
  16466. if (typeof track === 'undefined') {
  16467. return this.subtitlesTrack_;
  16468. }
  16469. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  16470. // buffering now
  16471. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  16472. this.init_();
  16473. }
  16474. return this.subtitlesTrack_;
  16475. }
  16476. /**
  16477. * Remove any data in the source buffer between start and end times
  16478. *
  16479. * @param {number} start - the start time of the region to remove from the buffer
  16480. * @param {number} end - the end time of the region to remove from the buffer
  16481. */
  16482. remove(start, end) {
  16483. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  16484. }
  16485. /**
  16486. * fill the buffer with segements unless the sourceBuffers are
  16487. * currently updating
  16488. *
  16489. * Note: this function should only ever be called by monitorBuffer_
  16490. * and never directly
  16491. *
  16492. * @private
  16493. */
  16494. fillBuffer_() {
  16495. // see if we need to begin loading immediately
  16496. const segmentInfo = this.chooseNextRequest_();
  16497. if (!segmentInfo) {
  16498. return;
  16499. }
  16500. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  16501. // We don't have the timestamp offset that we need to sync subtitles.
  16502. // Rerun on a timestamp offset or user interaction.
  16503. const checkTimestampOffset = () => {
  16504. this.state = 'READY';
  16505. if (!this.paused()) {
  16506. // if not paused, queue a buffer check as soon as possible
  16507. this.monitorBuffer_();
  16508. }
  16509. };
  16510. this.syncController_.one('timestampoffset', checkTimestampOffset);
  16511. this.state = 'WAITING_ON_TIMELINE';
  16512. return;
  16513. }
  16514. this.loadSegment_(segmentInfo);
  16515. } // never set a timestamp offset for vtt segments.
  16516. timestampOffsetForSegment_() {
  16517. return null;
  16518. }
  16519. chooseNextRequest_() {
  16520. return this.skipEmptySegments_(super.chooseNextRequest_());
  16521. }
  16522. /**
  16523. * Prevents the segment loader from requesting segments we know contain no subtitles
  16524. * by walking forward until we find the next segment that we don't know whether it is
  16525. * empty or not.
  16526. *
  16527. * @param {Object} segmentInfo
  16528. * a segment info object that describes the current segment
  16529. * @return {Object}
  16530. * a segment info object that describes the current segment
  16531. */
  16532. skipEmptySegments_(segmentInfo) {
  16533. while (segmentInfo && segmentInfo.segment.empty) {
  16534. // stop at the last possible segmentInfo
  16535. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  16536. segmentInfo = null;
  16537. break;
  16538. }
  16539. segmentInfo = this.generateSegmentInfo_({
  16540. playlist: segmentInfo.playlist,
  16541. mediaIndex: segmentInfo.mediaIndex + 1,
  16542. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  16543. isSyncRequest: segmentInfo.isSyncRequest
  16544. });
  16545. }
  16546. return segmentInfo;
  16547. }
  16548. stopForError(error) {
  16549. this.error(error);
  16550. this.state = 'READY';
  16551. this.pause();
  16552. this.trigger('error');
  16553. }
  16554. /**
  16555. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  16556. *
  16557. * @private
  16558. */
  16559. segmentRequestFinished_(error, simpleSegment, result) {
  16560. if (!this.subtitlesTrack_) {
  16561. this.state = 'READY';
  16562. return;
  16563. }
  16564. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  16565. if (!this.pendingSegment_) {
  16566. this.state = 'READY';
  16567. this.mediaRequestsAborted += 1;
  16568. return;
  16569. }
  16570. if (error) {
  16571. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  16572. this.handleTimeout_();
  16573. }
  16574. if (error.code === REQUEST_ERRORS.ABORTED) {
  16575. this.mediaRequestsAborted += 1;
  16576. } else {
  16577. this.mediaRequestsErrored += 1;
  16578. }
  16579. this.stopForError(error);
  16580. return;
  16581. }
  16582. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  16583. // maintain functionality between segment loaders
  16584. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  16585. if (simpleSegment.key) {
  16586. this.segmentKey(simpleSegment.key, true);
  16587. }
  16588. this.state = 'APPENDING'; // used for tests
  16589. this.trigger('appending');
  16590. const segment = segmentInfo.segment;
  16591. if (segment.map) {
  16592. segment.map.bytes = simpleSegment.map.bytes;
  16593. }
  16594. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  16595. if (typeof window$1.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  16596. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  16597. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  16598. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  16599. message: 'Error loading vtt.js'
  16600. }));
  16601. return;
  16602. }
  16603. segment.requested = true;
  16604. try {
  16605. this.parseVTTCues_(segmentInfo);
  16606. } catch (e) {
  16607. this.stopForError({
  16608. message: e.message
  16609. });
  16610. return;
  16611. }
  16612. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  16613. if (segmentInfo.cues.length) {
  16614. segmentInfo.timingInfo = {
  16615. start: segmentInfo.cues[0].startTime,
  16616. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  16617. };
  16618. } else {
  16619. segmentInfo.timingInfo = {
  16620. start: segmentInfo.startOfSegment,
  16621. end: segmentInfo.startOfSegment + segmentInfo.duration
  16622. };
  16623. }
  16624. if (segmentInfo.isSyncRequest) {
  16625. this.trigger('syncinfoupdate');
  16626. this.pendingSegment_ = null;
  16627. this.state = 'READY';
  16628. return;
  16629. }
  16630. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  16631. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  16632. // the subtitle track
  16633. segmentInfo.cues.forEach(cue => {
  16634. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window$1.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  16635. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  16636. // cues to have identical time-intervals, but if the text is also identical
  16637. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  16638. // "overlaps" VTT segments)
  16639. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  16640. this.handleAppendsDone_();
  16641. }
  16642. handleData_() {// noop as we shouldn't be getting video/audio data captions
  16643. // that we do not support here.
  16644. }
  16645. updateTimingInfoEnd_() {// noop
  16646. }
  16647. /**
  16648. * Uses the WebVTT parser to parse the segment response
  16649. *
  16650. * @throws NoVttJsError
  16651. *
  16652. * @param {Object} segmentInfo
  16653. * a segment info object that describes the current segment
  16654. * @private
  16655. */
  16656. parseVTTCues_(segmentInfo) {
  16657. let decoder;
  16658. let decodeBytesToString = false;
  16659. if (typeof window$1.WebVTT !== 'function') {
  16660. // caller is responsible for exception handling.
  16661. throw new NoVttJsError();
  16662. }
  16663. if (typeof window$1.TextDecoder === 'function') {
  16664. decoder = new window$1.TextDecoder('utf8');
  16665. } else {
  16666. decoder = window$1.WebVTT.StringDecoder();
  16667. decodeBytesToString = true;
  16668. }
  16669. const parser = new window$1.WebVTT.Parser(window$1, window$1.vttjs, decoder);
  16670. segmentInfo.cues = [];
  16671. segmentInfo.timestampmap = {
  16672. MPEGTS: 0,
  16673. LOCAL: 0
  16674. };
  16675. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  16676. parser.ontimestampmap = map => {
  16677. segmentInfo.timestampmap = map;
  16678. };
  16679. parser.onparsingerror = error => {
  16680. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  16681. };
  16682. if (segmentInfo.segment.map) {
  16683. let mapData = segmentInfo.segment.map.bytes;
  16684. if (decodeBytesToString) {
  16685. mapData = uint8ToUtf8(mapData);
  16686. }
  16687. parser.parse(mapData);
  16688. }
  16689. let segmentData = segmentInfo.bytes;
  16690. if (decodeBytesToString) {
  16691. segmentData = uint8ToUtf8(segmentData);
  16692. }
  16693. parser.parse(segmentData);
  16694. parser.flush();
  16695. }
  16696. /**
  16697. * Updates the start and end times of any cues parsed by the WebVTT parser using
  16698. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  16699. * from the SyncController
  16700. *
  16701. * @param {Object} segmentInfo
  16702. * a segment info object that describes the current segment
  16703. * @param {Object} mappingObj
  16704. * object containing a mapping from TS to media time
  16705. * @param {Object} playlist
  16706. * the playlist object containing the segment
  16707. * @private
  16708. */
  16709. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  16710. const segment = segmentInfo.segment;
  16711. if (!mappingObj) {
  16712. // If the sync controller does not have a mapping of TS to Media Time for the
  16713. // timeline, then we don't have enough information to update the cue
  16714. // start/end times
  16715. return;
  16716. }
  16717. if (!segmentInfo.cues.length) {
  16718. // If there are no cues, we also do not have enough information to figure out
  16719. // segment timing. Mark that the segment contains no cues so we don't re-request
  16720. // an empty segment.
  16721. segment.empty = true;
  16722. return;
  16723. }
  16724. const timestampmap = segmentInfo.timestampmap;
  16725. const diff = timestampmap.MPEGTS / ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  16726. segmentInfo.cues.forEach(cue => {
  16727. // First convert cue time to TS time using the timestamp-map provided within the vtt
  16728. cue.startTime += diff;
  16729. cue.endTime += diff;
  16730. });
  16731. if (!playlist.syncInfo) {
  16732. const firstStart = segmentInfo.cues[0].startTime;
  16733. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  16734. playlist.syncInfo = {
  16735. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  16736. time: Math.min(firstStart, lastStart - segment.duration)
  16737. };
  16738. }
  16739. }
  16740. }
  16741. /**
  16742. * @file ad-cue-tags.js
  16743. */
  16744. /**
  16745. * Searches for an ad cue that overlaps with the given mediaTime
  16746. *
  16747. * @param {Object} track
  16748. * the track to find the cue for
  16749. *
  16750. * @param {number} mediaTime
  16751. * the time to find the cue at
  16752. *
  16753. * @return {Object|null}
  16754. * the found cue or null
  16755. */
  16756. const findAdCue = function (track, mediaTime) {
  16757. const cues = track.cues;
  16758. for (let i = 0; i < cues.length; i++) {
  16759. const cue = cues[i];
  16760. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  16761. return cue;
  16762. }
  16763. }
  16764. return null;
  16765. };
  16766. const updateAdCues = function (media, track, offset = 0) {
  16767. if (!media.segments) {
  16768. return;
  16769. }
  16770. let mediaTime = offset;
  16771. let cue;
  16772. for (let i = 0; i < media.segments.length; i++) {
  16773. const segment = media.segments[i];
  16774. if (!cue) {
  16775. // Since the cues will span for at least the segment duration, adding a fudge
  16776. // factor of half segment duration will prevent duplicate cues from being
  16777. // created when timing info is not exact (e.g. cue start time initialized
  16778. // at 10.006677, but next call mediaTime is 10.003332 )
  16779. cue = findAdCue(track, mediaTime + segment.duration / 2);
  16780. }
  16781. if (cue) {
  16782. if ('cueIn' in segment) {
  16783. // Found a CUE-IN so end the cue
  16784. cue.endTime = mediaTime;
  16785. cue.adEndTime = mediaTime;
  16786. mediaTime += segment.duration;
  16787. cue = null;
  16788. continue;
  16789. }
  16790. if (mediaTime < cue.endTime) {
  16791. // Already processed this mediaTime for this cue
  16792. mediaTime += segment.duration;
  16793. continue;
  16794. } // otherwise extend cue until a CUE-IN is found
  16795. cue.endTime += segment.duration;
  16796. } else {
  16797. if ('cueOut' in segment) {
  16798. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  16799. cue.adStartTime = mediaTime; // Assumes tag format to be
  16800. // #EXT-X-CUE-OUT:30
  16801. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  16802. track.addCue(cue);
  16803. }
  16804. if ('cueOutCont' in segment) {
  16805. // Entered into the middle of an ad cue
  16806. // Assumes tag formate to be
  16807. // #EXT-X-CUE-OUT-CONT:10/30
  16808. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  16809. cue = new window$1.VTTCue(mediaTime, mediaTime + segment.duration, '');
  16810. cue.adStartTime = mediaTime - adOffset;
  16811. cue.adEndTime = cue.adStartTime + adTotal;
  16812. track.addCue(cue);
  16813. }
  16814. }
  16815. mediaTime += segment.duration;
  16816. }
  16817. };
  16818. /**
  16819. * @file sync-controller.js
  16820. */
  16821. // synchronize expired playlist segments.
  16822. // the max media sequence diff is 48 hours of live stream
  16823. // content with two second segments. Anything larger than that
  16824. // will likely be invalid.
  16825. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  16826. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  16827. // the equivalence display-time 0 === segment-index 0
  16828. {
  16829. name: 'VOD',
  16830. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16831. if (duration !== Infinity) {
  16832. const syncPoint = {
  16833. time: 0,
  16834. segmentIndex: 0,
  16835. partIndex: null
  16836. };
  16837. return syncPoint;
  16838. }
  16839. return null;
  16840. }
  16841. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  16842. {
  16843. name: 'ProgramDateTime',
  16844. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16845. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  16846. return null;
  16847. }
  16848. let syncPoint = null;
  16849. let lastDistance = null;
  16850. const partsAndSegments = getPartsAndSegments(playlist);
  16851. currentTime = currentTime || 0;
  16852. for (let i = 0; i < partsAndSegments.length; i++) {
  16853. // start from the end and loop backwards for live
  16854. // or start from the front and loop forwards for non-live
  16855. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  16856. const partAndSegment = partsAndSegments[index];
  16857. const segment = partAndSegment.segment;
  16858. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  16859. if (!datetimeMapping || !segment.dateTimeObject) {
  16860. continue;
  16861. }
  16862. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  16863. let start = segmentTime + datetimeMapping; // take part duration into account.
  16864. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  16865. for (let z = 0; z < partAndSegment.partIndex; z++) {
  16866. start += segment.parts[z].duration;
  16867. }
  16868. }
  16869. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  16870. // currentTime and can stop looking for better candidates
  16871. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  16872. break;
  16873. }
  16874. lastDistance = distance;
  16875. syncPoint = {
  16876. time: start,
  16877. segmentIndex: partAndSegment.segmentIndex,
  16878. partIndex: partAndSegment.partIndex
  16879. };
  16880. }
  16881. return syncPoint;
  16882. }
  16883. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  16884. // segment in the current timeline with timing data
  16885. {
  16886. name: 'Segment',
  16887. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16888. let syncPoint = null;
  16889. let lastDistance = null;
  16890. currentTime = currentTime || 0;
  16891. const partsAndSegments = getPartsAndSegments(playlist);
  16892. for (let i = 0; i < partsAndSegments.length; i++) {
  16893. // start from the end and loop backwards for live
  16894. // or start from the front and loop forwards for non-live
  16895. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  16896. const partAndSegment = partsAndSegments[index];
  16897. const segment = partAndSegment.segment;
  16898. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  16899. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  16900. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  16901. // currentTime and can stop looking for better candidates
  16902. if (lastDistance !== null && lastDistance < distance) {
  16903. break;
  16904. }
  16905. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  16906. lastDistance = distance;
  16907. syncPoint = {
  16908. time: start,
  16909. segmentIndex: partAndSegment.segmentIndex,
  16910. partIndex: partAndSegment.partIndex
  16911. };
  16912. }
  16913. }
  16914. }
  16915. return syncPoint;
  16916. }
  16917. }, // Stategy "Discontinuity": We have a discontinuity with a known
  16918. // display-time
  16919. {
  16920. name: 'Discontinuity',
  16921. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16922. let syncPoint = null;
  16923. currentTime = currentTime || 0;
  16924. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  16925. let lastDistance = null;
  16926. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  16927. const segmentIndex = playlist.discontinuityStarts[i];
  16928. const discontinuity = playlist.discontinuitySequence + i + 1;
  16929. const discontinuitySync = syncController.discontinuities[discontinuity];
  16930. if (discontinuitySync) {
  16931. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  16932. // currentTime and can stop looking for better candidates
  16933. if (lastDistance !== null && lastDistance < distance) {
  16934. break;
  16935. }
  16936. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  16937. lastDistance = distance;
  16938. syncPoint = {
  16939. time: discontinuitySync.time,
  16940. segmentIndex,
  16941. partIndex: null
  16942. };
  16943. }
  16944. }
  16945. }
  16946. }
  16947. return syncPoint;
  16948. }
  16949. }, // Stategy "Playlist": We have a playlist with a known mapping of
  16950. // segment index to display time
  16951. {
  16952. name: 'Playlist',
  16953. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16954. if (playlist.syncInfo) {
  16955. const syncPoint = {
  16956. time: playlist.syncInfo.time,
  16957. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  16958. partIndex: null
  16959. };
  16960. return syncPoint;
  16961. }
  16962. return null;
  16963. }
  16964. }];
  16965. class SyncController extends videojs.EventTarget {
  16966. constructor(options = {}) {
  16967. super(); // ...for synching across variants
  16968. this.timelines = [];
  16969. this.discontinuities = [];
  16970. this.timelineToDatetimeMappings = {};
  16971. this.logger_ = logger('SyncController');
  16972. }
  16973. /**
  16974. * Find a sync-point for the playlist specified
  16975. *
  16976. * A sync-point is defined as a known mapping from display-time to
  16977. * a segment-index in the current playlist.
  16978. *
  16979. * @param {Playlist} playlist
  16980. * The playlist that needs a sync-point
  16981. * @param {number} duration
  16982. * Duration of the MediaSource (Infinite if playing a live source)
  16983. * @param {number} currentTimeline
  16984. * The last timeline from which a segment was loaded
  16985. * @return {Object}
  16986. * A sync-point object
  16987. */
  16988. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  16989. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  16990. if (!syncPoints.length) {
  16991. // Signal that we need to attempt to get a sync-point manually
  16992. // by fetching a segment in the playlist and constructing
  16993. // a sync-point from that information
  16994. return null;
  16995. } // Now find the sync-point that is closest to the currentTime because
  16996. // that should result in the most accurate guess about which segment
  16997. // to fetch
  16998. return this.selectSyncPoint_(syncPoints, {
  16999. key: 'time',
  17000. value: currentTime
  17001. });
  17002. }
  17003. /**
  17004. * Calculate the amount of time that has expired off the playlist during playback
  17005. *
  17006. * @param {Playlist} playlist
  17007. * Playlist object to calculate expired from
  17008. * @param {number} duration
  17009. * Duration of the MediaSource (Infinity if playling a live source)
  17010. * @return {number|null}
  17011. * The amount of time that has expired off the playlist during playback. Null
  17012. * if no sync-points for the playlist can be found.
  17013. */
  17014. getExpiredTime(playlist, duration) {
  17015. if (!playlist || !playlist.segments) {
  17016. return null;
  17017. }
  17018. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  17019. if (!syncPoints.length) {
  17020. return null;
  17021. }
  17022. const syncPoint = this.selectSyncPoint_(syncPoints, {
  17023. key: 'segmentIndex',
  17024. value: 0
  17025. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  17026. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  17027. if (syncPoint.segmentIndex > 0) {
  17028. syncPoint.time *= -1;
  17029. }
  17030. return Math.abs(syncPoint.time + sumDurations({
  17031. defaultDuration: playlist.targetDuration,
  17032. durationList: playlist.segments,
  17033. startIndex: syncPoint.segmentIndex,
  17034. endIndex: 0
  17035. }));
  17036. }
  17037. /**
  17038. * Runs each sync-point strategy and returns a list of sync-points returned by the
  17039. * strategies
  17040. *
  17041. * @private
  17042. * @param {Playlist} playlist
  17043. * The playlist that needs a sync-point
  17044. * @param {number} duration
  17045. * Duration of the MediaSource (Infinity if playing a live source)
  17046. * @param {number} currentTimeline
  17047. * The last timeline from which a segment was loaded
  17048. * @return {Array}
  17049. * A list of sync-point objects
  17050. */
  17051. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  17052. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  17053. for (let i = 0; i < syncPointStrategies.length; i++) {
  17054. const strategy = syncPointStrategies[i];
  17055. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  17056. if (syncPoint) {
  17057. syncPoint.strategy = strategy.name;
  17058. syncPoints.push({
  17059. strategy: strategy.name,
  17060. syncPoint
  17061. });
  17062. }
  17063. }
  17064. return syncPoints;
  17065. }
  17066. /**
  17067. * Selects the sync-point nearest the specified target
  17068. *
  17069. * @private
  17070. * @param {Array} syncPoints
  17071. * List of sync-points to select from
  17072. * @param {Object} target
  17073. * Object specifying the property and value we are targeting
  17074. * @param {string} target.key
  17075. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  17076. * @param {number} target.value
  17077. * The value to target for the specified key.
  17078. * @return {Object}
  17079. * The sync-point nearest the target
  17080. */
  17081. selectSyncPoint_(syncPoints, target) {
  17082. let bestSyncPoint = syncPoints[0].syncPoint;
  17083. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  17084. let bestStrategy = syncPoints[0].strategy;
  17085. for (let i = 1; i < syncPoints.length; i++) {
  17086. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  17087. if (newDistance < bestDistance) {
  17088. bestDistance = newDistance;
  17089. bestSyncPoint = syncPoints[i].syncPoint;
  17090. bestStrategy = syncPoints[i].strategy;
  17091. }
  17092. }
  17093. 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}` : '') + ']');
  17094. return bestSyncPoint;
  17095. }
  17096. /**
  17097. * Save any meta-data present on the segments when segments leave
  17098. * the live window to the playlist to allow for synchronization at the
  17099. * playlist level later.
  17100. *
  17101. * @param {Playlist} oldPlaylist - The previous active playlist
  17102. * @param {Playlist} newPlaylist - The updated and most current playlist
  17103. */
  17104. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  17105. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  17106. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  17107. videojs.log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  17108. return;
  17109. } // When a segment expires from the playlist and it has a start time
  17110. // save that information as a possible sync-point reference in future
  17111. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  17112. const lastRemovedSegment = oldPlaylist.segments[i];
  17113. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  17114. newPlaylist.syncInfo = {
  17115. mediaSequence: oldPlaylist.mediaSequence + i,
  17116. time: lastRemovedSegment.start
  17117. };
  17118. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  17119. this.trigger('syncinfoupdate');
  17120. break;
  17121. }
  17122. }
  17123. }
  17124. /**
  17125. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  17126. * before segments start to load.
  17127. *
  17128. * @param {Playlist} playlist - The currently active playlist
  17129. */
  17130. setDateTimeMappingForStart(playlist) {
  17131. // It's possible for the playlist to be updated before playback starts, meaning time
  17132. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  17133. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  17134. // unless the mappings are cleared.
  17135. this.timelineToDatetimeMappings = {};
  17136. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  17137. const firstSegment = playlist.segments[0];
  17138. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  17139. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  17140. }
  17141. }
  17142. /**
  17143. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  17144. * based on the latest timing information.
  17145. *
  17146. * @param {Object} options
  17147. * Options object
  17148. * @param {SegmentInfo} options.segmentInfo
  17149. * The current active request information
  17150. * @param {boolean} options.shouldSaveTimelineMapping
  17151. * If there's a timeline change, determines if the timeline mapping should be
  17152. * saved for timeline mapping and program date time mappings.
  17153. */
  17154. saveSegmentTimingInfo({
  17155. segmentInfo,
  17156. shouldSaveTimelineMapping
  17157. }) {
  17158. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  17159. const segment = segmentInfo.segment;
  17160. if (didCalculateSegmentTimeMapping) {
  17161. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  17162. // now with segment timing information
  17163. if (!segmentInfo.playlist.syncInfo) {
  17164. segmentInfo.playlist.syncInfo = {
  17165. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  17166. time: segment.start
  17167. };
  17168. }
  17169. }
  17170. const dateTime = segment.dateTimeObject;
  17171. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  17172. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  17173. }
  17174. }
  17175. timestampOffsetForTimeline(timeline) {
  17176. if (typeof this.timelines[timeline] === 'undefined') {
  17177. return null;
  17178. }
  17179. return this.timelines[timeline].time;
  17180. }
  17181. mappingForTimeline(timeline) {
  17182. if (typeof this.timelines[timeline] === 'undefined') {
  17183. return null;
  17184. }
  17185. return this.timelines[timeline].mapping;
  17186. }
  17187. /**
  17188. * Use the "media time" for a segment to generate a mapping to "display time" and
  17189. * save that display time to the segment.
  17190. *
  17191. * @private
  17192. * @param {SegmentInfo} segmentInfo
  17193. * The current active request information
  17194. * @param {Object} timingInfo
  17195. * The start and end time of the current segment in "media time"
  17196. * @param {boolean} shouldSaveTimelineMapping
  17197. * If there's a timeline change, determines if the timeline mapping should be
  17198. * saved in timelines.
  17199. * @return {boolean}
  17200. * Returns false if segment time mapping could not be calculated
  17201. */
  17202. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  17203. // TODO: remove side effects
  17204. const segment = segmentInfo.segment;
  17205. const part = segmentInfo.part;
  17206. let mappingObj = this.timelines[segmentInfo.timeline];
  17207. let start;
  17208. let end;
  17209. if (typeof segmentInfo.timestampOffset === 'number') {
  17210. mappingObj = {
  17211. time: segmentInfo.startOfSegment,
  17212. mapping: segmentInfo.startOfSegment - timingInfo.start
  17213. };
  17214. if (shouldSaveTimelineMapping) {
  17215. this.timelines[segmentInfo.timeline] = mappingObj;
  17216. this.trigger('timestampoffset');
  17217. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  17218. }
  17219. start = segmentInfo.startOfSegment;
  17220. end = timingInfo.end + mappingObj.mapping;
  17221. } else if (mappingObj) {
  17222. start = timingInfo.start + mappingObj.mapping;
  17223. end = timingInfo.end + mappingObj.mapping;
  17224. } else {
  17225. return false;
  17226. }
  17227. if (part) {
  17228. part.start = start;
  17229. part.end = end;
  17230. } // If we don't have a segment start yet or the start value we got
  17231. // is less than our current segment.start value, save a new start value.
  17232. // We have to do this because parts will have segment timing info saved
  17233. // multiple times and we want segment start to be the earliest part start
  17234. // value for that segment.
  17235. if (!segment.start || start < segment.start) {
  17236. segment.start = start;
  17237. }
  17238. segment.end = end;
  17239. return true;
  17240. }
  17241. /**
  17242. * Each time we have discontinuity in the playlist, attempt to calculate the location
  17243. * in display of the start of the discontinuity and save that. We also save an accuracy
  17244. * value so that we save values with the most accuracy (closest to 0.)
  17245. *
  17246. * @private
  17247. * @param {SegmentInfo} segmentInfo - The current active request information
  17248. */
  17249. saveDiscontinuitySyncInfo_(segmentInfo) {
  17250. const playlist = segmentInfo.playlist;
  17251. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  17252. // the start of the range and it's accuracy is 0 (greater accuracy values
  17253. // mean more approximation)
  17254. if (segment.discontinuity) {
  17255. this.discontinuities[segment.timeline] = {
  17256. time: segment.start,
  17257. accuracy: 0
  17258. };
  17259. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  17260. // Search for future discontinuities that we can provide better timing
  17261. // information for and save that information for sync purposes
  17262. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  17263. const segmentIndex = playlist.discontinuityStarts[i];
  17264. const discontinuity = playlist.discontinuitySequence + i + 1;
  17265. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  17266. const accuracy = Math.abs(mediaIndexDiff);
  17267. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  17268. let time;
  17269. if (mediaIndexDiff < 0) {
  17270. time = segment.start - sumDurations({
  17271. defaultDuration: playlist.targetDuration,
  17272. durationList: playlist.segments,
  17273. startIndex: segmentInfo.mediaIndex,
  17274. endIndex: segmentIndex
  17275. });
  17276. } else {
  17277. time = segment.end + sumDurations({
  17278. defaultDuration: playlist.targetDuration,
  17279. durationList: playlist.segments,
  17280. startIndex: segmentInfo.mediaIndex + 1,
  17281. endIndex: segmentIndex
  17282. });
  17283. }
  17284. this.discontinuities[discontinuity] = {
  17285. time,
  17286. accuracy
  17287. };
  17288. }
  17289. }
  17290. }
  17291. }
  17292. dispose() {
  17293. this.trigger('dispose');
  17294. this.off();
  17295. }
  17296. }
  17297. /**
  17298. * The TimelineChangeController acts as a source for segment loaders to listen for and
  17299. * keep track of latest and pending timeline changes. This is useful to ensure proper
  17300. * sync, as each loader may need to make a consideration for what timeline the other
  17301. * loader is on before making changes which could impact the other loader's media.
  17302. *
  17303. * @class TimelineChangeController
  17304. * @extends videojs.EventTarget
  17305. */
  17306. class TimelineChangeController extends videojs.EventTarget {
  17307. constructor() {
  17308. super();
  17309. this.pendingTimelineChanges_ = {};
  17310. this.lastTimelineChanges_ = {};
  17311. }
  17312. clearPendingTimelineChange(type) {
  17313. this.pendingTimelineChanges_[type] = null;
  17314. this.trigger('pendingtimelinechange');
  17315. }
  17316. pendingTimelineChange({
  17317. type,
  17318. from,
  17319. to
  17320. }) {
  17321. if (typeof from === 'number' && typeof to === 'number') {
  17322. this.pendingTimelineChanges_[type] = {
  17323. type,
  17324. from,
  17325. to
  17326. };
  17327. this.trigger('pendingtimelinechange');
  17328. }
  17329. return this.pendingTimelineChanges_[type];
  17330. }
  17331. lastTimelineChange({
  17332. type,
  17333. from,
  17334. to
  17335. }) {
  17336. if (typeof from === 'number' && typeof to === 'number') {
  17337. this.lastTimelineChanges_[type] = {
  17338. type,
  17339. from,
  17340. to
  17341. };
  17342. delete this.pendingTimelineChanges_[type];
  17343. this.trigger('timelinechange');
  17344. }
  17345. return this.lastTimelineChanges_[type];
  17346. }
  17347. dispose() {
  17348. this.trigger('dispose');
  17349. this.pendingTimelineChanges_ = {};
  17350. this.lastTimelineChanges_ = {};
  17351. this.off();
  17352. }
  17353. }
  17354. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  17355. const workerCode = transform(getWorkerString(function () {
  17356. /**
  17357. * @file stream.js
  17358. */
  17359. /**
  17360. * A lightweight readable stream implemention that handles event dispatching.
  17361. *
  17362. * @class Stream
  17363. */
  17364. var Stream = /*#__PURE__*/function () {
  17365. function Stream() {
  17366. this.listeners = {};
  17367. }
  17368. /**
  17369. * Add a listener for a specified event type.
  17370. *
  17371. * @param {string} type the event name
  17372. * @param {Function} listener the callback to be invoked when an event of
  17373. * the specified type occurs
  17374. */
  17375. var _proto = Stream.prototype;
  17376. _proto.on = function on(type, listener) {
  17377. if (!this.listeners[type]) {
  17378. this.listeners[type] = [];
  17379. }
  17380. this.listeners[type].push(listener);
  17381. }
  17382. /**
  17383. * Remove a listener for a specified event type.
  17384. *
  17385. * @param {string} type the event name
  17386. * @param {Function} listener a function previously registered for this
  17387. * type of event through `on`
  17388. * @return {boolean} if we could turn it off or not
  17389. */
  17390. ;
  17391. _proto.off = function off(type, listener) {
  17392. if (!this.listeners[type]) {
  17393. return false;
  17394. }
  17395. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  17396. // In Video.js we slice listener functions
  17397. // on trigger so that it does not mess up the order
  17398. // while we loop through.
  17399. //
  17400. // Here we slice on off so that the loop in trigger
  17401. // can continue using it's old reference to loop without
  17402. // messing up the order.
  17403. this.listeners[type] = this.listeners[type].slice(0);
  17404. this.listeners[type].splice(index, 1);
  17405. return index > -1;
  17406. }
  17407. /**
  17408. * Trigger an event of the specified type on this stream. Any additional
  17409. * arguments to this function are passed as parameters to event listeners.
  17410. *
  17411. * @param {string} type the event name
  17412. */
  17413. ;
  17414. _proto.trigger = function trigger(type) {
  17415. var callbacks = this.listeners[type];
  17416. if (!callbacks) {
  17417. return;
  17418. } // Slicing the arguments on every invocation of this method
  17419. // can add a significant amount of overhead. Avoid the
  17420. // intermediate object creation for the common case of a
  17421. // single callback argument
  17422. if (arguments.length === 2) {
  17423. var length = callbacks.length;
  17424. for (var i = 0; i < length; ++i) {
  17425. callbacks[i].call(this, arguments[1]);
  17426. }
  17427. } else {
  17428. var args = Array.prototype.slice.call(arguments, 1);
  17429. var _length = callbacks.length;
  17430. for (var _i = 0; _i < _length; ++_i) {
  17431. callbacks[_i].apply(this, args);
  17432. }
  17433. }
  17434. }
  17435. /**
  17436. * Destroys the stream and cleans up.
  17437. */
  17438. ;
  17439. _proto.dispose = function dispose() {
  17440. this.listeners = {};
  17441. }
  17442. /**
  17443. * Forwards all `data` events on this stream to the destination stream. The
  17444. * destination stream should provide a method `push` to receive the data
  17445. * events as they arrive.
  17446. *
  17447. * @param {Stream} destination the stream that will receive all `data` events
  17448. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  17449. */
  17450. ;
  17451. _proto.pipe = function pipe(destination) {
  17452. this.on('data', function (data) {
  17453. destination.push(data);
  17454. });
  17455. };
  17456. return Stream;
  17457. }();
  17458. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  17459. /**
  17460. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  17461. *
  17462. * @param padded {Uint8Array} unencrypted bytes that have been padded
  17463. * @return {Uint8Array} the unpadded bytes
  17464. * @see http://tools.ietf.org/html/rfc5652
  17465. */
  17466. function unpad(padded) {
  17467. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  17468. }
  17469. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  17470. /**
  17471. * @file aes.js
  17472. *
  17473. * This file contains an adaptation of the AES decryption algorithm
  17474. * from the Standford Javascript Cryptography Library. That work is
  17475. * covered by the following copyright and permissions notice:
  17476. *
  17477. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  17478. * All rights reserved.
  17479. *
  17480. * Redistribution and use in source and binary forms, with or without
  17481. * modification, are permitted provided that the following conditions are
  17482. * met:
  17483. *
  17484. * 1. Redistributions of source code must retain the above copyright
  17485. * notice, this list of conditions and the following disclaimer.
  17486. *
  17487. * 2. Redistributions in binary form must reproduce the above
  17488. * copyright notice, this list of conditions and the following
  17489. * disclaimer in the documentation and/or other materials provided
  17490. * with the distribution.
  17491. *
  17492. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  17493. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17494. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17495. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  17496. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  17497. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  17498. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  17499. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  17500. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  17501. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  17502. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  17503. *
  17504. * The views and conclusions contained in the software and documentation
  17505. * are those of the authors and should not be interpreted as representing
  17506. * official policies, either expressed or implied, of the authors.
  17507. */
  17508. /**
  17509. * Expand the S-box tables.
  17510. *
  17511. * @private
  17512. */
  17513. const precompute = function () {
  17514. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  17515. const encTable = tables[0];
  17516. const decTable = tables[1];
  17517. const sbox = encTable[4];
  17518. const sboxInv = decTable[4];
  17519. let i;
  17520. let x;
  17521. let xInv;
  17522. const d = [];
  17523. const th = [];
  17524. let x2;
  17525. let x4;
  17526. let x8;
  17527. let s;
  17528. let tEnc;
  17529. let tDec; // Compute double and third tables
  17530. for (i = 0; i < 256; i++) {
  17531. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  17532. }
  17533. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  17534. // Compute sbox
  17535. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  17536. s = s >> 8 ^ s & 255 ^ 99;
  17537. sbox[x] = s;
  17538. sboxInv[s] = x; // Compute MixColumns
  17539. x8 = d[x4 = d[x2 = d[x]]];
  17540. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  17541. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  17542. for (i = 0; i < 4; i++) {
  17543. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  17544. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  17545. }
  17546. } // Compactify. Considerable speedup on Firefox.
  17547. for (i = 0; i < 5; i++) {
  17548. encTable[i] = encTable[i].slice(0);
  17549. decTable[i] = decTable[i].slice(0);
  17550. }
  17551. return tables;
  17552. };
  17553. let aesTables = null;
  17554. /**
  17555. * Schedule out an AES key for both encryption and decryption. This
  17556. * is a low-level class. Use a cipher mode to do bulk encryption.
  17557. *
  17558. * @class AES
  17559. * @param key {Array} The key as an array of 4, 6 or 8 words.
  17560. */
  17561. class AES {
  17562. constructor(key) {
  17563. /**
  17564. * The expanded S-box and inverse S-box tables. These will be computed
  17565. * on the client so that we don't have to send them down the wire.
  17566. *
  17567. * There are two tables, _tables[0] is for encryption and
  17568. * _tables[1] is for decryption.
  17569. *
  17570. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  17571. * last (_tables[01][4]) is the S-box itself.
  17572. *
  17573. * @private
  17574. */
  17575. // if we have yet to precompute the S-box tables
  17576. // do so now
  17577. if (!aesTables) {
  17578. aesTables = precompute();
  17579. } // then make a copy of that object for use
  17580. 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()]];
  17581. let i;
  17582. let j;
  17583. let tmp;
  17584. const sbox = this._tables[0][4];
  17585. const decTable = this._tables[1];
  17586. const keyLen = key.length;
  17587. let rcon = 1;
  17588. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  17589. throw new Error('Invalid aes key size');
  17590. }
  17591. const encKey = key.slice(0);
  17592. const decKey = [];
  17593. this._key = [encKey, decKey]; // schedule encryption keys
  17594. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  17595. tmp = encKey[i - 1]; // apply sbox
  17596. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  17597. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  17598. if (i % keyLen === 0) {
  17599. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  17600. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  17601. }
  17602. }
  17603. encKey[i] = encKey[i - keyLen] ^ tmp;
  17604. } // schedule decryption keys
  17605. for (j = 0; i; j++, i--) {
  17606. tmp = encKey[j & 3 ? i : i - 4];
  17607. if (i <= 4 || j < 4) {
  17608. decKey[j] = tmp;
  17609. } else {
  17610. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  17611. }
  17612. }
  17613. }
  17614. /**
  17615. * Decrypt 16 bytes, specified as four 32-bit words.
  17616. *
  17617. * @param {number} encrypted0 the first word to decrypt
  17618. * @param {number} encrypted1 the second word to decrypt
  17619. * @param {number} encrypted2 the third word to decrypt
  17620. * @param {number} encrypted3 the fourth word to decrypt
  17621. * @param {Int32Array} out the array to write the decrypted words
  17622. * into
  17623. * @param {number} offset the offset into the output array to start
  17624. * writing results
  17625. * @return {Array} The plaintext.
  17626. */
  17627. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  17628. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  17629. let a = encrypted0 ^ key[0];
  17630. let b = encrypted3 ^ key[1];
  17631. let c = encrypted2 ^ key[2];
  17632. let d = encrypted1 ^ key[3];
  17633. let a2;
  17634. let b2;
  17635. let c2; // key.length === 2 ?
  17636. const nInnerRounds = key.length / 4 - 2;
  17637. let i;
  17638. let kIndex = 4;
  17639. const table = this._tables[1]; // load up the tables
  17640. const table0 = table[0];
  17641. const table1 = table[1];
  17642. const table2 = table[2];
  17643. const table3 = table[3];
  17644. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  17645. for (i = 0; i < nInnerRounds; i++) {
  17646. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  17647. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  17648. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  17649. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  17650. kIndex += 4;
  17651. a = a2;
  17652. b = b2;
  17653. c = c2;
  17654. } // Last round.
  17655. for (i = 0; i < 4; i++) {
  17656. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  17657. a2 = a;
  17658. a = b;
  17659. b = c;
  17660. c = d;
  17661. d = a2;
  17662. }
  17663. }
  17664. }
  17665. /**
  17666. * @file async-stream.js
  17667. */
  17668. /**
  17669. * A wrapper around the Stream class to use setTimeout
  17670. * and run stream "jobs" Asynchronously
  17671. *
  17672. * @class AsyncStream
  17673. * @extends Stream
  17674. */
  17675. class AsyncStream extends Stream {
  17676. constructor() {
  17677. super(Stream);
  17678. this.jobs = [];
  17679. this.delay = 1;
  17680. this.timeout_ = null;
  17681. }
  17682. /**
  17683. * process an async job
  17684. *
  17685. * @private
  17686. */
  17687. processJob_() {
  17688. this.jobs.shift()();
  17689. if (this.jobs.length) {
  17690. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  17691. } else {
  17692. this.timeout_ = null;
  17693. }
  17694. }
  17695. /**
  17696. * push a job into the stream
  17697. *
  17698. * @param {Function} job the job to push into the stream
  17699. */
  17700. push(job) {
  17701. this.jobs.push(job);
  17702. if (!this.timeout_) {
  17703. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  17704. }
  17705. }
  17706. }
  17707. /**
  17708. * @file decrypter.js
  17709. *
  17710. * An asynchronous implementation of AES-128 CBC decryption with
  17711. * PKCS#7 padding.
  17712. */
  17713. /**
  17714. * Convert network-order (big-endian) bytes into their little-endian
  17715. * representation.
  17716. */
  17717. const ntoh = function (word) {
  17718. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  17719. };
  17720. /**
  17721. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  17722. *
  17723. * @param {Uint8Array} encrypted the encrypted bytes
  17724. * @param {Uint32Array} key the bytes of the decryption key
  17725. * @param {Uint32Array} initVector the initialization vector (IV) to
  17726. * use for the first round of CBC.
  17727. * @return {Uint8Array} the decrypted bytes
  17728. *
  17729. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  17730. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  17731. * @see https://tools.ietf.org/html/rfc2315
  17732. */
  17733. const decrypt = function (encrypted, key, initVector) {
  17734. // word-level access to the encrypted bytes
  17735. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  17736. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  17737. const decrypted = new Uint8Array(encrypted.byteLength);
  17738. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  17739. // decrypted data
  17740. let init0;
  17741. let init1;
  17742. let init2;
  17743. let init3;
  17744. let encrypted0;
  17745. let encrypted1;
  17746. let encrypted2;
  17747. let encrypted3; // iteration variable
  17748. let wordIx; // pull out the words of the IV to ensure we don't modify the
  17749. // passed-in reference and easier access
  17750. init0 = initVector[0];
  17751. init1 = initVector[1];
  17752. init2 = initVector[2];
  17753. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  17754. // to each decrypted block
  17755. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  17756. // convert big-endian (network order) words into little-endian
  17757. // (javascript order)
  17758. encrypted0 = ntoh(encrypted32[wordIx]);
  17759. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  17760. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  17761. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  17762. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  17763. // plaintext
  17764. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  17765. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  17766. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  17767. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  17768. init0 = encrypted0;
  17769. init1 = encrypted1;
  17770. init2 = encrypted2;
  17771. init3 = encrypted3;
  17772. }
  17773. return decrypted;
  17774. };
  17775. /**
  17776. * The `Decrypter` class that manages decryption of AES
  17777. * data through `AsyncStream` objects and the `decrypt`
  17778. * function
  17779. *
  17780. * @param {Uint8Array} encrypted the encrypted bytes
  17781. * @param {Uint32Array} key the bytes of the decryption key
  17782. * @param {Uint32Array} initVector the initialization vector (IV) to
  17783. * @param {Function} done the function to run when done
  17784. * @class Decrypter
  17785. */
  17786. class Decrypter {
  17787. constructor(encrypted, key, initVector, done) {
  17788. const step = Decrypter.STEP;
  17789. const encrypted32 = new Int32Array(encrypted.buffer);
  17790. const decrypted = new Uint8Array(encrypted.byteLength);
  17791. let i = 0;
  17792. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  17793. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  17794. for (i = step; i < encrypted32.length; i += step) {
  17795. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  17796. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  17797. } // invoke the done() callback when everything is finished
  17798. this.asyncStream_.push(function () {
  17799. // remove pkcs#7 padding from the decrypted bytes
  17800. done(null, unpad(decrypted));
  17801. });
  17802. }
  17803. /**
  17804. * a getter for step the maximum number of bytes to process at one time
  17805. *
  17806. * @return {number} the value of step 32000
  17807. */
  17808. static get STEP() {
  17809. // 4 * 8000;
  17810. return 32000;
  17811. }
  17812. /**
  17813. * @private
  17814. */
  17815. decryptChunk_(encrypted, key, initVector, decrypted) {
  17816. return function () {
  17817. const bytes = decrypt(encrypted, key, initVector);
  17818. decrypted.set(bytes, encrypted.byteOffset);
  17819. };
  17820. }
  17821. }
  17822. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  17823. var win;
  17824. if (typeof window !== "undefined") {
  17825. win = window;
  17826. } else if (typeof commonjsGlobal !== "undefined") {
  17827. win = commonjsGlobal;
  17828. } else if (typeof self !== "undefined") {
  17829. win = self;
  17830. } else {
  17831. win = {};
  17832. }
  17833. var window_1 = win;
  17834. var isArrayBufferView = function isArrayBufferView(obj) {
  17835. if (ArrayBuffer.isView === 'function') {
  17836. return ArrayBuffer.isView(obj);
  17837. }
  17838. return obj && obj.buffer instanceof ArrayBuffer;
  17839. };
  17840. var BigInt = window_1.BigInt || Number;
  17841. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  17842. (function () {
  17843. var a = new Uint16Array([0xFFCC]);
  17844. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  17845. if (b[0] === 0xFF) {
  17846. return 'big';
  17847. }
  17848. if (b[0] === 0xCC) {
  17849. return 'little';
  17850. }
  17851. return 'unknown';
  17852. })();
  17853. /**
  17854. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  17855. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  17856. *
  17857. * @param {Object} message
  17858. * Object of properties and values to send to the web worker
  17859. * @return {Object}
  17860. * Modified message with TypedArray values expanded
  17861. * @function createTransferableMessage
  17862. */
  17863. const createTransferableMessage = function (message) {
  17864. const transferable = {};
  17865. Object.keys(message).forEach(key => {
  17866. const value = message[key];
  17867. if (isArrayBufferView(value)) {
  17868. transferable[key] = {
  17869. bytes: value.buffer,
  17870. byteOffset: value.byteOffset,
  17871. byteLength: value.byteLength
  17872. };
  17873. } else {
  17874. transferable[key] = value;
  17875. }
  17876. });
  17877. return transferable;
  17878. };
  17879. /* global self */
  17880. /**
  17881. * Our web worker interface so that things can talk to aes-decrypter
  17882. * that will be running in a web worker. the scope is passed to this by
  17883. * webworkify.
  17884. */
  17885. self.onmessage = function (event) {
  17886. const data = event.data;
  17887. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  17888. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  17889. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  17890. /* eslint-disable no-new, handle-callback-err */
  17891. new Decrypter(encrypted, key, iv, function (err, bytes) {
  17892. self.postMessage(createTransferableMessage({
  17893. source: data.source,
  17894. decrypted: bytes
  17895. }), [bytes.buffer]);
  17896. });
  17897. /* eslint-enable */
  17898. };
  17899. }));
  17900. var Decrypter = factory(workerCode);
  17901. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  17902. /**
  17903. * Convert the properties of an HLS track into an audioTrackKind.
  17904. *
  17905. * @private
  17906. */
  17907. const audioTrackKind_ = properties => {
  17908. let kind = properties.default ? 'main' : 'alternative';
  17909. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  17910. kind = 'main-desc';
  17911. }
  17912. return kind;
  17913. };
  17914. /**
  17915. * Pause provided segment loader and playlist loader if active
  17916. *
  17917. * @param {SegmentLoader} segmentLoader
  17918. * SegmentLoader to pause
  17919. * @param {Object} mediaType
  17920. * Active media type
  17921. * @function stopLoaders
  17922. */
  17923. const stopLoaders = (segmentLoader, mediaType) => {
  17924. segmentLoader.abort();
  17925. segmentLoader.pause();
  17926. if (mediaType && mediaType.activePlaylistLoader) {
  17927. mediaType.activePlaylistLoader.pause();
  17928. mediaType.activePlaylistLoader = null;
  17929. }
  17930. };
  17931. /**
  17932. * Start loading provided segment loader and playlist loader
  17933. *
  17934. * @param {PlaylistLoader} playlistLoader
  17935. * PlaylistLoader to start loading
  17936. * @param {Object} mediaType
  17937. * Active media type
  17938. * @function startLoaders
  17939. */
  17940. const startLoaders = (playlistLoader, mediaType) => {
  17941. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  17942. // playlist loader
  17943. mediaType.activePlaylistLoader = playlistLoader;
  17944. playlistLoader.load();
  17945. };
  17946. /**
  17947. * Returns a function to be called when the media group changes. It performs a
  17948. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  17949. * change of group is merely a rendition switch of the same content at another encoding,
  17950. * rather than a change of content, such as switching audio from English to Spanish.
  17951. *
  17952. * @param {string} type
  17953. * MediaGroup type
  17954. * @param {Object} settings
  17955. * Object containing required information for media groups
  17956. * @return {Function}
  17957. * Handler for a non-destructive resync of SegmentLoader when the active media
  17958. * group changes.
  17959. * @function onGroupChanged
  17960. */
  17961. const onGroupChanged = (type, settings) => () => {
  17962. const {
  17963. segmentLoaders: {
  17964. [type]: segmentLoader,
  17965. main: mainSegmentLoader
  17966. },
  17967. mediaTypes: {
  17968. [type]: mediaType
  17969. }
  17970. } = settings;
  17971. const activeTrack = mediaType.activeTrack();
  17972. const activeGroup = mediaType.getActiveGroup();
  17973. const previousActiveLoader = mediaType.activePlaylistLoader;
  17974. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  17975. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  17976. return;
  17977. }
  17978. mediaType.lastGroup_ = activeGroup;
  17979. mediaType.lastTrack_ = activeTrack;
  17980. stopLoaders(segmentLoader, mediaType);
  17981. if (!activeGroup || activeGroup.isMainPlaylist) {
  17982. // there is no group active or active group is a main playlist and won't change
  17983. return;
  17984. }
  17985. if (!activeGroup.playlistLoader) {
  17986. if (previousActiveLoader) {
  17987. // The previous group had a playlist loader but the new active group does not
  17988. // this means we are switching from demuxed to muxed audio. In this case we want to
  17989. // do a destructive reset of the main segment loader and not restart the audio
  17990. // loaders.
  17991. mainSegmentLoader.resetEverything();
  17992. }
  17993. return;
  17994. } // Non-destructive resync
  17995. segmentLoader.resyncLoader();
  17996. startLoaders(activeGroup.playlistLoader, mediaType);
  17997. };
  17998. const onGroupChanging = (type, settings) => () => {
  17999. const {
  18000. segmentLoaders: {
  18001. [type]: segmentLoader
  18002. },
  18003. mediaTypes: {
  18004. [type]: mediaType
  18005. }
  18006. } = settings;
  18007. mediaType.lastGroup_ = null;
  18008. segmentLoader.abort();
  18009. segmentLoader.pause();
  18010. };
  18011. /**
  18012. * Returns a function to be called when the media track changes. It performs a
  18013. * destructive reset of the SegmentLoader to ensure we start loading as close to
  18014. * currentTime as possible.
  18015. *
  18016. * @param {string} type
  18017. * MediaGroup type
  18018. * @param {Object} settings
  18019. * Object containing required information for media groups
  18020. * @return {Function}
  18021. * Handler for a destructive reset of SegmentLoader when the active media
  18022. * track changes.
  18023. * @function onTrackChanged
  18024. */
  18025. const onTrackChanged = (type, settings) => () => {
  18026. const {
  18027. mainPlaylistLoader,
  18028. segmentLoaders: {
  18029. [type]: segmentLoader,
  18030. main: mainSegmentLoader
  18031. },
  18032. mediaTypes: {
  18033. [type]: mediaType
  18034. }
  18035. } = settings;
  18036. const activeTrack = mediaType.activeTrack();
  18037. const activeGroup = mediaType.getActiveGroup();
  18038. const previousActiveLoader = mediaType.activePlaylistLoader;
  18039. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  18040. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  18041. return;
  18042. }
  18043. mediaType.lastGroup_ = activeGroup;
  18044. mediaType.lastTrack_ = activeTrack;
  18045. stopLoaders(segmentLoader, mediaType);
  18046. if (!activeGroup) {
  18047. // there is no group active so we do not want to restart loaders
  18048. return;
  18049. }
  18050. if (activeGroup.isMainPlaylist) {
  18051. // track did not change, do nothing
  18052. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  18053. return;
  18054. }
  18055. const pc = settings.vhs.playlistController_;
  18056. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  18057. if (pc.media() === newPlaylist) {
  18058. return;
  18059. }
  18060. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  18061. mainPlaylistLoader.pause();
  18062. mainSegmentLoader.resetEverything();
  18063. pc.fastQualityChange_(newPlaylist);
  18064. return;
  18065. }
  18066. if (type === 'AUDIO') {
  18067. if (!activeGroup.playlistLoader) {
  18068. // when switching from demuxed audio/video to muxed audio/video (noted by no
  18069. // playlist loader for the audio group), we want to do a destructive reset of the
  18070. // main segment loader and not restart the audio loaders
  18071. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  18072. // it should be stopped
  18073. mainSegmentLoader.resetEverything();
  18074. return;
  18075. } // although the segment loader is an audio segment loader, call the setAudio
  18076. // function to ensure it is prepared to re-append the init segment (or handle other
  18077. // config changes)
  18078. segmentLoader.setAudio(true);
  18079. mainSegmentLoader.setAudio(false);
  18080. }
  18081. if (previousActiveLoader === activeGroup.playlistLoader) {
  18082. // Nothing has actually changed. This can happen because track change events can fire
  18083. // multiple times for a "single" change. One for enabling the new active track, and
  18084. // one for disabling the track that was active
  18085. startLoaders(activeGroup.playlistLoader, mediaType);
  18086. return;
  18087. }
  18088. if (segmentLoader.track) {
  18089. // For WebVTT, set the new text track in the segmentloader
  18090. segmentLoader.track(activeTrack);
  18091. } // destructive reset
  18092. segmentLoader.resetEverything();
  18093. startLoaders(activeGroup.playlistLoader, mediaType);
  18094. };
  18095. const onError = {
  18096. /**
  18097. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18098. * an error.
  18099. *
  18100. * @param {string} type
  18101. * MediaGroup type
  18102. * @param {Object} settings
  18103. * Object containing required information for media groups
  18104. * @return {Function}
  18105. * Error handler. Logs warning (or error if the playlist is excluded) to
  18106. * console and switches back to default audio track.
  18107. * @function onError.AUDIO
  18108. */
  18109. AUDIO: (type, settings) => () => {
  18110. const {
  18111. segmentLoaders: {
  18112. [type]: segmentLoader
  18113. },
  18114. mediaTypes: {
  18115. [type]: mediaType
  18116. },
  18117. excludePlaylist
  18118. } = settings;
  18119. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  18120. const activeTrack = mediaType.activeTrack();
  18121. const activeGroup = mediaType.activeGroup();
  18122. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  18123. const defaultTrack = mediaType.tracks[id];
  18124. if (activeTrack === defaultTrack) {
  18125. // Default track encountered an error. All we can do now is exclude the current
  18126. // rendition and hope another will switch audio groups
  18127. excludePlaylist({
  18128. error: {
  18129. message: 'Problem encountered loading the default audio track.'
  18130. }
  18131. });
  18132. return;
  18133. }
  18134. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  18135. for (const trackId in mediaType.tracks) {
  18136. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  18137. }
  18138. mediaType.onTrackChanged();
  18139. },
  18140. /**
  18141. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18142. * an error.
  18143. *
  18144. * @param {string} type
  18145. * MediaGroup type
  18146. * @param {Object} settings
  18147. * Object containing required information for media groups
  18148. * @return {Function}
  18149. * Error handler. Logs warning to console and disables the active subtitle track
  18150. * @function onError.SUBTITLES
  18151. */
  18152. SUBTITLES: (type, settings) => () => {
  18153. const {
  18154. segmentLoaders: {
  18155. [type]: segmentLoader
  18156. },
  18157. mediaTypes: {
  18158. [type]: mediaType
  18159. }
  18160. } = settings;
  18161. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  18162. stopLoaders(segmentLoader, mediaType);
  18163. const track = mediaType.activeTrack();
  18164. if (track) {
  18165. track.mode = 'disabled';
  18166. }
  18167. mediaType.onTrackChanged();
  18168. }
  18169. };
  18170. const setupListeners = {
  18171. /**
  18172. * Setup event listeners for audio playlist loader
  18173. *
  18174. * @param {string} type
  18175. * MediaGroup type
  18176. * @param {PlaylistLoader|null} playlistLoader
  18177. * PlaylistLoader to register listeners on
  18178. * @param {Object} settings
  18179. * Object containing required information for media groups
  18180. * @function setupListeners.AUDIO
  18181. */
  18182. AUDIO: (type, playlistLoader, settings) => {
  18183. if (!playlistLoader) {
  18184. // no playlist loader means audio will be muxed with the video
  18185. return;
  18186. }
  18187. const {
  18188. tech,
  18189. requestOptions,
  18190. segmentLoaders: {
  18191. [type]: segmentLoader
  18192. }
  18193. } = settings;
  18194. playlistLoader.on('loadedmetadata', () => {
  18195. const media = playlistLoader.media();
  18196. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  18197. // permits, start downloading segments
  18198. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  18199. segmentLoader.load();
  18200. }
  18201. });
  18202. playlistLoader.on('loadedplaylist', () => {
  18203. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  18204. if (!tech.paused()) {
  18205. segmentLoader.load();
  18206. }
  18207. });
  18208. playlistLoader.on('error', onError[type](type, settings));
  18209. },
  18210. /**
  18211. * Setup event listeners for subtitle playlist loader
  18212. *
  18213. * @param {string} type
  18214. * MediaGroup type
  18215. * @param {PlaylistLoader|null} playlistLoader
  18216. * PlaylistLoader to register listeners on
  18217. * @param {Object} settings
  18218. * Object containing required information for media groups
  18219. * @function setupListeners.SUBTITLES
  18220. */
  18221. SUBTITLES: (type, playlistLoader, settings) => {
  18222. const {
  18223. tech,
  18224. requestOptions,
  18225. segmentLoaders: {
  18226. [type]: segmentLoader
  18227. },
  18228. mediaTypes: {
  18229. [type]: mediaType
  18230. }
  18231. } = settings;
  18232. playlistLoader.on('loadedmetadata', () => {
  18233. const media = playlistLoader.media();
  18234. segmentLoader.playlist(media, requestOptions);
  18235. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  18236. // permits, start downloading segments
  18237. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  18238. segmentLoader.load();
  18239. }
  18240. });
  18241. playlistLoader.on('loadedplaylist', () => {
  18242. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  18243. if (!tech.paused()) {
  18244. segmentLoader.load();
  18245. }
  18246. });
  18247. playlistLoader.on('error', onError[type](type, settings));
  18248. }
  18249. };
  18250. const initialize = {
  18251. /**
  18252. * Setup PlaylistLoaders and AudioTracks for the audio groups
  18253. *
  18254. * @param {string} type
  18255. * MediaGroup type
  18256. * @param {Object} settings
  18257. * Object containing required information for media groups
  18258. * @function initialize.AUDIO
  18259. */
  18260. 'AUDIO': (type, settings) => {
  18261. const {
  18262. vhs,
  18263. sourceType,
  18264. segmentLoaders: {
  18265. [type]: segmentLoader
  18266. },
  18267. requestOptions,
  18268. main: {
  18269. mediaGroups
  18270. },
  18271. mediaTypes: {
  18272. [type]: {
  18273. groups,
  18274. tracks,
  18275. logger_
  18276. }
  18277. },
  18278. mainPlaylistLoader
  18279. } = settings;
  18280. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  18281. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  18282. mediaGroups[type] = {
  18283. main: {
  18284. default: {
  18285. default: true
  18286. }
  18287. }
  18288. };
  18289. if (audioOnlyMain) {
  18290. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  18291. }
  18292. }
  18293. for (const groupId in mediaGroups[type]) {
  18294. if (!groups[groupId]) {
  18295. groups[groupId] = [];
  18296. }
  18297. for (const variantLabel in mediaGroups[type][groupId]) {
  18298. let properties = mediaGroups[type][groupId][variantLabel];
  18299. let playlistLoader;
  18300. if (audioOnlyMain) {
  18301. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  18302. properties.isMainPlaylist = true;
  18303. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  18304. // use the resolved media playlist object
  18305. } else if (sourceType === 'vhs-json' && properties.playlists) {
  18306. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  18307. } else if (properties.resolvedUri) {
  18308. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  18309. // should we even have properties.playlists in this check.
  18310. } else if (properties.playlists && sourceType === 'dash') {
  18311. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  18312. } else {
  18313. // no resolvedUri means the audio is muxed with the video when using this
  18314. // audio track
  18315. playlistLoader = null;
  18316. }
  18317. properties = merge({
  18318. id: variantLabel,
  18319. playlistLoader
  18320. }, properties);
  18321. setupListeners[type](type, properties.playlistLoader, settings);
  18322. groups[groupId].push(properties);
  18323. if (typeof tracks[variantLabel] === 'undefined') {
  18324. const track = new videojs.AudioTrack({
  18325. id: variantLabel,
  18326. kind: audioTrackKind_(properties),
  18327. enabled: false,
  18328. language: properties.language,
  18329. default: properties.default,
  18330. label: variantLabel
  18331. });
  18332. tracks[variantLabel] = track;
  18333. }
  18334. }
  18335. } // setup single error event handler for the segment loader
  18336. segmentLoader.on('error', onError[type](type, settings));
  18337. },
  18338. /**
  18339. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  18340. *
  18341. * @param {string} type
  18342. * MediaGroup type
  18343. * @param {Object} settings
  18344. * Object containing required information for media groups
  18345. * @function initialize.SUBTITLES
  18346. */
  18347. 'SUBTITLES': (type, settings) => {
  18348. const {
  18349. tech,
  18350. vhs,
  18351. sourceType,
  18352. segmentLoaders: {
  18353. [type]: segmentLoader
  18354. },
  18355. requestOptions,
  18356. main: {
  18357. mediaGroups
  18358. },
  18359. mediaTypes: {
  18360. [type]: {
  18361. groups,
  18362. tracks
  18363. }
  18364. },
  18365. mainPlaylistLoader
  18366. } = settings;
  18367. for (const groupId in mediaGroups[type]) {
  18368. if (!groups[groupId]) {
  18369. groups[groupId] = [];
  18370. }
  18371. for (const variantLabel in mediaGroups[type][groupId]) {
  18372. if (mediaGroups[type][groupId][variantLabel].forced) {
  18373. // Subtitle playlists with the forced attribute are not selectable in Safari.
  18374. // According to Apple's HLS Authoring Specification:
  18375. // If content has forced subtitles and regular subtitles in a given language,
  18376. // the regular subtitles track in that language MUST contain both the forced
  18377. // subtitles and the regular subtitles for that language.
  18378. // Because of this requirement and that Safari does not add forced subtitles,
  18379. // forced subtitles are skipped here to maintain consistent experience across
  18380. // all platforms
  18381. continue;
  18382. }
  18383. let properties = mediaGroups[type][groupId][variantLabel];
  18384. let playlistLoader;
  18385. if (sourceType === 'hls') {
  18386. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  18387. } else if (sourceType === 'dash') {
  18388. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  18389. if (!playlists.length) {
  18390. return;
  18391. }
  18392. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  18393. } else if (sourceType === 'vhs-json') {
  18394. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  18395. // as provided, otherwise use the resolved URI to load the playlist
  18396. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  18397. }
  18398. properties = merge({
  18399. id: variantLabel,
  18400. playlistLoader
  18401. }, properties);
  18402. setupListeners[type](type, properties.playlistLoader, settings);
  18403. groups[groupId].push(properties);
  18404. if (typeof tracks[variantLabel] === 'undefined') {
  18405. const track = tech.addRemoteTextTrack({
  18406. id: variantLabel,
  18407. kind: 'subtitles',
  18408. default: properties.default && properties.autoselect,
  18409. language: properties.language,
  18410. label: variantLabel
  18411. }, false).track;
  18412. tracks[variantLabel] = track;
  18413. }
  18414. }
  18415. } // setup single error event handler for the segment loader
  18416. segmentLoader.on('error', onError[type](type, settings));
  18417. },
  18418. /**
  18419. * Setup TextTracks for the closed-caption groups
  18420. *
  18421. * @param {String} type
  18422. * MediaGroup type
  18423. * @param {Object} settings
  18424. * Object containing required information for media groups
  18425. * @function initialize['CLOSED-CAPTIONS']
  18426. */
  18427. 'CLOSED-CAPTIONS': (type, settings) => {
  18428. const {
  18429. tech,
  18430. main: {
  18431. mediaGroups
  18432. },
  18433. mediaTypes: {
  18434. [type]: {
  18435. groups,
  18436. tracks
  18437. }
  18438. }
  18439. } = settings;
  18440. for (const groupId in mediaGroups[type]) {
  18441. if (!groups[groupId]) {
  18442. groups[groupId] = [];
  18443. }
  18444. for (const variantLabel in mediaGroups[type][groupId]) {
  18445. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  18446. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  18447. continue;
  18448. }
  18449. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  18450. let newProps = {
  18451. label: variantLabel,
  18452. language: properties.language,
  18453. instreamId: properties.instreamId,
  18454. default: properties.default && properties.autoselect
  18455. };
  18456. if (captionServices[newProps.instreamId]) {
  18457. newProps = merge(newProps, captionServices[newProps.instreamId]);
  18458. }
  18459. if (newProps.default === undefined) {
  18460. delete newProps.default;
  18461. } // No PlaylistLoader is required for Closed-Captions because the captions are
  18462. // embedded within the video stream
  18463. groups[groupId].push(merge({
  18464. id: variantLabel
  18465. }, properties));
  18466. if (typeof tracks[variantLabel] === 'undefined') {
  18467. const track = tech.addRemoteTextTrack({
  18468. id: newProps.instreamId,
  18469. kind: 'captions',
  18470. default: newProps.default,
  18471. language: newProps.language,
  18472. label: newProps.label
  18473. }, false).track;
  18474. tracks[variantLabel] = track;
  18475. }
  18476. }
  18477. }
  18478. }
  18479. };
  18480. const groupMatch = (list, media) => {
  18481. for (let i = 0; i < list.length; i++) {
  18482. if (playlistMatch(media, list[i])) {
  18483. return true;
  18484. }
  18485. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  18486. return true;
  18487. }
  18488. }
  18489. return false;
  18490. };
  18491. /**
  18492. * Returns a function used to get the active group of the provided type
  18493. *
  18494. * @param {string} type
  18495. * MediaGroup type
  18496. * @param {Object} settings
  18497. * Object containing required information for media groups
  18498. * @return {Function}
  18499. * Function that returns the active media group for the provided type. Takes an
  18500. * optional parameter {TextTrack} track. If no track is provided, a list of all
  18501. * variants in the group, otherwise the variant corresponding to the provided
  18502. * track is returned.
  18503. * @function activeGroup
  18504. */
  18505. const activeGroup = (type, settings) => track => {
  18506. const {
  18507. mainPlaylistLoader,
  18508. mediaTypes: {
  18509. [type]: {
  18510. groups
  18511. }
  18512. }
  18513. } = settings;
  18514. const media = mainPlaylistLoader.media();
  18515. if (!media) {
  18516. return null;
  18517. }
  18518. let variants = null; // set to variants to main media active group
  18519. if (media.attributes[type]) {
  18520. variants = groups[media.attributes[type]];
  18521. }
  18522. const groupKeys = Object.keys(groups);
  18523. if (!variants) {
  18524. // find the mainPlaylistLoader media
  18525. // that is in a media group if we are dealing
  18526. // with audio only
  18527. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  18528. for (let i = 0; i < groupKeys.length; i++) {
  18529. const groupPropertyList = groups[groupKeys[i]];
  18530. if (groupMatch(groupPropertyList, media)) {
  18531. variants = groupPropertyList;
  18532. break;
  18533. }
  18534. } // use the main group if it exists
  18535. } else if (groups.main) {
  18536. variants = groups.main; // only one group, use that one
  18537. } else if (groupKeys.length === 1) {
  18538. variants = groups[groupKeys[0]];
  18539. }
  18540. }
  18541. if (typeof track === 'undefined') {
  18542. return variants;
  18543. }
  18544. if (track === null || !variants) {
  18545. // An active track was specified so a corresponding group is expected. track === null
  18546. // means no track is currently active so there is no corresponding group
  18547. return null;
  18548. }
  18549. return variants.filter(props => props.id === track.id)[0] || null;
  18550. };
  18551. const activeTrack = {
  18552. /**
  18553. * Returns a function used to get the active track of type provided
  18554. *
  18555. * @param {string} type
  18556. * MediaGroup type
  18557. * @param {Object} settings
  18558. * Object containing required information for media groups
  18559. * @return {Function}
  18560. * Function that returns the active media track for the provided type. Returns
  18561. * null if no track is active
  18562. * @function activeTrack.AUDIO
  18563. */
  18564. AUDIO: (type, settings) => () => {
  18565. const {
  18566. mediaTypes: {
  18567. [type]: {
  18568. tracks
  18569. }
  18570. }
  18571. } = settings;
  18572. for (const id in tracks) {
  18573. if (tracks[id].enabled) {
  18574. return tracks[id];
  18575. }
  18576. }
  18577. return null;
  18578. },
  18579. /**
  18580. * Returns a function used to get the active track of type provided
  18581. *
  18582. * @param {string} type
  18583. * MediaGroup type
  18584. * @param {Object} settings
  18585. * Object containing required information for media groups
  18586. * @return {Function}
  18587. * Function that returns the active media track for the provided type. Returns
  18588. * null if no track is active
  18589. * @function activeTrack.SUBTITLES
  18590. */
  18591. SUBTITLES: (type, settings) => () => {
  18592. const {
  18593. mediaTypes: {
  18594. [type]: {
  18595. tracks
  18596. }
  18597. }
  18598. } = settings;
  18599. for (const id in tracks) {
  18600. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  18601. return tracks[id];
  18602. }
  18603. }
  18604. return null;
  18605. }
  18606. };
  18607. const getActiveGroup = (type, {
  18608. mediaTypes
  18609. }) => () => {
  18610. const activeTrack_ = mediaTypes[type].activeTrack();
  18611. if (!activeTrack_) {
  18612. return null;
  18613. }
  18614. return mediaTypes[type].activeGroup(activeTrack_);
  18615. };
  18616. /**
  18617. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  18618. * Closed-Captions) specified in the main manifest.
  18619. *
  18620. * @param {Object} settings
  18621. * Object containing required information for setting up the media groups
  18622. * @param {Tech} settings.tech
  18623. * The tech of the player
  18624. * @param {Object} settings.requestOptions
  18625. * XHR request options used by the segment loaders
  18626. * @param {PlaylistLoader} settings.mainPlaylistLoader
  18627. * PlaylistLoader for the main source
  18628. * @param {VhsHandler} settings.vhs
  18629. * VHS SourceHandler
  18630. * @param {Object} settings.main
  18631. * The parsed main manifest
  18632. * @param {Object} settings.mediaTypes
  18633. * Object to store the loaders, tracks, and utility methods for each media type
  18634. * @param {Function} settings.excludePlaylist
  18635. * Excludes the current rendition and forces a rendition switch.
  18636. * @function setupMediaGroups
  18637. */
  18638. const setupMediaGroups = settings => {
  18639. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  18640. initialize[type](type, settings);
  18641. });
  18642. const {
  18643. mediaTypes,
  18644. mainPlaylistLoader,
  18645. tech,
  18646. vhs,
  18647. segmentLoaders: {
  18648. ['AUDIO']: audioSegmentLoader,
  18649. main: mainSegmentLoader
  18650. }
  18651. } = settings; // setup active group and track getters and change event handlers
  18652. ['AUDIO', 'SUBTITLES'].forEach(type => {
  18653. mediaTypes[type].activeGroup = activeGroup(type, settings);
  18654. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  18655. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  18656. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  18657. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  18658. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  18659. }); // DO NOT enable the default subtitle or caption track.
  18660. // DO enable the default audio track
  18661. const audioGroup = mediaTypes.AUDIO.activeGroup();
  18662. if (audioGroup) {
  18663. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  18664. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  18665. mediaTypes.AUDIO.onGroupChanged();
  18666. mediaTypes.AUDIO.onTrackChanged();
  18667. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  18668. // track is changed, but needs to be handled here since the track may not be considered
  18669. // changed on the first call to onTrackChanged
  18670. if (!activeAudioGroup.playlistLoader) {
  18671. // either audio is muxed with video or the stream is audio only
  18672. mainSegmentLoader.setAudio(true);
  18673. } else {
  18674. // audio is demuxed
  18675. mainSegmentLoader.setAudio(false);
  18676. audioSegmentLoader.setAudio(true);
  18677. }
  18678. }
  18679. mainPlaylistLoader.on('mediachange', () => {
  18680. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  18681. });
  18682. mainPlaylistLoader.on('mediachanging', () => {
  18683. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  18684. }); // custom audio track change event handler for usage event
  18685. const onAudioTrackChanged = () => {
  18686. mediaTypes.AUDIO.onTrackChanged();
  18687. tech.trigger({
  18688. type: 'usage',
  18689. name: 'vhs-audio-change'
  18690. });
  18691. };
  18692. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  18693. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  18694. vhs.on('dispose', () => {
  18695. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  18696. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  18697. }); // clear existing audio tracks and add the ones we just created
  18698. tech.clearTracks('audio');
  18699. for (const id in mediaTypes.AUDIO.tracks) {
  18700. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  18701. }
  18702. };
  18703. /**
  18704. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  18705. * media type
  18706. *
  18707. * @return {Object}
  18708. * Object to store the loaders, tracks, and utility methods for each media type
  18709. * @function createMediaTypes
  18710. */
  18711. const createMediaTypes = () => {
  18712. const mediaTypes = {};
  18713. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  18714. mediaTypes[type] = {
  18715. groups: {},
  18716. tracks: {},
  18717. activePlaylistLoader: null,
  18718. activeGroup: noop,
  18719. activeTrack: noop,
  18720. getActiveGroup: noop,
  18721. onGroupChanged: noop,
  18722. onTrackChanged: noop,
  18723. lastTrack_: null,
  18724. logger_: logger(`MediaGroups[${type}]`)
  18725. };
  18726. });
  18727. return mediaTypes;
  18728. };
  18729. /**
  18730. * @file playlist-controller.js
  18731. */
  18732. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  18733. let Vhs$1; // SegmentLoader stats that need to have each loader's
  18734. // values summed to calculate the final value
  18735. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  18736. const sumLoaderStat = function (stat) {
  18737. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  18738. };
  18739. const shouldSwitchToMedia = function ({
  18740. currentPlaylist,
  18741. buffered,
  18742. currentTime,
  18743. nextPlaylist,
  18744. bufferLowWaterLine,
  18745. bufferHighWaterLine,
  18746. duration,
  18747. bufferBasedABR,
  18748. log
  18749. }) {
  18750. // we have no other playlist to switch to
  18751. if (!nextPlaylist) {
  18752. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  18753. return false;
  18754. }
  18755. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  18756. if (!currentPlaylist) {
  18757. log(`${sharedLogLine} as current playlist is not set`);
  18758. return true;
  18759. } // no need to switch if playlist is the same
  18760. if (nextPlaylist.id === currentPlaylist.id) {
  18761. return false;
  18762. } // determine if current time is in a buffered range.
  18763. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  18764. // This is because in LIVE, the player plays 3 segments from the end of the
  18765. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  18766. // in those segments, a viewer will never experience a rendition upswitch.
  18767. if (!currentPlaylist.endList) {
  18768. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  18769. // doubles the time to first playback.
  18770. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  18771. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  18772. return false;
  18773. }
  18774. log(`${sharedLogLine} as current playlist is live`);
  18775. return true;
  18776. }
  18777. const forwardBuffer = timeAheadOf(buffered, currentTime);
  18778. 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
  18779. // duration is below the max potential low water line
  18780. if (duration < maxBufferLowWaterLine) {
  18781. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  18782. return true;
  18783. }
  18784. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  18785. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  18786. // we can switch down
  18787. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  18788. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  18789. if (bufferBasedABR) {
  18790. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  18791. }
  18792. log(logLine);
  18793. return true;
  18794. } // and if our buffer is higher than the low water line,
  18795. // we can switch up
  18796. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  18797. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  18798. if (bufferBasedABR) {
  18799. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  18800. }
  18801. log(logLine);
  18802. return true;
  18803. }
  18804. log(`not ${sharedLogLine} as no switching criteria met`);
  18805. return false;
  18806. };
  18807. /**
  18808. * the main playlist controller controller all interactons
  18809. * between playlists and segmentloaders. At this time this mainly
  18810. * involves a main playlist and a series of audio playlists
  18811. * if they are available
  18812. *
  18813. * @class PlaylistController
  18814. * @extends videojs.EventTarget
  18815. */
  18816. class PlaylistController extends videojs.EventTarget {
  18817. constructor(options) {
  18818. super();
  18819. const {
  18820. src,
  18821. withCredentials,
  18822. tech,
  18823. bandwidth,
  18824. externVhs,
  18825. useCueTags,
  18826. playlistExclusionDuration,
  18827. enableLowInitialPlaylist,
  18828. sourceType,
  18829. cacheEncryptionKeys,
  18830. bufferBasedABR,
  18831. leastPixelDiffSelector,
  18832. captionServices
  18833. } = options;
  18834. if (!src) {
  18835. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  18836. }
  18837. let {
  18838. maxPlaylistRetries
  18839. } = options;
  18840. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  18841. maxPlaylistRetries = Infinity;
  18842. }
  18843. Vhs$1 = externVhs;
  18844. this.bufferBasedABR = Boolean(bufferBasedABR);
  18845. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  18846. this.withCredentials = withCredentials;
  18847. this.tech_ = tech;
  18848. this.vhs_ = tech.vhs;
  18849. this.sourceType_ = sourceType;
  18850. this.useCueTags_ = useCueTags;
  18851. this.playlistExclusionDuration = playlistExclusionDuration;
  18852. this.maxPlaylistRetries = maxPlaylistRetries;
  18853. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  18854. if (this.useCueTags_) {
  18855. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  18856. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  18857. }
  18858. this.requestOptions_ = {
  18859. withCredentials,
  18860. maxPlaylistRetries,
  18861. timeout: null
  18862. };
  18863. this.on('error', this.pauseLoading);
  18864. this.mediaTypes_ = createMediaTypes();
  18865. this.mediaSource = new window$1.MediaSource();
  18866. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  18867. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  18868. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  18869. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  18870. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  18871. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  18872. // everything, and the MediaSource should not be detached without a proper disposal
  18873. this.seekable_ = createTimeRanges();
  18874. this.hasPlayed_ = false;
  18875. this.syncController_ = new SyncController(options);
  18876. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  18877. kind: 'metadata',
  18878. label: 'segment-metadata'
  18879. }, false).track;
  18880. this.decrypter_ = new Decrypter();
  18881. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  18882. this.inbandTextTracks_ = {};
  18883. this.timelineChangeController_ = new TimelineChangeController();
  18884. const segmentLoaderSettings = {
  18885. vhs: this.vhs_,
  18886. parse708captions: options.parse708captions,
  18887. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  18888. captionServices,
  18889. mediaSource: this.mediaSource,
  18890. currentTime: this.tech_.currentTime.bind(this.tech_),
  18891. seekable: () => this.seekable(),
  18892. seeking: () => this.tech_.seeking(),
  18893. duration: () => this.duration(),
  18894. hasPlayed: () => this.hasPlayed_,
  18895. goalBufferLength: () => this.goalBufferLength(),
  18896. bandwidth,
  18897. syncController: this.syncController_,
  18898. decrypter: this.decrypter_,
  18899. sourceType: this.sourceType_,
  18900. inbandTextTracks: this.inbandTextTracks_,
  18901. cacheEncryptionKeys,
  18902. sourceUpdater: this.sourceUpdater_,
  18903. timelineChangeController: this.timelineChangeController_,
  18904. exactManifestTimings: options.exactManifestTimings
  18905. }; // The source type check not only determines whether a special DASH playlist loader
  18906. // should be used, but also covers the case where the provided src is a vhs-json
  18907. // manifest object (instead of a URL). In the case of vhs-json, the default
  18908. // PlaylistLoader should be used.
  18909. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  18910. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  18911. // combined audio/video or just video when alternate audio track is selected
  18912. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  18913. segmentMetadataTrack: this.segmentMetadataTrack_,
  18914. loaderType: 'main'
  18915. }), options); // alternate audio track
  18916. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  18917. loaderType: 'audio'
  18918. }), options);
  18919. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  18920. loaderType: 'vtt',
  18921. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  18922. loadVttJs: () => new Promise((resolve, reject) => {
  18923. function onLoad() {
  18924. tech.off('vttjserror', onError);
  18925. resolve();
  18926. }
  18927. function onError() {
  18928. tech.off('vttjsloaded', onLoad);
  18929. reject();
  18930. }
  18931. tech.one('vttjsloaded', onLoad);
  18932. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  18933. tech.addWebVttScript_();
  18934. })
  18935. }), options);
  18936. this.setupSegmentLoaderListeners_();
  18937. if (this.bufferBasedABR) {
  18938. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  18939. this.tech_.on('pause', () => this.stopABRTimer_());
  18940. this.tech_.on('play', () => this.startABRTimer_());
  18941. } // Create SegmentLoader stat-getters
  18942. // mediaRequests_
  18943. // mediaRequestsAborted_
  18944. // mediaRequestsTimedout_
  18945. // mediaRequestsErrored_
  18946. // mediaTransferDuration_
  18947. // mediaBytesTransferred_
  18948. // mediaAppends_
  18949. loaderStats.forEach(stat => {
  18950. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  18951. });
  18952. this.logger_ = logger('pc');
  18953. this.triggeredFmp4Usage = false;
  18954. if (this.tech_.preload() === 'none') {
  18955. this.loadOnPlay_ = () => {
  18956. this.loadOnPlay_ = null;
  18957. this.mainPlaylistLoader_.load();
  18958. };
  18959. this.tech_.one('play', this.loadOnPlay_);
  18960. } else {
  18961. this.mainPlaylistLoader_.load();
  18962. }
  18963. this.timeToLoadedData__ = -1;
  18964. this.mainAppendsToLoadedData__ = -1;
  18965. this.audioAppendsToLoadedData__ = -1;
  18966. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  18967. this.tech_.one(event, () => {
  18968. const timeToLoadedDataStart = Date.now();
  18969. this.tech_.one('loadeddata', () => {
  18970. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  18971. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  18972. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  18973. });
  18974. });
  18975. }
  18976. mainAppendsToLoadedData_() {
  18977. return this.mainAppendsToLoadedData__;
  18978. }
  18979. audioAppendsToLoadedData_() {
  18980. return this.audioAppendsToLoadedData__;
  18981. }
  18982. appendsToLoadedData_() {
  18983. const main = this.mainAppendsToLoadedData_();
  18984. const audio = this.audioAppendsToLoadedData_();
  18985. if (main === -1 || audio === -1) {
  18986. return -1;
  18987. }
  18988. return main + audio;
  18989. }
  18990. timeToLoadedData_() {
  18991. return this.timeToLoadedData__;
  18992. }
  18993. /**
  18994. * Run selectPlaylist and switch to the new playlist if we should
  18995. *
  18996. * @param {string} [reason=abr] a reason for why the ABR check is made
  18997. * @private
  18998. */
  18999. checkABR_(reason = 'abr') {
  19000. const nextPlaylist = this.selectPlaylist();
  19001. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  19002. this.switchMedia_(nextPlaylist, reason);
  19003. }
  19004. }
  19005. switchMedia_(playlist, cause, delay) {
  19006. const oldMedia = this.media();
  19007. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  19008. const newId = playlist.id || playlist.uri;
  19009. if (oldId && oldId !== newId) {
  19010. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  19011. this.tech_.trigger({
  19012. type: 'usage',
  19013. name: `vhs-rendition-change-${cause}`
  19014. });
  19015. }
  19016. this.mainPlaylistLoader_.media(playlist, delay);
  19017. }
  19018. /**
  19019. * Start a timer that periodically calls checkABR_
  19020. *
  19021. * @private
  19022. */
  19023. startABRTimer_() {
  19024. this.stopABRTimer_();
  19025. this.abrTimer_ = window$1.setInterval(() => this.checkABR_(), 250);
  19026. }
  19027. /**
  19028. * Stop the timer that periodically calls checkABR_
  19029. *
  19030. * @private
  19031. */
  19032. stopABRTimer_() {
  19033. // if we're scrubbing, we don't need to pause.
  19034. // This getter will be added to Video.js in version 7.11.
  19035. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  19036. return;
  19037. }
  19038. window$1.clearInterval(this.abrTimer_);
  19039. this.abrTimer_ = null;
  19040. }
  19041. /**
  19042. * Get a list of playlists for the currently selected audio playlist
  19043. *
  19044. * @return {Array} the array of audio playlists
  19045. */
  19046. getAudioTrackPlaylists_() {
  19047. const main = this.main();
  19048. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  19049. // assume that the audio tracks are contained in main
  19050. // playlist array, use that or an empty array.
  19051. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  19052. return defaultPlaylists;
  19053. }
  19054. const AUDIO = main.mediaGroups.AUDIO;
  19055. const groupKeys = Object.keys(AUDIO);
  19056. let track; // get the current active track
  19057. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  19058. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  19059. } else {
  19060. // default group is `main` or just the first group.
  19061. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  19062. for (const label in defaultGroup) {
  19063. if (defaultGroup[label].default) {
  19064. track = {
  19065. label
  19066. };
  19067. break;
  19068. }
  19069. }
  19070. } // no active track no playlists.
  19071. if (!track) {
  19072. return defaultPlaylists;
  19073. }
  19074. const playlists = []; // get all of the playlists that are possible for the
  19075. // active track.
  19076. for (const group in AUDIO) {
  19077. if (AUDIO[group][track.label]) {
  19078. const properties = AUDIO[group][track.label];
  19079. if (properties.playlists && properties.playlists.length) {
  19080. playlists.push.apply(playlists, properties.playlists);
  19081. } else if (properties.uri) {
  19082. playlists.push(properties);
  19083. } else if (main.playlists.length) {
  19084. // if an audio group does not have a uri
  19085. // see if we have main playlists that use it as a group.
  19086. // if we do then add those to the playlists list.
  19087. for (let i = 0; i < main.playlists.length; i++) {
  19088. const playlist = main.playlists[i];
  19089. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  19090. playlists.push(playlist);
  19091. }
  19092. }
  19093. }
  19094. }
  19095. }
  19096. if (!playlists.length) {
  19097. return defaultPlaylists;
  19098. }
  19099. return playlists;
  19100. }
  19101. /**
  19102. * Register event handlers on the main playlist loader. A helper
  19103. * function for construction time.
  19104. *
  19105. * @private
  19106. */
  19107. setupMainPlaylistLoaderListeners_() {
  19108. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  19109. const media = this.mainPlaylistLoader_.media();
  19110. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  19111. // timeout the request.
  19112. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  19113. this.requestOptions_.timeout = 0;
  19114. } else {
  19115. this.requestOptions_.timeout = requestTimeout;
  19116. } // if this isn't a live video and preload permits, start
  19117. // downloading segments
  19118. if (media.endList && this.tech_.preload() !== 'none') {
  19119. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  19120. this.mainSegmentLoader_.load();
  19121. }
  19122. setupMediaGroups({
  19123. sourceType: this.sourceType_,
  19124. segmentLoaders: {
  19125. AUDIO: this.audioSegmentLoader_,
  19126. SUBTITLES: this.subtitleSegmentLoader_,
  19127. main: this.mainSegmentLoader_
  19128. },
  19129. tech: this.tech_,
  19130. requestOptions: this.requestOptions_,
  19131. mainPlaylistLoader: this.mainPlaylistLoader_,
  19132. vhs: this.vhs_,
  19133. main: this.main(),
  19134. mediaTypes: this.mediaTypes_,
  19135. excludePlaylist: this.excludePlaylist.bind(this)
  19136. });
  19137. this.triggerPresenceUsage_(this.main(), media);
  19138. this.setupFirstPlay();
  19139. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  19140. this.trigger('selectedinitialmedia');
  19141. } else {
  19142. // We must wait for the active audio playlist loader to
  19143. // finish setting up before triggering this event so the
  19144. // representations API and EME setup is correct
  19145. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  19146. this.trigger('selectedinitialmedia');
  19147. });
  19148. }
  19149. });
  19150. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  19151. if (this.loadOnPlay_) {
  19152. this.tech_.off('play', this.loadOnPlay_);
  19153. }
  19154. let updatedPlaylist = this.mainPlaylistLoader_.media();
  19155. if (!updatedPlaylist) {
  19156. // exclude any variants that are not supported by the browser before selecting
  19157. // an initial media as the playlist selectors do not consider browser support
  19158. this.excludeUnsupportedVariants_();
  19159. let selectedMedia;
  19160. if (this.enableLowInitialPlaylist) {
  19161. selectedMedia = this.selectInitialPlaylist();
  19162. }
  19163. if (!selectedMedia) {
  19164. selectedMedia = this.selectPlaylist();
  19165. }
  19166. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  19167. return;
  19168. }
  19169. this.initialMedia_ = selectedMedia;
  19170. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  19171. // fire again since the playlist will be requested. In the case of vhs-json
  19172. // (where the manifest object is provided as the source), when the media
  19173. // playlist's `segments` list is already available, a media playlist won't be
  19174. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  19175. // called on its own here.
  19176. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  19177. if (!haveJsonSource) {
  19178. return;
  19179. }
  19180. updatedPlaylist = this.initialMedia_;
  19181. }
  19182. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  19183. });
  19184. this.mainPlaylistLoader_.on('error', () => {
  19185. const error = this.mainPlaylistLoader_.error;
  19186. this.excludePlaylist({
  19187. playlistToExclude: error.playlist,
  19188. error
  19189. });
  19190. });
  19191. this.mainPlaylistLoader_.on('mediachanging', () => {
  19192. this.mainSegmentLoader_.abort();
  19193. this.mainSegmentLoader_.pause();
  19194. });
  19195. this.mainPlaylistLoader_.on('mediachange', () => {
  19196. const media = this.mainPlaylistLoader_.media();
  19197. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  19198. // timeout the request.
  19199. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  19200. this.requestOptions_.timeout = 0;
  19201. } else {
  19202. this.requestOptions_.timeout = requestTimeout;
  19203. }
  19204. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  19205. // that the segments have changed in some way and use that to
  19206. // update the SegmentLoader instead of doing it twice here and
  19207. // on `loadedplaylist`
  19208. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  19209. this.mainSegmentLoader_.load();
  19210. this.tech_.trigger({
  19211. type: 'mediachange',
  19212. bubbles: true
  19213. });
  19214. });
  19215. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  19216. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  19217. // excluded for not-changing. We likely just have a really slowly updating
  19218. // playlist.
  19219. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  19220. return;
  19221. }
  19222. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  19223. if (playlistOutdated) {
  19224. // Playlist has stopped updating and we're stuck at its end. Try to
  19225. // exclude it and switch to another playlist in the hope that that
  19226. // one is updating (and give the player a chance to re-adjust to the
  19227. // safe live point).
  19228. this.excludePlaylist({
  19229. error: {
  19230. message: 'Playlist no longer updating.',
  19231. reason: 'playlist-unchanged'
  19232. }
  19233. }); // useful for monitoring QoS
  19234. this.tech_.trigger('playliststuck');
  19235. }
  19236. });
  19237. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  19238. this.tech_.trigger({
  19239. type: 'usage',
  19240. name: 'vhs-rendition-disabled'
  19241. });
  19242. });
  19243. this.mainPlaylistLoader_.on('renditionenabled', () => {
  19244. this.tech_.trigger({
  19245. type: 'usage',
  19246. name: 'vhs-rendition-enabled'
  19247. });
  19248. });
  19249. }
  19250. /**
  19251. * Given an updated media playlist (whether it was loaded for the first time, or
  19252. * refreshed for live playlists), update any relevant properties and state to reflect
  19253. * changes in the media that should be accounted for (e.g., cues and duration).
  19254. *
  19255. * @param {Object} updatedPlaylist the updated media playlist object
  19256. *
  19257. * @private
  19258. */
  19259. handleUpdatedMediaPlaylist(updatedPlaylist) {
  19260. if (this.useCueTags_) {
  19261. this.updateAdCues_(updatedPlaylist);
  19262. } // TODO: Create a new event on the PlaylistLoader that signals
  19263. // that the segments have changed in some way and use that to
  19264. // update the SegmentLoader instead of doing it twice here and
  19265. // on `mediachange`
  19266. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  19267. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  19268. // as it is possible that it was temporarily stopped while waiting for
  19269. // a playlist (e.g., in case the playlist errored and we re-requested it).
  19270. if (!this.tech_.paused()) {
  19271. this.mainSegmentLoader_.load();
  19272. if (this.audioSegmentLoader_) {
  19273. this.audioSegmentLoader_.load();
  19274. }
  19275. }
  19276. }
  19277. /**
  19278. * A helper function for triggerring presence usage events once per source
  19279. *
  19280. * @private
  19281. */
  19282. triggerPresenceUsage_(main, media) {
  19283. const mediaGroups = main.mediaGroups || {};
  19284. let defaultDemuxed = true;
  19285. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  19286. for (const mediaGroup in mediaGroups.AUDIO) {
  19287. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  19288. const properties = mediaGroups.AUDIO[mediaGroup][label];
  19289. if (!properties.uri) {
  19290. defaultDemuxed = false;
  19291. }
  19292. }
  19293. }
  19294. if (defaultDemuxed) {
  19295. this.tech_.trigger({
  19296. type: 'usage',
  19297. name: 'vhs-demuxed'
  19298. });
  19299. }
  19300. if (Object.keys(mediaGroups.SUBTITLES).length) {
  19301. this.tech_.trigger({
  19302. type: 'usage',
  19303. name: 'vhs-webvtt'
  19304. });
  19305. }
  19306. if (Vhs$1.Playlist.isAes(media)) {
  19307. this.tech_.trigger({
  19308. type: 'usage',
  19309. name: 'vhs-aes'
  19310. });
  19311. }
  19312. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  19313. this.tech_.trigger({
  19314. type: 'usage',
  19315. name: 'vhs-alternate-audio'
  19316. });
  19317. }
  19318. if (this.useCueTags_) {
  19319. this.tech_.trigger({
  19320. type: 'usage',
  19321. name: 'vhs-playlist-cue-tags'
  19322. });
  19323. }
  19324. }
  19325. shouldSwitchToMedia_(nextPlaylist) {
  19326. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  19327. const currentTime = this.tech_.currentTime();
  19328. const bufferLowWaterLine = this.bufferLowWaterLine();
  19329. const bufferHighWaterLine = this.bufferHighWaterLine();
  19330. const buffered = this.tech_.buffered();
  19331. return shouldSwitchToMedia({
  19332. buffered,
  19333. currentTime,
  19334. currentPlaylist,
  19335. nextPlaylist,
  19336. bufferLowWaterLine,
  19337. bufferHighWaterLine,
  19338. duration: this.duration(),
  19339. bufferBasedABR: this.bufferBasedABR,
  19340. log: this.logger_
  19341. });
  19342. }
  19343. /**
  19344. * Register event handlers on the segment loaders. A helper function
  19345. * for construction time.
  19346. *
  19347. * @private
  19348. */
  19349. setupSegmentLoaderListeners_() {
  19350. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  19351. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  19352. // useful to check to see if a rendition switch should be made.
  19353. this.checkABR_('bandwidthupdate');
  19354. this.tech_.trigger('bandwidthupdate');
  19355. });
  19356. this.mainSegmentLoader_.on('timeout', () => {
  19357. if (this.bufferBasedABR) {
  19358. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  19359. // Here the only consideration is that for buffer based ABR there's no guarantee
  19360. // of an immediate switch (since the bandwidth is averaged with a timeout
  19361. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  19362. this.mainSegmentLoader_.load();
  19363. }
  19364. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  19365. // based ABR.
  19366. if (!this.bufferBasedABR) {
  19367. this.mainSegmentLoader_.on('progress', () => {
  19368. this.trigger('progress');
  19369. });
  19370. }
  19371. this.mainSegmentLoader_.on('error', () => {
  19372. const error = this.mainSegmentLoader_.error();
  19373. this.excludePlaylist({
  19374. playlistToExclude: error.playlist,
  19375. error
  19376. });
  19377. });
  19378. this.mainSegmentLoader_.on('appenderror', () => {
  19379. this.error = this.mainSegmentLoader_.error_;
  19380. this.trigger('error');
  19381. });
  19382. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  19383. this.onSyncInfoUpdate_();
  19384. });
  19385. this.mainSegmentLoader_.on('timestampoffset', () => {
  19386. this.tech_.trigger({
  19387. type: 'usage',
  19388. name: 'vhs-timestamp-offset'
  19389. });
  19390. });
  19391. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  19392. this.onSyncInfoUpdate_();
  19393. });
  19394. this.audioSegmentLoader_.on('appenderror', () => {
  19395. this.error = this.audioSegmentLoader_.error_;
  19396. this.trigger('error');
  19397. });
  19398. this.mainSegmentLoader_.on('ended', () => {
  19399. this.logger_('main segment loader ended');
  19400. this.onEndOfStream();
  19401. });
  19402. this.mainSegmentLoader_.on('earlyabort', event => {
  19403. // never try to early abort with the new ABR algorithm
  19404. if (this.bufferBasedABR) {
  19405. return;
  19406. }
  19407. this.delegateLoaders_('all', ['abort']);
  19408. this.excludePlaylist({
  19409. error: {
  19410. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  19411. },
  19412. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  19413. });
  19414. });
  19415. const updateCodecs = () => {
  19416. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  19417. return this.tryToCreateSourceBuffers_();
  19418. }
  19419. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  19420. if (!codecs) {
  19421. return;
  19422. }
  19423. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  19424. };
  19425. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  19426. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  19427. this.mainSegmentLoader_.on('fmp4', () => {
  19428. if (!this.triggeredFmp4Usage) {
  19429. this.tech_.trigger({
  19430. type: 'usage',
  19431. name: 'vhs-fmp4'
  19432. });
  19433. this.triggeredFmp4Usage = true;
  19434. }
  19435. });
  19436. this.audioSegmentLoader_.on('fmp4', () => {
  19437. if (!this.triggeredFmp4Usage) {
  19438. this.tech_.trigger({
  19439. type: 'usage',
  19440. name: 'vhs-fmp4'
  19441. });
  19442. this.triggeredFmp4Usage = true;
  19443. }
  19444. });
  19445. this.audioSegmentLoader_.on('ended', () => {
  19446. this.logger_('audioSegmentLoader ended');
  19447. this.onEndOfStream();
  19448. });
  19449. }
  19450. mediaSecondsLoaded_() {
  19451. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  19452. }
  19453. /**
  19454. * Call load on our SegmentLoaders
  19455. */
  19456. load() {
  19457. this.mainSegmentLoader_.load();
  19458. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19459. this.audioSegmentLoader_.load();
  19460. }
  19461. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  19462. this.subtitleSegmentLoader_.load();
  19463. }
  19464. }
  19465. /**
  19466. * Re-tune playback quality level for the current player
  19467. * conditions. This method will perform destructive actions like removing
  19468. * already buffered content in order to readjust the currently active
  19469. * playlist quickly. This is good for manual quality changes
  19470. *
  19471. * @private
  19472. */
  19473. fastQualityChange_(media = this.selectPlaylist()) {
  19474. if (media === this.mainPlaylistLoader_.media()) {
  19475. this.logger_('skipping fastQualityChange because new media is same as old');
  19476. return;
  19477. }
  19478. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  19479. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  19480. // ahead is roughly the minimum that will accomplish this across a variety of content
  19481. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  19482. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  19483. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  19484. this.mainSegmentLoader_.resetEverything(() => {
  19485. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  19486. // from the previously enabled rendition to load before the new playlist has finished loading
  19487. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  19488. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  19489. } else {
  19490. this.tech_.setCurrentTime(this.tech_.currentTime());
  19491. }
  19492. }); // don't need to reset audio as it is reset when media changes
  19493. }
  19494. /**
  19495. * Begin playback.
  19496. */
  19497. play() {
  19498. if (this.setupFirstPlay()) {
  19499. return;
  19500. }
  19501. if (this.tech_.ended()) {
  19502. this.tech_.setCurrentTime(0);
  19503. }
  19504. if (this.hasPlayed_) {
  19505. this.load();
  19506. }
  19507. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  19508. // seek forward to the live point
  19509. if (this.tech_.duration() === Infinity) {
  19510. if (this.tech_.currentTime() < seekable.start(0)) {
  19511. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  19512. }
  19513. }
  19514. }
  19515. /**
  19516. * Seek to the latest media position if this is a live video and the
  19517. * player and video are loaded and initialized.
  19518. */
  19519. setupFirstPlay() {
  19520. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  19521. // If 1) there is no active media
  19522. // 2) the player is paused
  19523. // 3) the first play has already been setup
  19524. // then exit early
  19525. if (!media || this.tech_.paused() || this.hasPlayed_) {
  19526. return false;
  19527. } // when the video is a live stream
  19528. if (!media.endList) {
  19529. const seekable = this.seekable();
  19530. if (!seekable.length) {
  19531. // without a seekable range, the player cannot seek to begin buffering at the live
  19532. // point
  19533. return false;
  19534. }
  19535. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  19536. // IE11 throws an InvalidStateError if you try to set currentTime while the
  19537. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  19538. this.tech_.one('loadedmetadata', () => {
  19539. this.trigger('firstplay');
  19540. this.tech_.setCurrentTime(seekable.end(0));
  19541. this.hasPlayed_ = true;
  19542. });
  19543. return false;
  19544. } // trigger firstplay to inform the source handler to ignore the next seek event
  19545. this.trigger('firstplay'); // seek to the live point
  19546. this.tech_.setCurrentTime(seekable.end(0));
  19547. }
  19548. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  19549. this.load();
  19550. return true;
  19551. }
  19552. /**
  19553. * handle the sourceopen event on the MediaSource
  19554. *
  19555. * @private
  19556. */
  19557. handleSourceOpen_() {
  19558. // Only attempt to create the source buffer if none already exist.
  19559. // handleSourceOpen is also called when we are "re-opening" a source buffer
  19560. // after `endOfStream` has been called (in response to a seek for instance)
  19561. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  19562. // code in video.js but is required because play() must be invoked
  19563. // *after* the media source has opened.
  19564. if (this.tech_.autoplay()) {
  19565. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  19566. // on browsers which return a promise
  19567. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  19568. playPromise.then(null, e => {});
  19569. }
  19570. }
  19571. this.trigger('sourceopen');
  19572. }
  19573. /**
  19574. * handle the sourceended event on the MediaSource
  19575. *
  19576. * @private
  19577. */
  19578. handleSourceEnded_() {
  19579. if (!this.inbandTextTracks_.metadataTrack_) {
  19580. return;
  19581. }
  19582. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  19583. if (!cues || !cues.length) {
  19584. return;
  19585. }
  19586. const duration = this.duration();
  19587. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  19588. }
  19589. /**
  19590. * handle the durationchange event on the MediaSource
  19591. *
  19592. * @private
  19593. */
  19594. handleDurationChange_() {
  19595. this.tech_.trigger('durationchange');
  19596. }
  19597. /**
  19598. * Calls endOfStream on the media source when all active stream types have called
  19599. * endOfStream
  19600. *
  19601. * @param {string} streamType
  19602. * Stream type of the segment loader that called endOfStream
  19603. * @private
  19604. */
  19605. onEndOfStream() {
  19606. let isEndOfStream = this.mainSegmentLoader_.ended_;
  19607. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19608. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  19609. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  19610. // if we do not know if the main segment loader contains video yet or if we
  19611. // definitively know the main segment loader contains video, then we need to wait
  19612. // for both main and audio segment loaders to call endOfStream
  19613. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  19614. } else {
  19615. // otherwise just rely on the audio loader
  19616. isEndOfStream = this.audioSegmentLoader_.ended_;
  19617. }
  19618. }
  19619. if (!isEndOfStream) {
  19620. return;
  19621. }
  19622. this.stopABRTimer_();
  19623. this.sourceUpdater_.endOfStream();
  19624. }
  19625. /**
  19626. * Check if a playlist has stopped being updated
  19627. *
  19628. * @param {Object} playlist the media playlist object
  19629. * @return {boolean} whether the playlist has stopped being updated or not
  19630. */
  19631. stuckAtPlaylistEnd_(playlist) {
  19632. const seekable = this.seekable();
  19633. if (!seekable.length) {
  19634. // playlist doesn't have enough information to determine whether we are stuck
  19635. return false;
  19636. }
  19637. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  19638. if (expired === null) {
  19639. return false;
  19640. } // does not use the safe live end to calculate playlist end, since we
  19641. // don't want to say we are stuck while there is still content
  19642. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  19643. const currentTime = this.tech_.currentTime();
  19644. const buffered = this.tech_.buffered();
  19645. if (!buffered.length) {
  19646. // return true if the playhead reached the absolute end of the playlist
  19647. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  19648. }
  19649. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  19650. // end of playlist
  19651. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  19652. }
  19653. /**
  19654. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  19655. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  19656. *
  19657. * @param {Object=} playlistToExclude
  19658. * the playlist to exclude, defaults to the currently selected playlist
  19659. * @param {Object=} error
  19660. * an optional error
  19661. * @param {number=} playlistExclusionDuration
  19662. * an optional number of seconds to exclude the playlist
  19663. */
  19664. excludePlaylist({
  19665. playlistToExclude = this.mainPlaylistLoader_.media(),
  19666. error = {},
  19667. playlistExclusionDuration
  19668. }) {
  19669. // If the `error` was generated by the playlist loader, it will contain
  19670. // the playlist we were trying to load (but failed) and that should be
  19671. // excluded instead of the currently selected playlist which is likely
  19672. // out-of-date in this scenario
  19673. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  19674. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  19675. // trying to load the main OR while we were disposing of the tech
  19676. if (!playlistToExclude) {
  19677. this.error = error;
  19678. if (this.mediaSource.readyState !== 'open') {
  19679. this.trigger('error');
  19680. } else {
  19681. this.sourceUpdater_.endOfStream('network');
  19682. }
  19683. return;
  19684. }
  19685. playlistToExclude.playlistErrors_++;
  19686. const playlists = this.mainPlaylistLoader_.main.playlists;
  19687. const enabledPlaylists = playlists.filter(isEnabled);
  19688. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  19689. // forever
  19690. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  19691. videojs.log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  19692. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  19693. return this.mainPlaylistLoader_.load(isFinalRendition);
  19694. }
  19695. if (isFinalRendition) {
  19696. // Since we're on the final non-excluded playlist, and we're about to exclude
  19697. // it, instead of erring the player or retrying this playlist, clear out the current
  19698. // exclusion list. This allows other playlists to be attempted in case any have been
  19699. // fixed.
  19700. let reincluded = false;
  19701. playlists.forEach(playlist => {
  19702. // skip current playlist which is about to be excluded
  19703. if (playlist === playlistToExclude) {
  19704. return;
  19705. }
  19706. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  19707. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  19708. reincluded = true;
  19709. delete playlist.excludeUntil;
  19710. }
  19711. });
  19712. if (reincluded) {
  19713. videojs.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
  19714. // playlist. This is needed for users relying on the retryplaylist event to catch a
  19715. // case where the player might be stuck and looping through "dead" playlists.
  19716. this.tech_.trigger('retryplaylist');
  19717. }
  19718. } // Exclude this playlist
  19719. let excludeUntil;
  19720. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  19721. excludeUntil = Infinity;
  19722. } else {
  19723. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  19724. }
  19725. playlistToExclude.excludeUntil = excludeUntil;
  19726. if (error.reason) {
  19727. playlistToExclude.lastExcludeReason_ = error.reason;
  19728. }
  19729. this.tech_.trigger('excludeplaylist');
  19730. this.tech_.trigger({
  19731. type: 'usage',
  19732. name: 'vhs-rendition-excluded'
  19733. }); // TODO: only load a new playlist if we're excluding the current playlist
  19734. // If this function was called with a playlist that's not the current active playlist
  19735. // (e.g., media().id !== playlistToExclude.id),
  19736. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  19737. const nextPlaylist = this.selectPlaylist();
  19738. if (!nextPlaylist) {
  19739. this.error = 'Playback cannot continue. No available working or supported playlists.';
  19740. this.trigger('error');
  19741. return;
  19742. }
  19743. const logFn = error.internal ? this.logger_ : videojs.log.warn;
  19744. const errorMessage = error.message ? ' ' + error.message : '';
  19745. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  19746. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  19747. this.delegateLoaders_('audio', ['abort', 'pause']);
  19748. } // if subtitle group changed reset subtitle loaders
  19749. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  19750. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  19751. }
  19752. this.delegateLoaders_('main', ['abort', 'pause']);
  19753. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  19754. 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
  19755. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  19756. }
  19757. /**
  19758. * Pause all segment/playlist loaders
  19759. */
  19760. pauseLoading() {
  19761. this.delegateLoaders_('all', ['abort', 'pause']);
  19762. this.stopABRTimer_();
  19763. }
  19764. /**
  19765. * Call a set of functions in order on playlist loaders, segment loaders,
  19766. * or both types of loaders.
  19767. *
  19768. * @param {string} filter
  19769. * Filter loaders that should call fnNames using a string. Can be:
  19770. * * all - run on all loaders
  19771. * * audio - run on all audio loaders
  19772. * * subtitle - run on all subtitle loaders
  19773. * * main - run on the main loaders
  19774. *
  19775. * @param {Array|string} fnNames
  19776. * A string or array of function names to call.
  19777. */
  19778. delegateLoaders_(filter, fnNames) {
  19779. const loaders = [];
  19780. const dontFilterPlaylist = filter === 'all';
  19781. if (dontFilterPlaylist || filter === 'main') {
  19782. loaders.push(this.mainPlaylistLoader_);
  19783. }
  19784. const mediaTypes = [];
  19785. if (dontFilterPlaylist || filter === 'audio') {
  19786. mediaTypes.push('AUDIO');
  19787. }
  19788. if (dontFilterPlaylist || filter === 'subtitle') {
  19789. mediaTypes.push('CLOSED-CAPTIONS');
  19790. mediaTypes.push('SUBTITLES');
  19791. }
  19792. mediaTypes.forEach(mediaType => {
  19793. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  19794. if (loader) {
  19795. loaders.push(loader);
  19796. }
  19797. });
  19798. ['main', 'audio', 'subtitle'].forEach(name => {
  19799. const loader = this[`${name}SegmentLoader_`];
  19800. if (loader && (filter === name || filter === 'all')) {
  19801. loaders.push(loader);
  19802. }
  19803. });
  19804. loaders.forEach(loader => fnNames.forEach(fnName => {
  19805. if (typeof loader[fnName] === 'function') {
  19806. loader[fnName]();
  19807. }
  19808. }));
  19809. }
  19810. /**
  19811. * set the current time on all segment loaders
  19812. *
  19813. * @param {TimeRange} currentTime the current time to set
  19814. * @return {TimeRange} the current time
  19815. */
  19816. setCurrentTime(currentTime) {
  19817. const buffered = findRange(this.tech_.buffered(), currentTime);
  19818. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  19819. // return immediately if the metadata is not ready yet
  19820. return 0;
  19821. } // it's clearly an edge-case but don't thrown an error if asked to
  19822. // seek within an empty playlist
  19823. if (!this.mainPlaylistLoader_.media().segments) {
  19824. return 0;
  19825. } // if the seek location is already buffered, continue buffering as usual
  19826. if (buffered && buffered.length) {
  19827. return currentTime;
  19828. } // cancel outstanding requests so we begin buffering at the new
  19829. // location
  19830. this.mainSegmentLoader_.resetEverything();
  19831. this.mainSegmentLoader_.abort();
  19832. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19833. this.audioSegmentLoader_.resetEverything();
  19834. this.audioSegmentLoader_.abort();
  19835. }
  19836. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  19837. this.subtitleSegmentLoader_.resetEverything();
  19838. this.subtitleSegmentLoader_.abort();
  19839. } // start segment loader loading in case they are paused
  19840. this.load();
  19841. }
  19842. /**
  19843. * get the current duration
  19844. *
  19845. * @return {TimeRange} the duration
  19846. */
  19847. duration() {
  19848. if (!this.mainPlaylistLoader_) {
  19849. return 0;
  19850. }
  19851. const media = this.mainPlaylistLoader_.media();
  19852. if (!media) {
  19853. // no playlists loaded yet, so can't determine a duration
  19854. return 0;
  19855. } // Don't rely on the media source for duration in the case of a live playlist since
  19856. // setting the native MediaSource's duration to infinity ends up with consequences to
  19857. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  19858. //
  19859. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  19860. // however, few browsers have support for setLiveSeekableRange()
  19861. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  19862. //
  19863. // Until a time when the duration of the media source can be set to infinity, and a
  19864. // seekable range specified across browsers, just return Infinity.
  19865. if (!media.endList) {
  19866. return Infinity;
  19867. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  19868. // available). If it's not available, fall back to a playlist-calculated estimate.
  19869. if (this.mediaSource) {
  19870. return this.mediaSource.duration;
  19871. }
  19872. return Vhs$1.Playlist.duration(media);
  19873. }
  19874. /**
  19875. * check the seekable range
  19876. *
  19877. * @return {TimeRange} the seekable range
  19878. */
  19879. seekable() {
  19880. return this.seekable_;
  19881. }
  19882. onSyncInfoUpdate_() {
  19883. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  19884. //
  19885. // A fix was made to this function where a check for
  19886. // this.sourceUpdater_.hasCreatedSourceBuffers
  19887. // was added to ensure that both source buffers were created before seekable was
  19888. // updated. However, it originally had a bug where it was checking for a true and
  19889. // returning early instead of checking for false. Setting it to check for false to
  19890. // return early though created other issues. A call to play() would check for seekable
  19891. // end without verifying that a seekable range was present. In addition, even checking
  19892. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  19893. // due to a media update calling load on the segment loaders, skipping a seek to live,
  19894. // thereby starting live streams at the beginning of the stream rather than at the end.
  19895. //
  19896. // This conditional should be fixed to wait for the creation of two source buffers at
  19897. // the same time as the other sections of code are fixed to properly seek to live and
  19898. // not throw an error due to checking for a seekable end when no seekable range exists.
  19899. //
  19900. // For now, fall back to the older behavior, with the understanding that the seekable
  19901. // range may not be completely correct, leading to a suboptimal initial live point.
  19902. if (!this.mainPlaylistLoader_) {
  19903. return;
  19904. }
  19905. let media = this.mainPlaylistLoader_.media();
  19906. if (!media) {
  19907. return;
  19908. }
  19909. let expired = this.syncController_.getExpiredTime(media, this.duration());
  19910. if (expired === null) {
  19911. // not enough information to update seekable
  19912. return;
  19913. }
  19914. const main = this.mainPlaylistLoader_.main;
  19915. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  19916. if (mainSeekable.length === 0) {
  19917. return;
  19918. }
  19919. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19920. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  19921. expired = this.syncController_.getExpiredTime(media, this.duration());
  19922. if (expired === null) {
  19923. return;
  19924. }
  19925. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  19926. if (audioSeekable.length === 0) {
  19927. return;
  19928. }
  19929. }
  19930. let oldEnd;
  19931. let oldStart;
  19932. if (this.seekable_ && this.seekable_.length) {
  19933. oldEnd = this.seekable_.end(0);
  19934. oldStart = this.seekable_.start(0);
  19935. }
  19936. if (!audioSeekable) {
  19937. // seekable has been calculated based on buffering video data so it
  19938. // can be returned directly
  19939. this.seekable_ = mainSeekable;
  19940. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  19941. // seekables are pretty far off, rely on main
  19942. this.seekable_ = mainSeekable;
  19943. } else {
  19944. 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)]]);
  19945. } // seekable is the same as last time
  19946. if (this.seekable_ && this.seekable_.length) {
  19947. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  19948. return;
  19949. }
  19950. }
  19951. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  19952. this.tech_.trigger('seekablechanged');
  19953. }
  19954. /**
  19955. * Update the player duration
  19956. */
  19957. updateDuration(isLive) {
  19958. if (this.updateDuration_) {
  19959. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  19960. this.updateDuration_ = null;
  19961. }
  19962. if (this.mediaSource.readyState !== 'open') {
  19963. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  19964. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  19965. return;
  19966. }
  19967. if (isLive) {
  19968. const seekable = this.seekable();
  19969. if (!seekable.length) {
  19970. return;
  19971. } // Even in the case of a live playlist, the native MediaSource's duration should not
  19972. // be set to Infinity (even though this would be expected for a live playlist), since
  19973. // setting the native MediaSource's duration to infinity ends up with consequences to
  19974. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  19975. //
  19976. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  19977. // however, few browsers have support for setLiveSeekableRange()
  19978. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  19979. //
  19980. // Until a time when the duration of the media source can be set to infinity, and a
  19981. // seekable range specified across browsers, the duration should be greater than or
  19982. // equal to the last possible seekable value.
  19983. // MediaSource duration starts as NaN
  19984. // It is possible (and probable) that this case will never be reached for many
  19985. // sources, since the MediaSource reports duration as the highest value without
  19986. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  19987. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  19988. // time will be between 0 and 100, the native media source may report the duration
  19989. // as 200. However, since we report duration separate from the media source (as
  19990. // Infinity), and as long as the native media source duration value is greater than
  19991. // our reported seekable range, seeks will work as expected. The large number as
  19992. // duration for live is actually a strategy used by some players to work around the
  19993. // issue of live seekable ranges cited above.
  19994. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  19995. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  19996. }
  19997. return;
  19998. }
  19999. const buffered = this.tech_.buffered();
  20000. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  20001. if (buffered.length > 0) {
  20002. duration = Math.max(duration, buffered.end(buffered.length - 1));
  20003. }
  20004. if (this.mediaSource.duration !== duration) {
  20005. this.sourceUpdater_.setDuration(duration);
  20006. }
  20007. }
  20008. /**
  20009. * dispose of the PlaylistController and everything
  20010. * that it controls
  20011. */
  20012. dispose() {
  20013. this.trigger('dispose');
  20014. this.decrypter_.terminate();
  20015. this.mainPlaylistLoader_.dispose();
  20016. this.mainSegmentLoader_.dispose();
  20017. if (this.loadOnPlay_) {
  20018. this.tech_.off('play', this.loadOnPlay_);
  20019. }
  20020. ['AUDIO', 'SUBTITLES'].forEach(type => {
  20021. const groups = this.mediaTypes_[type].groups;
  20022. for (const id in groups) {
  20023. groups[id].forEach(group => {
  20024. if (group.playlistLoader) {
  20025. group.playlistLoader.dispose();
  20026. }
  20027. });
  20028. }
  20029. });
  20030. this.audioSegmentLoader_.dispose();
  20031. this.subtitleSegmentLoader_.dispose();
  20032. this.sourceUpdater_.dispose();
  20033. this.timelineChangeController_.dispose();
  20034. this.stopABRTimer_();
  20035. if (this.updateDuration_) {
  20036. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  20037. }
  20038. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  20039. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  20040. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  20041. this.off();
  20042. }
  20043. /**
  20044. * return the main playlist object if we have one
  20045. *
  20046. * @return {Object} the main playlist object that we parsed
  20047. */
  20048. main() {
  20049. return this.mainPlaylistLoader_.main;
  20050. }
  20051. /**
  20052. * return the currently selected playlist
  20053. *
  20054. * @return {Object} the currently selected playlist object that we parsed
  20055. */
  20056. media() {
  20057. // playlist loader will not return media if it has not been fully loaded
  20058. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  20059. }
  20060. areMediaTypesKnown_() {
  20061. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  20062. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  20063. // otherwise check on the segment loader.
  20064. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  20065. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  20066. return false;
  20067. }
  20068. return true;
  20069. }
  20070. getCodecsOrExclude_() {
  20071. const media = {
  20072. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  20073. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  20074. };
  20075. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  20076. media.video = media.main;
  20077. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  20078. const codecs = {};
  20079. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  20080. if (media.main.hasVideo) {
  20081. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  20082. }
  20083. if (media.main.isMuxed) {
  20084. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  20085. }
  20086. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  20087. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  20088. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  20089. } // no codecs, no playback.
  20090. if (!codecs.audio && !codecs.video) {
  20091. this.excludePlaylist({
  20092. playlistToExclude: playlist,
  20093. error: {
  20094. message: 'Could not determine codecs for playlist.'
  20095. },
  20096. playlistExclusionDuration: Infinity
  20097. });
  20098. return;
  20099. } // fmp4 relies on browser support, while ts relies on muxer support
  20100. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  20101. const unsupportedCodecs = {};
  20102. let unsupportedAudio;
  20103. ['video', 'audio'].forEach(function (type) {
  20104. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  20105. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  20106. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  20107. unsupportedCodecs[supporter].push(codecs[type]);
  20108. if (type === 'audio') {
  20109. unsupportedAudio = supporter;
  20110. }
  20111. }
  20112. });
  20113. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  20114. const audioGroup = playlist.attributes.AUDIO;
  20115. this.main().playlists.forEach(variant => {
  20116. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  20117. if (variantAudioGroup === audioGroup && variant !== playlist) {
  20118. variant.excludeUntil = Infinity;
  20119. }
  20120. });
  20121. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  20122. } // if we have any unsupported codecs exclude this playlist.
  20123. if (Object.keys(unsupportedCodecs).length) {
  20124. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  20125. if (acc) {
  20126. acc += ', ';
  20127. }
  20128. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  20129. return acc;
  20130. }, '') + '.';
  20131. this.excludePlaylist({
  20132. playlistToExclude: playlist,
  20133. error: {
  20134. internal: true,
  20135. message
  20136. },
  20137. playlistExclusionDuration: Infinity
  20138. });
  20139. return;
  20140. } // check if codec switching is happening
  20141. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  20142. const switchMessages = [];
  20143. ['video', 'audio'].forEach(type => {
  20144. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  20145. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  20146. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  20147. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  20148. }
  20149. });
  20150. if (switchMessages.length) {
  20151. this.excludePlaylist({
  20152. playlistToExclude: playlist,
  20153. error: {
  20154. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  20155. internal: true
  20156. },
  20157. playlistExclusionDuration: Infinity
  20158. });
  20159. return;
  20160. }
  20161. } // TODO: when using the muxer shouldn't we just return
  20162. // the codecs that the muxer outputs?
  20163. return codecs;
  20164. }
  20165. /**
  20166. * Create source buffers and exlude any incompatible renditions.
  20167. *
  20168. * @private
  20169. */
  20170. tryToCreateSourceBuffers_() {
  20171. // media source is not ready yet or sourceBuffers are already
  20172. // created.
  20173. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  20174. return;
  20175. }
  20176. if (!this.areMediaTypesKnown_()) {
  20177. return;
  20178. }
  20179. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  20180. if (!codecs) {
  20181. return;
  20182. }
  20183. this.sourceUpdater_.createSourceBuffers(codecs);
  20184. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  20185. this.excludeIncompatibleVariants_(codecString);
  20186. }
  20187. /**
  20188. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  20189. */
  20190. excludeUnsupportedVariants_() {
  20191. const playlists = this.main().playlists;
  20192. const ids = []; // TODO: why don't we have a property to loop through all
  20193. // playlist? Why did we ever mix indexes and keys?
  20194. Object.keys(playlists).forEach(key => {
  20195. const variant = playlists[key]; // check if we already processed this playlist.
  20196. if (ids.indexOf(variant.id) !== -1) {
  20197. return;
  20198. }
  20199. ids.push(variant.id);
  20200. const codecs = codecsForPlaylist(this.main, variant);
  20201. const unsupported = [];
  20202. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  20203. unsupported.push(`audio codec ${codecs.audio}`);
  20204. }
  20205. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  20206. unsupported.push(`video codec ${codecs.video}`);
  20207. }
  20208. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  20209. unsupported.push(`text codec ${codecs.text}`);
  20210. }
  20211. if (unsupported.length) {
  20212. variant.excludeUntil = Infinity;
  20213. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  20214. }
  20215. });
  20216. }
  20217. /**
  20218. * Exclude playlists that are known to be codec or
  20219. * stream-incompatible with the SourceBuffer configuration. For
  20220. * instance, Media Source Extensions would cause the video element to
  20221. * stall waiting for video data if you switched from a variant with
  20222. * video and audio to an audio-only one.
  20223. *
  20224. * @param {Object} media a media playlist compatible with the current
  20225. * set of SourceBuffers. Variants in the current main playlist that
  20226. * do not appear to have compatible codec or stream configurations
  20227. * will be excluded from the default playlist selection algorithm
  20228. * indefinitely.
  20229. * @private
  20230. */
  20231. excludeIncompatibleVariants_(codecString) {
  20232. const ids = [];
  20233. const playlists = this.main().playlists;
  20234. const codecs = unwrapCodecList(parseCodecs(codecString));
  20235. const codecCount_ = codecCount(codecs);
  20236. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  20237. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  20238. Object.keys(playlists).forEach(key => {
  20239. const variant = playlists[key]; // check if we already processed this playlist.
  20240. // or it if it is already excluded forever.
  20241. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  20242. return;
  20243. }
  20244. ids.push(variant.id);
  20245. const exclusionReasons = []; // get codecs from the playlist for this variant
  20246. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  20247. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  20248. // variant is incompatible. Wait for mux.js to probe
  20249. if (!variantCodecs.audio && !variantCodecs.video) {
  20250. return;
  20251. } // TODO: we can support this by removing the
  20252. // old media source and creating a new one, but it will take some work.
  20253. // The number of streams cannot change
  20254. if (variantCodecCount !== codecCount_) {
  20255. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  20256. } // only exclude playlists by codec change, if codecs cannot switch
  20257. // during playback.
  20258. if (!this.sourceUpdater_.canChangeType()) {
  20259. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  20260. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  20261. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  20262. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  20263. } // the audio codec cannot change
  20264. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  20265. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  20266. }
  20267. }
  20268. if (exclusionReasons.length) {
  20269. variant.excludeUntil = Infinity;
  20270. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  20271. }
  20272. });
  20273. }
  20274. updateAdCues_(media) {
  20275. let offset = 0;
  20276. const seekable = this.seekable();
  20277. if (seekable.length) {
  20278. offset = seekable.start(0);
  20279. }
  20280. updateAdCues(media, this.cueTagsTrack_, offset);
  20281. }
  20282. /**
  20283. * Calculates the desired forward buffer length based on current time
  20284. *
  20285. * @return {number} Desired forward buffer length in seconds
  20286. */
  20287. goalBufferLength() {
  20288. const currentTime = this.tech_.currentTime();
  20289. const initial = Config.GOAL_BUFFER_LENGTH;
  20290. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  20291. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  20292. return Math.min(initial + currentTime * rate, max);
  20293. }
  20294. /**
  20295. * Calculates the desired buffer low water line based on current time
  20296. *
  20297. * @return {number} Desired buffer low water line in seconds
  20298. */
  20299. bufferLowWaterLine() {
  20300. const currentTime = this.tech_.currentTime();
  20301. const initial = Config.BUFFER_LOW_WATER_LINE;
  20302. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  20303. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  20304. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  20305. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  20306. }
  20307. bufferHighWaterLine() {
  20308. return Config.BUFFER_HIGH_WATER_LINE;
  20309. }
  20310. }
  20311. /**
  20312. * Returns a function that acts as the Enable/disable playlist function.
  20313. *
  20314. * @param {PlaylistLoader} loader - The main playlist loader
  20315. * @param {string} playlistID - id of the playlist
  20316. * @param {Function} changePlaylistFn - A function to be called after a
  20317. * playlist's enabled-state has been changed. Will NOT be called if a
  20318. * playlist's enabled-state is unchanged
  20319. * @param {boolean=} enable - Value to set the playlist enabled-state to
  20320. * or if undefined returns the current enabled-state for the playlist
  20321. * @return {Function} Function for setting/getting enabled
  20322. */
  20323. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  20324. const playlist = loader.main.playlists[playlistID];
  20325. const incompatible = isIncompatible(playlist);
  20326. const currentlyEnabled = isEnabled(playlist);
  20327. if (typeof enable === 'undefined') {
  20328. return currentlyEnabled;
  20329. }
  20330. if (enable) {
  20331. delete playlist.disabled;
  20332. } else {
  20333. playlist.disabled = true;
  20334. }
  20335. if (enable !== currentlyEnabled && !incompatible) {
  20336. // Ensure the outside world knows about our changes
  20337. changePlaylistFn();
  20338. if (enable) {
  20339. loader.trigger('renditionenabled');
  20340. } else {
  20341. loader.trigger('renditiondisabled');
  20342. }
  20343. }
  20344. return enable;
  20345. };
  20346. /**
  20347. * The representation object encapsulates the publicly visible information
  20348. * in a media playlist along with a setter/getter-type function (enabled)
  20349. * for changing the enabled-state of a particular playlist entry
  20350. *
  20351. * @class Representation
  20352. */
  20353. class Representation {
  20354. constructor(vhsHandler, playlist, id) {
  20355. const {
  20356. playlistController_: pc
  20357. } = vhsHandler;
  20358. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  20359. if (playlist.attributes) {
  20360. const resolution = playlist.attributes.RESOLUTION;
  20361. this.width = resolution && resolution.width;
  20362. this.height = resolution && resolution.height;
  20363. this.bandwidth = playlist.attributes.BANDWIDTH;
  20364. this.frameRate = playlist.attributes['FRAME-RATE'];
  20365. }
  20366. this.codecs = codecsForPlaylist(pc.main(), playlist);
  20367. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  20368. // within the main playlist
  20369. this.id = id; // Partially-apply the enableFunction to create a playlist-
  20370. // specific variant
  20371. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  20372. }
  20373. }
  20374. /**
  20375. * A mixin function that adds the `representations` api to an instance
  20376. * of the VhsHandler class
  20377. *
  20378. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  20379. * representation API into
  20380. */
  20381. const renditionSelectionMixin = function (vhsHandler) {
  20382. // Add a single API-specific function to the VhsHandler instance
  20383. vhsHandler.representations = () => {
  20384. const main = vhsHandler.playlistController_.main();
  20385. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  20386. if (!playlists) {
  20387. return [];
  20388. }
  20389. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  20390. };
  20391. };
  20392. /**
  20393. * @file playback-watcher.js
  20394. *
  20395. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  20396. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  20397. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  20398. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  20399. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  20400. */
  20401. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  20402. /**
  20403. * @class PlaybackWatcher
  20404. */
  20405. class PlaybackWatcher {
  20406. /**
  20407. * Represents an PlaybackWatcher object.
  20408. *
  20409. * @class
  20410. * @param {Object} options an object that includes the tech and settings
  20411. */
  20412. constructor(options) {
  20413. this.playlistController_ = options.playlistController;
  20414. this.tech_ = options.tech;
  20415. this.seekable = options.seekable;
  20416. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  20417. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  20418. this.media = options.media;
  20419. this.consecutiveUpdates = 0;
  20420. this.lastRecordedTime = null;
  20421. this.checkCurrentTimeTimeout_ = null;
  20422. this.logger_ = logger('PlaybackWatcher');
  20423. this.logger_('initialize');
  20424. const playHandler = () => this.monitorCurrentTime_();
  20425. const canPlayHandler = () => this.monitorCurrentTime_();
  20426. const waitingHandler = () => this.techWaiting_();
  20427. const cancelTimerHandler = () => this.resetTimeUpdate_();
  20428. const pc = this.playlistController_;
  20429. const loaderTypes = ['main', 'subtitle', 'audio'];
  20430. const loaderChecks = {};
  20431. loaderTypes.forEach(type => {
  20432. loaderChecks[type] = {
  20433. reset: () => this.resetSegmentDownloads_(type),
  20434. updateend: () => this.checkSegmentDownloads_(type)
  20435. };
  20436. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  20437. // isn't changing we want to reset. We cannot assume that the new rendition
  20438. // will also be stalled, until after new appends.
  20439. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  20440. // This prevents one segment playlists (single vtt or single segment content)
  20441. // from being detected as stalling. As the buffer will not change in those cases, since
  20442. // the buffer is the entire video duration.
  20443. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  20444. });
  20445. /**
  20446. * We check if a seek was into a gap through the following steps:
  20447. * 1. We get a seeking event and we do not get a seeked event. This means that
  20448. * a seek was attempted but not completed.
  20449. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  20450. * removed everything from our buffer and appended a segment, and should be ready
  20451. * to check for gaps.
  20452. */
  20453. const setSeekingHandlers = fn => {
  20454. ['main', 'audio'].forEach(type => {
  20455. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  20456. });
  20457. };
  20458. this.seekingAppendCheck_ = () => {
  20459. if (this.fixesBadSeeks_()) {
  20460. this.consecutiveUpdates = 0;
  20461. this.lastRecordedTime = this.tech_.currentTime();
  20462. setSeekingHandlers('off');
  20463. }
  20464. };
  20465. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  20466. this.watchForBadSeeking_ = () => {
  20467. this.clearSeekingAppendCheck_();
  20468. setSeekingHandlers('on');
  20469. };
  20470. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  20471. this.tech_.on('seeking', this.watchForBadSeeking_);
  20472. this.tech_.on('waiting', waitingHandler);
  20473. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  20474. this.tech_.on('canplay', canPlayHandler);
  20475. /*
  20476. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  20477. is surfaced in one of two ways:
  20478. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  20479. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  20480. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  20481. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  20482. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  20483. even if the player is in a playing state
  20484. */
  20485. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  20486. this.dispose = () => {
  20487. this.clearSeekingAppendCheck_();
  20488. this.logger_('dispose');
  20489. this.tech_.off('waiting', waitingHandler);
  20490. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  20491. this.tech_.off('canplay', canPlayHandler);
  20492. this.tech_.off('play', playHandler);
  20493. this.tech_.off('seeking', this.watchForBadSeeking_);
  20494. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  20495. loaderTypes.forEach(type => {
  20496. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  20497. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  20498. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  20499. });
  20500. if (this.checkCurrentTimeTimeout_) {
  20501. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  20502. }
  20503. this.resetTimeUpdate_();
  20504. };
  20505. }
  20506. /**
  20507. * Periodically check current time to see if playback stopped
  20508. *
  20509. * @private
  20510. */
  20511. monitorCurrentTime_() {
  20512. this.checkCurrentTime_();
  20513. if (this.checkCurrentTimeTimeout_) {
  20514. window$1.clearTimeout(this.checkCurrentTimeTimeout_);
  20515. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  20516. this.checkCurrentTimeTimeout_ = window$1.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  20517. }
  20518. /**
  20519. * Reset stalled download stats for a specific type of loader
  20520. *
  20521. * @param {string} type
  20522. * The segment loader type to check.
  20523. *
  20524. * @listens SegmentLoader#playlistupdate
  20525. * @listens Tech#seeking
  20526. * @listens Tech#seeked
  20527. */
  20528. resetSegmentDownloads_(type) {
  20529. const loader = this.playlistController_[`${type}SegmentLoader_`];
  20530. if (this[`${type}StalledDownloads_`] > 0) {
  20531. this.logger_(`resetting possible stalled download count for ${type} loader`);
  20532. }
  20533. this[`${type}StalledDownloads_`] = 0;
  20534. this[`${type}Buffered_`] = loader.buffered_();
  20535. }
  20536. /**
  20537. * Checks on every segment `appendsdone` to see
  20538. * if segment appends are making progress. If they are not
  20539. * and we are still downloading bytes. We exclude the playlist.
  20540. *
  20541. * @param {string} type
  20542. * The segment loader type to check.
  20543. *
  20544. * @listens SegmentLoader#appendsdone
  20545. */
  20546. checkSegmentDownloads_(type) {
  20547. const pc = this.playlistController_;
  20548. const loader = pc[`${type}SegmentLoader_`];
  20549. const buffered = loader.buffered_();
  20550. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  20551. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  20552. // the buffered value for this loader changed
  20553. // appends are working
  20554. if (isBufferedDifferent) {
  20555. this.resetSegmentDownloads_(type);
  20556. return;
  20557. }
  20558. this[`${type}StalledDownloads_`]++;
  20559. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  20560. playlistId: loader.playlist_ && loader.playlist_.id,
  20561. buffered: timeRangesToArray(buffered)
  20562. }); // after 10 possibly stalled appends with no reset, exclude
  20563. if (this[`${type}StalledDownloads_`] < 10) {
  20564. return;
  20565. }
  20566. this.logger_(`${type} loader stalled download exclusion`);
  20567. this.resetSegmentDownloads_(type);
  20568. this.tech_.trigger({
  20569. type: 'usage',
  20570. name: `vhs-${type}-download-exclusion`
  20571. });
  20572. if (type === 'subtitle') {
  20573. return;
  20574. } // TODO: should we exclude audio tracks rather than main tracks
  20575. // when type is audio?
  20576. pc.excludePlaylist({
  20577. error: {
  20578. message: `Excessive ${type} segment downloading detected.`
  20579. },
  20580. playlistExclusionDuration: Infinity
  20581. });
  20582. }
  20583. /**
  20584. * The purpose of this function is to emulate the "waiting" event on
  20585. * browsers that do not emit it when they are waiting for more
  20586. * data to continue playback
  20587. *
  20588. * @private
  20589. */
  20590. checkCurrentTime_() {
  20591. if (this.tech_.paused() || this.tech_.seeking()) {
  20592. return;
  20593. }
  20594. const currentTime = this.tech_.currentTime();
  20595. const buffered = this.tech_.buffered();
  20596. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  20597. // If current time is at the end of the final buffered region, then any playback
  20598. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  20599. // should fire a `waiting` event in this scenario, but due to browser and tech
  20600. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  20601. // responding to a native `waiting` event when the tech fails to emit one.
  20602. return this.techWaiting_();
  20603. }
  20604. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  20605. this.consecutiveUpdates++;
  20606. this.waiting_();
  20607. } else if (currentTime === this.lastRecordedTime) {
  20608. this.consecutiveUpdates++;
  20609. } else {
  20610. this.consecutiveUpdates = 0;
  20611. this.lastRecordedTime = currentTime;
  20612. }
  20613. }
  20614. /**
  20615. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  20616. *
  20617. * @private
  20618. */
  20619. resetTimeUpdate_() {
  20620. this.consecutiveUpdates = 0;
  20621. }
  20622. /**
  20623. * Fixes situations where there's a bad seek
  20624. *
  20625. * @return {boolean} whether an action was taken to fix the seek
  20626. * @private
  20627. */
  20628. fixesBadSeeks_() {
  20629. const seeking = this.tech_.seeking();
  20630. if (!seeking) {
  20631. return false;
  20632. } // TODO: It's possible that these seekable checks should be moved out of this function
  20633. // and into a function that runs on seekablechange. It's also possible that we only need
  20634. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  20635. // seekable range.
  20636. const seekable = this.seekable();
  20637. const currentTime = this.tech_.currentTime();
  20638. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  20639. let seekTo;
  20640. if (isAfterSeekableRange) {
  20641. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  20642. seekTo = seekableEnd;
  20643. }
  20644. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  20645. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  20646. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  20647. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  20648. // happen in live with a 3 segment playlist), then don't use a time delta
  20649. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  20650. }
  20651. if (typeof seekTo !== 'undefined') {
  20652. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  20653. this.tech_.setCurrentTime(seekTo);
  20654. return true;
  20655. }
  20656. const sourceUpdater = this.playlistController_.sourceUpdater_;
  20657. const buffered = this.tech_.buffered();
  20658. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  20659. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  20660. const media = this.media(); // verify that at least two segment durations or one part duration have been
  20661. // appended before checking for a gap.
  20662. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  20663. // appended before checking for a gap.
  20664. const bufferedToCheck = [audioBuffered, videoBuffered];
  20665. for (let i = 0; i < bufferedToCheck.length; i++) {
  20666. // skip null buffered
  20667. if (!bufferedToCheck[i]) {
  20668. continue;
  20669. }
  20670. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  20671. // duration behind we haven't appended enough to call this a bad seek.
  20672. if (timeAhead < minAppendedDuration) {
  20673. return false;
  20674. }
  20675. }
  20676. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  20677. // to seek over the gap
  20678. if (nextRange.length === 0) {
  20679. return false;
  20680. }
  20681. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  20682. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  20683. this.tech_.setCurrentTime(seekTo);
  20684. return true;
  20685. }
  20686. /**
  20687. * Handler for situations when we determine the player is waiting.
  20688. *
  20689. * @private
  20690. */
  20691. waiting_() {
  20692. if (this.techWaiting_()) {
  20693. return;
  20694. } // All tech waiting checks failed. Use last resort correction
  20695. const currentTime = this.tech_.currentTime();
  20696. const buffered = this.tech_.buffered();
  20697. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  20698. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  20699. // currentTime is usually enough to kickstart the player. This checks that the player
  20700. // is currently within a buffered region before attempting a corrective seek.
  20701. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  20702. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  20703. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  20704. // to avoid triggering an `unknownwaiting` event when the network is slow.
  20705. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  20706. this.resetTimeUpdate_();
  20707. this.tech_.setCurrentTime(currentTime);
  20708. 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
  20709. this.tech_.trigger({
  20710. type: 'usage',
  20711. name: 'vhs-unknown-waiting'
  20712. });
  20713. return;
  20714. }
  20715. }
  20716. /**
  20717. * Handler for situations when the tech fires a `waiting` event
  20718. *
  20719. * @return {boolean}
  20720. * True if an action (or none) was needed to correct the waiting. False if no
  20721. * checks passed
  20722. * @private
  20723. */
  20724. techWaiting_() {
  20725. const seekable = this.seekable();
  20726. const currentTime = this.tech_.currentTime();
  20727. if (this.tech_.seeking()) {
  20728. // Tech is seeking or already waiting on another action, no action needed
  20729. return true;
  20730. }
  20731. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  20732. const livePoint = seekable.end(seekable.length - 1);
  20733. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  20734. this.resetTimeUpdate_();
  20735. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  20736. this.tech_.trigger({
  20737. type: 'usage',
  20738. name: 'vhs-live-resync'
  20739. });
  20740. return true;
  20741. }
  20742. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  20743. const buffered = this.tech_.buffered();
  20744. const videoUnderflow = this.videoUnderflow_({
  20745. audioBuffered: sourceUpdater.audioBuffered(),
  20746. videoBuffered: sourceUpdater.videoBuffered(),
  20747. currentTime
  20748. });
  20749. if (videoUnderflow) {
  20750. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  20751. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  20752. // allows the video to catch up to the audio position without losing any audio
  20753. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  20754. this.resetTimeUpdate_();
  20755. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  20756. this.tech_.trigger({
  20757. type: 'usage',
  20758. name: 'vhs-video-underflow'
  20759. });
  20760. return true;
  20761. }
  20762. const nextRange = findNextRange(buffered, currentTime); // check for gap
  20763. if (nextRange.length > 0) {
  20764. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  20765. this.resetTimeUpdate_();
  20766. this.skipTheGap_(currentTime);
  20767. return true;
  20768. } // All checks failed. Returning false to indicate failure to correct waiting
  20769. return false;
  20770. }
  20771. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  20772. if (!seekable.length) {
  20773. // we can't make a solid case if there's no seekable, default to false
  20774. return false;
  20775. }
  20776. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  20777. const isLive = !playlist.endList;
  20778. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  20779. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  20780. }
  20781. if (currentTime > allowedEnd) {
  20782. return true;
  20783. }
  20784. return false;
  20785. }
  20786. beforeSeekableWindow_(seekable, currentTime) {
  20787. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  20788. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  20789. return true;
  20790. }
  20791. return false;
  20792. }
  20793. videoUnderflow_({
  20794. videoBuffered,
  20795. audioBuffered,
  20796. currentTime
  20797. }) {
  20798. // audio only content will not have video underflow :)
  20799. if (!videoBuffered) {
  20800. return;
  20801. }
  20802. let gap; // find a gap in demuxed content.
  20803. if (videoBuffered.length && audioBuffered.length) {
  20804. // in Chrome audio will continue to play for ~3s when we run out of video
  20805. // so we have to check that the video buffer did have some buffer in the
  20806. // past.
  20807. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  20808. const videoRange = findRange(videoBuffered, currentTime);
  20809. const audioRange = findRange(audioBuffered, currentTime);
  20810. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  20811. gap = {
  20812. start: lastVideoRange.end(0),
  20813. end: audioRange.end(0)
  20814. };
  20815. } // find a gap in muxed content.
  20816. } else {
  20817. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  20818. // stuck in a gap due to video underflow.
  20819. if (!nextRange.length) {
  20820. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  20821. }
  20822. }
  20823. if (gap) {
  20824. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  20825. return true;
  20826. }
  20827. return false;
  20828. }
  20829. /**
  20830. * Timer callback. If playback still has not proceeded, then we seek
  20831. * to the start of the next buffered region.
  20832. *
  20833. * @private
  20834. */
  20835. skipTheGap_(scheduledCurrentTime) {
  20836. const buffered = this.tech_.buffered();
  20837. const currentTime = this.tech_.currentTime();
  20838. const nextRange = findNextRange(buffered, currentTime);
  20839. this.resetTimeUpdate_();
  20840. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  20841. return;
  20842. }
  20843. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  20844. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  20845. this.tech_.trigger({
  20846. type: 'usage',
  20847. name: 'vhs-gap-skip'
  20848. });
  20849. }
  20850. gapFromVideoUnderflow_(buffered, currentTime) {
  20851. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  20852. // playing for ~3 seconds after the video gap starts. This is done to account for
  20853. // video buffer underflow/underrun (note that this is not done when there is audio
  20854. // buffer underflow/underrun -- in that case the video will stop as soon as it
  20855. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  20856. // video stalls). The player's time will reflect the playthrough of audio, so the
  20857. // time will appear as if we are in a buffered region, even if we are stuck in a
  20858. // "gap."
  20859. //
  20860. // Example:
  20861. // video buffer: 0 => 10.1, 10.2 => 20
  20862. // audio buffer: 0 => 20
  20863. // overall buffer: 0 => 10.1, 10.2 => 20
  20864. // current time: 13
  20865. //
  20866. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  20867. // however, the audio continued playing until it reached ~3 seconds past the gap
  20868. // (13 seconds), at which point it stops as well. Since current time is past the
  20869. // gap, findNextRange will return no ranges.
  20870. //
  20871. // To check for this issue, we see if there is a gap that starts somewhere within
  20872. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  20873. const gaps = findGaps(buffered);
  20874. for (let i = 0; i < gaps.length; i++) {
  20875. const start = gaps.start(i);
  20876. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  20877. if (currentTime - start < 4 && currentTime - start > 2) {
  20878. return {
  20879. start,
  20880. end
  20881. };
  20882. }
  20883. }
  20884. return null;
  20885. }
  20886. }
  20887. const defaultOptions = {
  20888. errorInterval: 30,
  20889. getSource(next) {
  20890. const tech = this.tech({
  20891. IWillNotUseThisInPlugins: true
  20892. });
  20893. const sourceObj = tech.currentSource_ || this.currentSource();
  20894. return next(sourceObj);
  20895. }
  20896. };
  20897. /**
  20898. * Main entry point for the plugin
  20899. *
  20900. * @param {Player} player a reference to a videojs Player instance
  20901. * @param {Object} [options] an object with plugin options
  20902. * @private
  20903. */
  20904. const initPlugin = function (player, options) {
  20905. let lastCalled = 0;
  20906. let seekTo = 0;
  20907. const localOptions = merge(defaultOptions, options);
  20908. player.ready(() => {
  20909. player.trigger({
  20910. type: 'usage',
  20911. name: 'vhs-error-reload-initialized'
  20912. });
  20913. });
  20914. /**
  20915. * Player modifications to perform that must wait until `loadedmetadata`
  20916. * has been triggered
  20917. *
  20918. * @private
  20919. */
  20920. const loadedMetadataHandler = function () {
  20921. if (seekTo) {
  20922. player.currentTime(seekTo);
  20923. }
  20924. };
  20925. /**
  20926. * Set the source on the player element, play, and seek if necessary
  20927. *
  20928. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  20929. * @private
  20930. */
  20931. const setSource = function (sourceObj) {
  20932. if (sourceObj === null || sourceObj === undefined) {
  20933. return;
  20934. }
  20935. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  20936. player.one('loadedmetadata', loadedMetadataHandler);
  20937. player.src(sourceObj);
  20938. player.trigger({
  20939. type: 'usage',
  20940. name: 'vhs-error-reload'
  20941. });
  20942. player.play();
  20943. };
  20944. /**
  20945. * Attempt to get a source from either the built-in getSource function
  20946. * or a custom function provided via the options
  20947. *
  20948. * @private
  20949. */
  20950. const errorHandler = function () {
  20951. // Do not attempt to reload the source if a source-reload occurred before
  20952. // 'errorInterval' time has elapsed since the last source-reload
  20953. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  20954. player.trigger({
  20955. type: 'usage',
  20956. name: 'vhs-error-reload-canceled'
  20957. });
  20958. return;
  20959. }
  20960. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  20961. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  20962. return;
  20963. }
  20964. lastCalled = Date.now();
  20965. return localOptions.getSource.call(player, setSource);
  20966. };
  20967. /**
  20968. * Unbind any event handlers that were bound by the plugin
  20969. *
  20970. * @private
  20971. */
  20972. const cleanupEvents = function () {
  20973. player.off('loadedmetadata', loadedMetadataHandler);
  20974. player.off('error', errorHandler);
  20975. player.off('dispose', cleanupEvents);
  20976. };
  20977. /**
  20978. * Cleanup before re-initializing the plugin
  20979. *
  20980. * @param {Object} [newOptions] an object with plugin options
  20981. * @private
  20982. */
  20983. const reinitPlugin = function (newOptions) {
  20984. cleanupEvents();
  20985. initPlugin(player, newOptions);
  20986. };
  20987. player.on('error', errorHandler);
  20988. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  20989. // initializing the plugin
  20990. player.reloadSourceOnError = reinitPlugin;
  20991. };
  20992. /**
  20993. * Reload the source when an error is detected as long as there
  20994. * wasn't an error previously within the last 30 seconds
  20995. *
  20996. * @param {Object} [options] an object with plugin options
  20997. */
  20998. const reloadSourceOnError = function (options) {
  20999. initPlugin(this, options);
  21000. };
  21001. var version$4 = "3.0.2";
  21002. var version$3 = "6.3.0";
  21003. var version$2 = "1.0.1";
  21004. var version$1 = "6.0.0";
  21005. var version = "4.0.1";
  21006. /**
  21007. * @file videojs-http-streaming.js
  21008. *
  21009. * The main file for the VHS project.
  21010. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  21011. */
  21012. const Vhs = {
  21013. PlaylistLoader,
  21014. Playlist,
  21015. utils,
  21016. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  21017. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  21018. lastBandwidthSelector,
  21019. movingAverageBandwidthSelector,
  21020. comparePlaylistBandwidth,
  21021. comparePlaylistResolution,
  21022. xhr: xhrFactory()
  21023. }; // Define getter/setters for config properties
  21024. Object.keys(Config).forEach(prop => {
  21025. Object.defineProperty(Vhs, prop, {
  21026. get() {
  21027. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  21028. return Config[prop];
  21029. },
  21030. set(value) {
  21031. videojs.log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  21032. if (typeof value !== 'number' || value < 0) {
  21033. videojs.log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  21034. return;
  21035. }
  21036. Config[prop] = value;
  21037. }
  21038. });
  21039. });
  21040. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  21041. /**
  21042. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  21043. *
  21044. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  21045. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  21046. * @function handleVhsMediaChange
  21047. */
  21048. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  21049. const newPlaylist = playlistLoader.media();
  21050. let selectedIndex = -1;
  21051. for (let i = 0; i < qualityLevels.length; i++) {
  21052. if (qualityLevels[i].id === newPlaylist.id) {
  21053. selectedIndex = i;
  21054. break;
  21055. }
  21056. }
  21057. qualityLevels.selectedIndex_ = selectedIndex;
  21058. qualityLevels.trigger({
  21059. selectedIndex,
  21060. type: 'change'
  21061. });
  21062. };
  21063. /**
  21064. * Adds quality levels to list once playlist metadata is available
  21065. *
  21066. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  21067. * @param {Object} vhs Vhs object to listen to for media events.
  21068. * @function handleVhsLoadedMetadata
  21069. */
  21070. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  21071. vhs.representations().forEach(rep => {
  21072. qualityLevels.addQualityLevel(rep);
  21073. });
  21074. handleVhsMediaChange(qualityLevels, vhs.playlists);
  21075. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  21076. // as one do not cause exceptions.
  21077. Vhs.canPlaySource = function () {
  21078. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  21079. };
  21080. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  21081. if (!keySystemOptions) {
  21082. return keySystemOptions;
  21083. }
  21084. let codecs = {};
  21085. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  21086. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  21087. }
  21088. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  21089. codecs.audio = audioPlaylist.attributes.CODECS;
  21090. }
  21091. const videoContentType = getMimeForCodec(codecs.video);
  21092. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  21093. const keySystemContentTypes = {};
  21094. for (const keySystem in keySystemOptions) {
  21095. keySystemContentTypes[keySystem] = {};
  21096. if (audioContentType) {
  21097. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  21098. }
  21099. if (videoContentType) {
  21100. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  21101. } // Default to using the video playlist's PSSH even though they may be different, as
  21102. // videojs-contrib-eme will only accept one in the options.
  21103. //
  21104. // This shouldn't be an issue for most cases as early intialization will handle all
  21105. // unique PSSH values, and if they aren't, then encrypted events should have the
  21106. // specific information needed for the unique license.
  21107. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  21108. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  21109. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  21110. // so we need to prevent overwriting the URL entirely
  21111. if (typeof keySystemOptions[keySystem] === 'string') {
  21112. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  21113. }
  21114. }
  21115. return merge(keySystemOptions, keySystemContentTypes);
  21116. };
  21117. /**
  21118. * @typedef {Object} KeySystems
  21119. *
  21120. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  21121. * Note: not all options are listed here.
  21122. *
  21123. * @property {Uint8Array} [pssh]
  21124. * Protection System Specific Header
  21125. */
  21126. /**
  21127. * Goes through all the playlists and collects an array of KeySystems options objects
  21128. * containing each playlist's keySystems and their pssh values, if available.
  21129. *
  21130. * @param {Object[]} playlists
  21131. * The playlists to look through
  21132. * @param {string[]} keySystems
  21133. * The keySystems to collect pssh values for
  21134. *
  21135. * @return {KeySystems[]}
  21136. * An array of KeySystems objects containing available key systems and their
  21137. * pssh values
  21138. */
  21139. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  21140. return playlists.reduce((keySystemsArr, playlist) => {
  21141. if (!playlist.contentProtection) {
  21142. return keySystemsArr;
  21143. }
  21144. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  21145. const keySystemOptions = playlist.contentProtection[keySystem];
  21146. if (keySystemOptions && keySystemOptions.pssh) {
  21147. keySystemsObj[keySystem] = {
  21148. pssh: keySystemOptions.pssh
  21149. };
  21150. }
  21151. return keySystemsObj;
  21152. }, {});
  21153. if (Object.keys(keySystemsOptions).length) {
  21154. keySystemsArr.push(keySystemsOptions);
  21155. }
  21156. return keySystemsArr;
  21157. }, []);
  21158. };
  21159. /**
  21160. * Returns a promise that waits for the
  21161. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  21162. *
  21163. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  21164. * browsers.
  21165. *
  21166. * As per the above ticket, this is particularly important for Chrome, where, if
  21167. * unencrypted content is appended before encrypted content and the key session has not
  21168. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  21169. * during playback.
  21170. *
  21171. * @param {Object} player
  21172. * The player instance
  21173. * @param {Object[]} sourceKeySystems
  21174. * The key systems options from the player source
  21175. * @param {Object} [audioMedia]
  21176. * The active audio media playlist (optional)
  21177. * @param {Object[]} mainPlaylists
  21178. * The playlists found on the main playlist object
  21179. *
  21180. * @return {Object}
  21181. * Promise that resolves when the key session has been created
  21182. */
  21183. const waitForKeySessionCreation = ({
  21184. player,
  21185. sourceKeySystems,
  21186. audioMedia,
  21187. mainPlaylists
  21188. }) => {
  21189. if (!player.eme.initializeMediaKeys) {
  21190. return Promise.resolve();
  21191. } // TODO should all audio PSSH values be initialized for DRM?
  21192. //
  21193. // All unique video rendition pssh values are initialized for DRM, but here only
  21194. // the initial audio playlist license is initialized. In theory, an encrypted
  21195. // event should be fired if the user switches to an alternative audio playlist
  21196. // where a license is required, but this case hasn't yet been tested. In addition, there
  21197. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  21198. // languages).
  21199. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  21200. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  21201. const initializationFinishedPromises = [];
  21202. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  21203. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  21204. // return for IE11 above, and the existence of modern EME APIs in addition to
  21205. // ms-prefixed APIs on Edge should prevent this from being a concern.
  21206. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  21207. keySystemsOptionsArr.forEach(keySystemsOptions => {
  21208. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  21209. player.tech_.one('keysessioncreated', resolve);
  21210. }));
  21211. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  21212. player.eme.initializeMediaKeys({
  21213. keySystems: keySystemsOptions
  21214. }, err => {
  21215. if (err) {
  21216. reject(err);
  21217. return;
  21218. }
  21219. resolve();
  21220. });
  21221. }));
  21222. }); // The reasons Promise.race is chosen over Promise.any:
  21223. //
  21224. // * Promise.any is only available in Safari 14+.
  21225. // * None of these promises are expected to reject. If they do reject, it might be
  21226. // better here for the race to surface the rejection, rather than mask it by using
  21227. // Promise.any.
  21228. return Promise.race([// If a session was previously created, these will all finish resolving without
  21229. // creating a new session, otherwise it will take until the end of all license
  21230. // requests, which is why the key session check is used (to make setup much faster).
  21231. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  21232. Promise.race(keySessionCreatedPromises)]);
  21233. };
  21234. /**
  21235. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  21236. * there are keySystems on the source, sets up source options to prepare the source for
  21237. * eme.
  21238. *
  21239. * @param {Object} player
  21240. * The player instance
  21241. * @param {Object[]} sourceKeySystems
  21242. * The key systems options from the player source
  21243. * @param {Object} media
  21244. * The active media playlist
  21245. * @param {Object} [audioMedia]
  21246. * The active audio media playlist (optional)
  21247. *
  21248. * @return {boolean}
  21249. * Whether or not options were configured and EME is available
  21250. */
  21251. const setupEmeOptions = ({
  21252. player,
  21253. sourceKeySystems,
  21254. media,
  21255. audioMedia
  21256. }) => {
  21257. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  21258. if (!sourceOptions) {
  21259. return false;
  21260. }
  21261. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  21262. // do nothing.
  21263. if (sourceOptions && !player.eme) {
  21264. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  21265. return false;
  21266. }
  21267. return true;
  21268. };
  21269. const getVhsLocalStorage = () => {
  21270. if (!window$1.localStorage) {
  21271. return null;
  21272. }
  21273. const storedObject = window$1.localStorage.getItem(LOCAL_STORAGE_KEY);
  21274. if (!storedObject) {
  21275. return null;
  21276. }
  21277. try {
  21278. return JSON.parse(storedObject);
  21279. } catch (e) {
  21280. // someone may have tampered with the value
  21281. return null;
  21282. }
  21283. };
  21284. const updateVhsLocalStorage = options => {
  21285. if (!window$1.localStorage) {
  21286. return false;
  21287. }
  21288. let objectToStore = getVhsLocalStorage();
  21289. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  21290. try {
  21291. window$1.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  21292. } catch (e) {
  21293. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  21294. // storage is set to 0).
  21295. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  21296. // No need to perform any operation.
  21297. return false;
  21298. }
  21299. return objectToStore;
  21300. };
  21301. /**
  21302. * Parses VHS-supported media types from data URIs. See
  21303. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  21304. * for information on data URIs.
  21305. *
  21306. * @param {string} dataUri
  21307. * The data URI
  21308. *
  21309. * @return {string|Object}
  21310. * The parsed object/string, or the original string if no supported media type
  21311. * was found
  21312. */
  21313. const expandDataUri = dataUri => {
  21314. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  21315. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  21316. } // no known case for this data URI, return the string as-is
  21317. return dataUri;
  21318. };
  21319. /**
  21320. * Whether the browser has built-in HLS support.
  21321. */
  21322. Vhs.supportsNativeHls = function () {
  21323. if (!document || !document.createElement) {
  21324. return false;
  21325. }
  21326. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  21327. if (!videojs.getTech('Html5').isSupported()) {
  21328. return false;
  21329. } // HLS manifests can go by many mime-types
  21330. const canPlay = [// Apple santioned
  21331. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  21332. 'audio/mpegurl', // Very common
  21333. 'audio/x-mpegurl', // Very common
  21334. 'application/x-mpegurl', // Included for completeness
  21335. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  21336. return canPlay.some(function (canItPlay) {
  21337. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  21338. });
  21339. }();
  21340. Vhs.supportsNativeDash = function () {
  21341. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  21342. return false;
  21343. }
  21344. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  21345. }();
  21346. Vhs.supportsTypeNatively = type => {
  21347. if (type === 'hls') {
  21348. return Vhs.supportsNativeHls;
  21349. }
  21350. if (type === 'dash') {
  21351. return Vhs.supportsNativeDash;
  21352. }
  21353. return false;
  21354. };
  21355. /**
  21356. * VHS is a source handler, not a tech. Make sure attempts to use it
  21357. * as one do not cause exceptions.
  21358. */
  21359. Vhs.isSupported = function () {
  21360. return videojs.log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  21361. };
  21362. const Component = videojs.getComponent('Component');
  21363. /**
  21364. * The Vhs Handler object, where we orchestrate all of the parts
  21365. * of VHS to interact with video.js
  21366. *
  21367. * @class VhsHandler
  21368. * @extends videojs.Component
  21369. * @param {Object} source the soruce object
  21370. * @param {Tech} tech the parent tech object
  21371. * @param {Object} options optional and required options
  21372. */
  21373. class VhsHandler extends Component {
  21374. constructor(source, tech, options) {
  21375. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  21376. // use that over the VHS level `bandwidth` option
  21377. if (typeof options.initialBandwidth === 'number') {
  21378. this.options_.bandwidth = options.initialBandwidth;
  21379. }
  21380. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  21381. // so, get it from Video.js via the `playerId`
  21382. if (tech.options_ && tech.options_.playerId) {
  21383. const _player = videojs.getPlayer(tech.options_.playerId);
  21384. this.player_ = _player;
  21385. }
  21386. this.tech_ = tech;
  21387. this.source_ = source;
  21388. this.stats = {};
  21389. this.ignoreNextSeekingEvent_ = false;
  21390. this.setOptions_();
  21391. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  21392. tech.overrideNativeAudioTracks(true);
  21393. tech.overrideNativeVideoTracks(true);
  21394. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  21395. // overriding native VHS only works if audio tracks have been emulated
  21396. // error early if we're misconfigured
  21397. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  21398. } // listen for fullscreenchange events for this player so that we
  21399. // can adjust our quality selection quickly
  21400. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  21401. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  21402. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  21403. this.playlistController_.fastQualityChange_();
  21404. } else {
  21405. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  21406. // than full screen, see if there should be a rendition switch down to preserve
  21407. // bandwidth.
  21408. this.playlistController_.checkABR_();
  21409. }
  21410. });
  21411. this.on(this.tech_, 'seeking', function () {
  21412. if (this.ignoreNextSeekingEvent_) {
  21413. this.ignoreNextSeekingEvent_ = false;
  21414. return;
  21415. }
  21416. this.setCurrentTime(this.tech_.currentTime());
  21417. });
  21418. this.on(this.tech_, 'error', function () {
  21419. // verify that the error was real and we are loaded
  21420. // enough to have pc loaded.
  21421. if (this.tech_.error() && this.playlistController_) {
  21422. this.playlistController_.pauseLoading();
  21423. }
  21424. });
  21425. this.on(this.tech_, 'play', this.play);
  21426. }
  21427. setOptions_() {
  21428. // defaults
  21429. this.options_.withCredentials = this.options_.withCredentials || false;
  21430. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  21431. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  21432. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  21433. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  21434. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  21435. this.options_.customTagParsers = this.options_.customTagParsers || [];
  21436. this.options_.customTagMappers = this.options_.customTagMappers || [];
  21437. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  21438. this.options_.llhls = this.options_.llhls === false ? false : true;
  21439. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  21440. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  21441. this.options_.playlistExclusionDuration = 5 * 60;
  21442. }
  21443. if (typeof this.options_.bandwidth !== 'number') {
  21444. if (this.options_.useBandwidthFromLocalStorage) {
  21445. const storedObject = getVhsLocalStorage();
  21446. if (storedObject && storedObject.bandwidth) {
  21447. this.options_.bandwidth = storedObject.bandwidth;
  21448. this.tech_.trigger({
  21449. type: 'usage',
  21450. name: 'vhs-bandwidth-from-local-storage'
  21451. });
  21452. }
  21453. if (storedObject && storedObject.throughput) {
  21454. this.options_.throughput = storedObject.throughput;
  21455. this.tech_.trigger({
  21456. type: 'usage',
  21457. name: 'vhs-throughput-from-local-storage'
  21458. });
  21459. }
  21460. }
  21461. } // if bandwidth was not set by options or pulled from local storage, start playlist
  21462. // selection at a reasonable bandwidth
  21463. if (typeof this.options_.bandwidth !== 'number') {
  21464. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  21465. } // If the bandwidth number is unchanged from the initial setting
  21466. // then this takes precedence over the enableLowInitialPlaylist option
  21467. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  21468. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  21469. if (typeof this.source_[option] !== 'undefined') {
  21470. this.options_[option] = this.source_[option];
  21471. }
  21472. });
  21473. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  21474. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  21475. }
  21476. /**
  21477. * called when player.src gets called, handle a new source
  21478. *
  21479. * @param {Object} src the source object to handle
  21480. */
  21481. src(src, type) {
  21482. // do nothing if the src is falsey
  21483. if (!src) {
  21484. return;
  21485. }
  21486. this.setOptions_(); // add main playlist controller options
  21487. this.options_.src = expandDataUri(this.source_.src);
  21488. this.options_.tech = this.tech_;
  21489. this.options_.externVhs = Vhs;
  21490. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  21491. this.options_.seekTo = time => {
  21492. this.tech_.setCurrentTime(time);
  21493. };
  21494. this.playlistController_ = new PlaylistController(this.options_);
  21495. const playbackWatcherOptions = merge({
  21496. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  21497. }, this.options_, {
  21498. seekable: () => this.seekable(),
  21499. media: () => this.playlistController_.media(),
  21500. playlistController: this.playlistController_
  21501. });
  21502. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  21503. this.playlistController_.on('error', () => {
  21504. const player = videojs.players[this.tech_.options_.playerId];
  21505. let error = this.playlistController_.error;
  21506. if (typeof error === 'object' && !error.code) {
  21507. error.code = 3;
  21508. } else if (typeof error === 'string') {
  21509. error = {
  21510. message: error,
  21511. code: 3
  21512. };
  21513. }
  21514. player.error(error);
  21515. });
  21516. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  21517. // compatibility with < v2
  21518. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  21519. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  21520. this.playlists = this.playlistController_.mainPlaylistLoader_;
  21521. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  21522. // controller. Using a custom property for backwards compatibility
  21523. // with < v2
  21524. Object.defineProperties(this, {
  21525. selectPlaylist: {
  21526. get() {
  21527. return this.playlistController_.selectPlaylist;
  21528. },
  21529. set(selectPlaylist) {
  21530. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  21531. }
  21532. },
  21533. throughput: {
  21534. get() {
  21535. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  21536. },
  21537. set(throughput) {
  21538. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  21539. // for the cumulative average
  21540. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  21541. }
  21542. },
  21543. bandwidth: {
  21544. get() {
  21545. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  21546. const networkInformation = window$1.navigator.connection || window$1.navigator.mozConnection || window$1.navigator.webkitConnection;
  21547. const tenMbpsAsBitsPerSecond = 10e6;
  21548. if (this.options_.useNetworkInformationApi && networkInformation) {
  21549. // downlink returns Mbps
  21550. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  21551. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  21552. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  21553. // high quality streams are not filtered out.
  21554. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  21555. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  21556. } else {
  21557. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  21558. }
  21559. }
  21560. return playerBandwidthEst;
  21561. },
  21562. set(bandwidth) {
  21563. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  21564. // `count` is set to zero that current value of `rate` isn't included
  21565. // in the cumulative average
  21566. this.playlistController_.mainSegmentLoader_.throughput = {
  21567. rate: 0,
  21568. count: 0
  21569. };
  21570. }
  21571. },
  21572. /**
  21573. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  21574. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  21575. * the entire process after that - decryption, transmuxing, and appending - provided
  21576. * by `throughput`.
  21577. *
  21578. * Since the two process are serial, the overall system bandwidth is given by:
  21579. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  21580. */
  21581. systemBandwidth: {
  21582. get() {
  21583. const invBandwidth = 1 / (this.bandwidth || 1);
  21584. let invThroughput;
  21585. if (this.throughput > 0) {
  21586. invThroughput = 1 / this.throughput;
  21587. } else {
  21588. invThroughput = 0;
  21589. }
  21590. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  21591. return systemBitrate;
  21592. },
  21593. set() {
  21594. videojs.log.error('The "systemBandwidth" property is read-only');
  21595. }
  21596. }
  21597. });
  21598. if (this.options_.bandwidth) {
  21599. this.bandwidth = this.options_.bandwidth;
  21600. }
  21601. if (this.options_.throughput) {
  21602. this.throughput = this.options_.throughput;
  21603. }
  21604. Object.defineProperties(this.stats, {
  21605. bandwidth: {
  21606. get: () => this.bandwidth || 0,
  21607. enumerable: true
  21608. },
  21609. mediaRequests: {
  21610. get: () => this.playlistController_.mediaRequests_() || 0,
  21611. enumerable: true
  21612. },
  21613. mediaRequestsAborted: {
  21614. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  21615. enumerable: true
  21616. },
  21617. mediaRequestsTimedout: {
  21618. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  21619. enumerable: true
  21620. },
  21621. mediaRequestsErrored: {
  21622. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  21623. enumerable: true
  21624. },
  21625. mediaTransferDuration: {
  21626. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  21627. enumerable: true
  21628. },
  21629. mediaBytesTransferred: {
  21630. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  21631. enumerable: true
  21632. },
  21633. mediaSecondsLoaded: {
  21634. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  21635. enumerable: true
  21636. },
  21637. mediaAppends: {
  21638. get: () => this.playlistController_.mediaAppends_() || 0,
  21639. enumerable: true
  21640. },
  21641. mainAppendsToLoadedData: {
  21642. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  21643. enumerable: true
  21644. },
  21645. audioAppendsToLoadedData: {
  21646. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  21647. enumerable: true
  21648. },
  21649. appendsToLoadedData: {
  21650. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  21651. enumerable: true
  21652. },
  21653. timeToLoadedData: {
  21654. get: () => this.playlistController_.timeToLoadedData_() || 0,
  21655. enumerable: true
  21656. },
  21657. buffered: {
  21658. get: () => timeRangesToArray(this.tech_.buffered()),
  21659. enumerable: true
  21660. },
  21661. currentTime: {
  21662. get: () => this.tech_.currentTime(),
  21663. enumerable: true
  21664. },
  21665. currentSource: {
  21666. get: () => this.tech_.currentSource_,
  21667. enumerable: true
  21668. },
  21669. currentTech: {
  21670. get: () => this.tech_.name_,
  21671. enumerable: true
  21672. },
  21673. duration: {
  21674. get: () => this.tech_.duration(),
  21675. enumerable: true
  21676. },
  21677. main: {
  21678. get: () => this.playlists.main,
  21679. enumerable: true
  21680. },
  21681. playerDimensions: {
  21682. get: () => this.tech_.currentDimensions(),
  21683. enumerable: true
  21684. },
  21685. seekable: {
  21686. get: () => timeRangesToArray(this.tech_.seekable()),
  21687. enumerable: true
  21688. },
  21689. timestamp: {
  21690. get: () => Date.now(),
  21691. enumerable: true
  21692. },
  21693. videoPlaybackQuality: {
  21694. get: () => this.tech_.getVideoPlaybackQuality(),
  21695. enumerable: true
  21696. }
  21697. });
  21698. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  21699. this.tech_.on('bandwidthupdate', () => {
  21700. if (this.options_.useBandwidthFromLocalStorage) {
  21701. updateVhsLocalStorage({
  21702. bandwidth: this.bandwidth,
  21703. throughput: Math.round(this.throughput)
  21704. });
  21705. }
  21706. });
  21707. this.playlistController_.on('selectedinitialmedia', () => {
  21708. // Add the manual rendition mix-in to VhsHandler
  21709. renditionSelectionMixin(this);
  21710. });
  21711. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  21712. this.setupEme_();
  21713. }); // the bandwidth of the primary segment loader is our best
  21714. // estimate of overall bandwidth
  21715. this.on(this.playlistController_, 'progress', function () {
  21716. this.tech_.trigger('progress');
  21717. }); // In the live case, we need to ignore the very first `seeking` event since
  21718. // that will be the result of the seek-to-live behavior
  21719. this.on(this.playlistController_, 'firstplay', function () {
  21720. this.ignoreNextSeekingEvent_ = true;
  21721. });
  21722. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  21723. // this can occur if someone sets the src in player.ready(), for instance
  21724. if (!this.tech_.el()) {
  21725. return;
  21726. }
  21727. this.mediaSourceUrl_ = window$1.URL.createObjectURL(this.playlistController_.mediaSource);
  21728. this.tech_.src(this.mediaSourceUrl_);
  21729. }
  21730. createKeySessions_() {
  21731. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  21732. this.logger_('waiting for EME key session creation');
  21733. waitForKeySessionCreation({
  21734. player: this.player_,
  21735. sourceKeySystems: this.source_.keySystems,
  21736. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  21737. mainPlaylists: this.playlists.main.playlists
  21738. }).then(() => {
  21739. this.logger_('created EME key session');
  21740. this.playlistController_.sourceUpdater_.initializedEme();
  21741. }).catch(err => {
  21742. this.logger_('error while creating EME key session', err);
  21743. this.player_.error({
  21744. message: 'Failed to initialize media keys for EME',
  21745. code: 3
  21746. });
  21747. });
  21748. }
  21749. handleWaitingForKey_() {
  21750. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  21751. // the key is in the manifest. While this should've happened on initial source load, it
  21752. // may happen again in live streams where the keys change, and the manifest info
  21753. // reflects the update.
  21754. //
  21755. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  21756. // already requested keys for, we don't have to worry about this generating extraneous
  21757. // requests.
  21758. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  21759. this.createKeySessions_();
  21760. }
  21761. /**
  21762. * If necessary and EME is available, sets up EME options and waits for key session
  21763. * creation.
  21764. *
  21765. * This function also updates the source updater so taht it can be used, as for some
  21766. * browsers, EME must be configured before content is appended (if appending unencrypted
  21767. * content before encrypted content).
  21768. */
  21769. setupEme_() {
  21770. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  21771. const didSetupEmeOptions = setupEmeOptions({
  21772. player: this.player_,
  21773. sourceKeySystems: this.source_.keySystems,
  21774. media: this.playlists.media(),
  21775. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  21776. });
  21777. this.player_.tech_.on('keystatuschange', e => {
  21778. if (e.status !== 'output-restricted') {
  21779. return;
  21780. }
  21781. const mainPlaylist = this.playlistController_.main();
  21782. if (!mainPlaylist || !mainPlaylist.playlists) {
  21783. return;
  21784. }
  21785. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  21786. mainPlaylist.playlists.forEach(playlist => {
  21787. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  21788. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  21789. playlist.excludeUntil = Infinity;
  21790. excludedHDPlaylists.push(playlist);
  21791. }
  21792. }
  21793. });
  21794. if (excludedHDPlaylists.length) {
  21795. videojs.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
  21796. this.playlistController_.fastQualityChange_();
  21797. }
  21798. });
  21799. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  21800. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  21801. // promises.
  21802. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  21803. // If EME options were not set up, we've done all we could to initialize EME.
  21804. this.playlistController_.sourceUpdater_.initializedEme();
  21805. return;
  21806. }
  21807. this.createKeySessions_();
  21808. }
  21809. /**
  21810. * Initializes the quality levels and sets listeners to update them.
  21811. *
  21812. * @method setupQualityLevels_
  21813. * @private
  21814. */
  21815. setupQualityLevels_() {
  21816. const player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  21817. // or qualityLevels_ listeners have already been setup, do nothing.
  21818. if (!player || !player.qualityLevels || this.qualityLevels_) {
  21819. return;
  21820. }
  21821. this.qualityLevels_ = player.qualityLevels();
  21822. this.playlistController_.on('selectedinitialmedia', () => {
  21823. handleVhsLoadedMetadata(this.qualityLevels_, this);
  21824. });
  21825. this.playlists.on('mediachange', () => {
  21826. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  21827. });
  21828. }
  21829. /**
  21830. * return the version
  21831. */
  21832. static version() {
  21833. return {
  21834. '@videojs/http-streaming': version$4,
  21835. 'mux.js': version$3,
  21836. 'mpd-parser': version$2,
  21837. 'm3u8-parser': version$1,
  21838. 'aes-decrypter': version
  21839. };
  21840. }
  21841. /**
  21842. * return the version
  21843. */
  21844. version() {
  21845. return this.constructor.version();
  21846. }
  21847. canChangeType() {
  21848. return SourceUpdater.canChangeType();
  21849. }
  21850. /**
  21851. * Begin playing the video.
  21852. */
  21853. play() {
  21854. this.playlistController_.play();
  21855. }
  21856. /**
  21857. * a wrapper around the function in PlaylistController
  21858. */
  21859. setCurrentTime(currentTime) {
  21860. this.playlistController_.setCurrentTime(currentTime);
  21861. }
  21862. /**
  21863. * a wrapper around the function in PlaylistController
  21864. */
  21865. duration() {
  21866. return this.playlistController_.duration();
  21867. }
  21868. /**
  21869. * a wrapper around the function in PlaylistController
  21870. */
  21871. seekable() {
  21872. return this.playlistController_.seekable();
  21873. }
  21874. /**
  21875. * Abort all outstanding work and cleanup.
  21876. */
  21877. dispose() {
  21878. if (this.playbackWatcher_) {
  21879. this.playbackWatcher_.dispose();
  21880. }
  21881. if (this.playlistController_) {
  21882. this.playlistController_.dispose();
  21883. }
  21884. if (this.qualityLevels_) {
  21885. this.qualityLevels_.dispose();
  21886. }
  21887. if (this.tech_ && this.tech_.vhs) {
  21888. delete this.tech_.vhs;
  21889. }
  21890. if (this.mediaSourceUrl_ && window$1.URL.revokeObjectURL) {
  21891. window$1.URL.revokeObjectURL(this.mediaSourceUrl_);
  21892. this.mediaSourceUrl_ = null;
  21893. }
  21894. if (this.tech_) {
  21895. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  21896. }
  21897. super.dispose();
  21898. }
  21899. convertToProgramTime(time, callback) {
  21900. return getProgramTime({
  21901. playlist: this.playlistController_.media(),
  21902. time,
  21903. callback
  21904. });
  21905. } // the player must be playing before calling this
  21906. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  21907. return seekToProgramTime({
  21908. programTime,
  21909. playlist: this.playlistController_.media(),
  21910. retryCount,
  21911. pauseAfterSeek,
  21912. seekTo: this.options_.seekTo,
  21913. tech: this.options_.tech,
  21914. callback
  21915. });
  21916. }
  21917. }
  21918. /**
  21919. * The Source Handler object, which informs video.js what additional
  21920. * MIME types are supported and sets up playback. It is registered
  21921. * automatically to the appropriate tech based on the capabilities of
  21922. * the browser it is running in. It is not necessary to use or modify
  21923. * this object in normal usage.
  21924. */
  21925. const VhsSourceHandler = {
  21926. name: 'videojs-http-streaming',
  21927. VERSION: version$4,
  21928. canHandleSource(srcObj, options = {}) {
  21929. const localOptions = merge(videojs.options, options);
  21930. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  21931. },
  21932. handleSource(source, tech, options = {}) {
  21933. const localOptions = merge(videojs.options, options);
  21934. tech.vhs = new VhsHandler(source, tech, localOptions);
  21935. tech.vhs.xhr = xhrFactory();
  21936. tech.vhs.src(source.src, source.type);
  21937. return tech.vhs;
  21938. },
  21939. canPlayType(type, options) {
  21940. const simpleType = simpleTypeFromSourceType(type);
  21941. if (!simpleType) {
  21942. return '';
  21943. }
  21944. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  21945. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  21946. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  21947. return canUseMsePlayback ? 'maybe' : '';
  21948. },
  21949. getOverrideNative(options = {}) {
  21950. const {
  21951. vhs = {}
  21952. } = options;
  21953. const defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  21954. const {
  21955. overrideNative = defaultOverrideNative
  21956. } = vhs;
  21957. return overrideNative;
  21958. }
  21959. };
  21960. /**
  21961. * Check to see if the native MediaSource object exists and supports
  21962. * an MP4 container with both H.264 video and AAC-LC audio.
  21963. *
  21964. * @return {boolean} if native media sources are supported
  21965. */
  21966. const supportsNativeMediaSources = () => {
  21967. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  21968. }; // register source handlers with the appropriate techs
  21969. if (supportsNativeMediaSources()) {
  21970. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  21971. }
  21972. videojs.VhsHandler = VhsHandler;
  21973. videojs.VhsSourceHandler = VhsSourceHandler;
  21974. videojs.Vhs = Vhs;
  21975. if (!videojs.use) {
  21976. videojs.registerComponent('Vhs', Vhs);
  21977. }
  21978. videojs.options.vhs = videojs.options.vhs || {};
  21979. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  21980. videojs.registerPlugin('reloadSourceOnError', reloadSourceOnError);
  21981. }
  21982. export { LOCAL_STORAGE_KEY, Vhs, VhsHandler, VhsSourceHandler, emeKeySystems, expandDataUri, getAllPsshKeySystemsOptions, setupEmeOptions, waitForKeySessionCreation };